id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,831
|
viewerplaybacktimer.cpp
|
olive-editor_olive/app/widget/viewer/viewerplaybacktimer.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "viewerplaybacktimer.h"
#include <QDateTime>
#include <QtMath>
namespace olive {
void ViewerPlaybackTimer::Start(const int64_t &start_timestamp, const int &playback_speed, const double &timebase)
{
start_msec_ = QDateTime::currentMSecsSinceEpoch();
start_timestamp_ = start_timestamp;
playback_speed_ = playback_speed;
timebase_ = timebase * 1000;
}
int64_t ViewerPlaybackTimer::GetTimestampNow() const
{
int64_t real_time = QDateTime::currentMSecsSinceEpoch() - start_msec_;
int64_t frames_since_start = qFloor(static_cast<double>(real_time) / (timebase_));
return start_timestamp_ + frames_since_start * playback_speed_;
}
}
| 1,369
|
C++
|
.cpp
| 32
| 40.1875
| 114
| 0.769637
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,832
|
manageddisplay.cpp
|
olive-editor_olive/app/widget/manageddisplay/manageddisplay.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "manageddisplay.h"
#include <QHBoxLayout>
#include <QMessageBox>
#include "panel/panelmanager.h"
#include "render/opengl/openglrenderer.h"
#include "render/rendermanager.h"
namespace olive {
#define super QWidget
ManagedDisplayWidget::ManagedDisplayWidget(QWidget *parent) :
QWidget(parent),
color_manager_(nullptr),
color_service_(nullptr)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
// Create OpenGL widget
inner_widget_ = new ManagedDisplayWidgetOpenGL();
inner_widget_->setAttribute(Qt::WA_TranslucentBackground, false);
connect(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_),
&ManagedDisplayWidgetOpenGL::OnInit,
this, &ManagedDisplayWidget::OnInit, Qt::DirectConnection);
connect(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_),
&ManagedDisplayWidgetOpenGL::OnDestroy,
this, &ManagedDisplayWidget::OnDestroy, Qt::DirectConnection);
connect(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_),
&ManagedDisplayWidgetOpenGL::OnPaint,
this, &ManagedDisplayWidget::OnPaint, Qt::DirectConnection);
connect(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_),
&ManagedDisplayWidgetOpenGL::frameSwapped,
this, &ManagedDisplayWidget::frameSwapped, Qt::DirectConnection);
inner_widget_->installEventFilter(this);
// Create OpenGL renderer
attached_renderer_ = new OpenGLRenderer(this);
// Create widget wrapper for OpenGL window
#ifdef USE_QOPENGLWINDOW
wrapper_ = QWidget::createWindowContainer(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_));
#else
wrapper_ = inner_widget_;
#endif
layout->addWidget(wrapper_);
} else {
inner_widget_ = nullptr;
wrapper_ = nullptr;
}
}
ManagedDisplayWidget::~ManagedDisplayWidget()
{
MANAGEDDISPLAYWIDGET_DEFAULT_DESTRUCTOR_INNER;
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
disconnect(static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_),
&ManagedDisplayWidgetOpenGL::OnDestroy,
this, &ManagedDisplayWidget::OnDestroy);
}
}
void ManagedDisplayWidget::ConnectColorManager(ColorManager *color_manager)
{
if (color_manager_ == color_manager) {
return;
}
if (color_manager_ != nullptr) {
disconnect(color_manager_, &ColorManager::ConfigChanged, this, &ManagedDisplayWidget::ColorConfigChanged);
disconnect(color_manager_, &ColorManager::ReferenceSpaceChanged, this, &ManagedDisplayWidget::ColorConfigChanged);
}
color_manager_ = color_manager;
if (color_manager_ != nullptr) {
connect(color_manager_, &ColorManager::ConfigChanged, this, &ManagedDisplayWidget::ColorConfigChanged);
connect(color_manager_, &ColorManager::ReferenceSpaceChanged, this, &ManagedDisplayWidget::ColorConfigChanged);
}
ColorConfigChanged();
emit ColorManagerChanged(color_manager_);
}
ColorManager *ManagedDisplayWidget::color_manager() const
{
return color_manager_;
}
void ManagedDisplayWidget::DisconnectColorManager()
{
ConnectColorManager(nullptr);
}
const ColorTransform &ManagedDisplayWidget::GetColorTransform() const
{
return color_transform_;
}
Menu *ManagedDisplayWidget::GetColorSpaceMenu(QMenu *parent, bool auto_connect)
{
QStringList colorspaces = color_manager()->ListAvailableColorspaces();
Menu* ocio_colorspace_menu = new Menu(tr("Color Space"), parent);
if (auto_connect) {
connect(ocio_colorspace_menu, &Menu::triggered, this, &ManagedDisplayWidget::MenuColorspaceSelect);
}
foreach (const QString& c, colorspaces) {
QAction* action = ocio_colorspace_menu->addAction(c);
action->setCheckable(true);
action->setChecked(color_transform_.output() == c);
action->setData(c);
}
return ocio_colorspace_menu;
}
void ManagedDisplayWidget::ColorConfigChanged()
{
if (!color_manager_) {
color_service_ = nullptr;
return;
}
SetColorTransform(color_manager_->GetCompliantColorSpace(color_transform_, false));
}
ColorProcessorPtr ManagedDisplayWidget::color_service()
{
return color_service_;
}
void ManagedDisplayWidget::ShowDefaultContextMenu()
{
Menu m(this);
if (color_manager_) {
m.addMenu(GetColorSpaceMenu(&m));
m.addSeparator();
m.addMenu(GetDisplayMenu(&m));
m.addMenu(GetViewMenu(&m));
m.addMenu(GetLookMenu(&m));
} else {
QAction* a = m.addAction(tr("No color manager connected"));
a->setEnabled(false);
}
m.exec(QCursor::pos());
}
void ManagedDisplayWidget::MenuDisplaySelect(QAction *action)
{
const ColorTransform& old_transform = GetColorTransform();
ColorTransform new_transform = color_manager()->GetCompliantColorSpace(ColorTransform(action->data().toString(),
old_transform.view(),
old_transform.look()));
SetColorTransform(new_transform);
}
void ManagedDisplayWidget::MenuViewSelect(QAction *action)
{
const ColorTransform& old_transform = GetColorTransform();
ColorTransform new_transform = color_manager()->GetCompliantColorSpace(ColorTransform(old_transform.display(),
action->data().toString(),
old_transform.look()));
SetColorTransform(new_transform);
}
void ManagedDisplayWidget::MenuLookSelect(QAction *action)
{
const ColorTransform& old_transform = GetColorTransform();
ColorTransform new_transform = color_manager()->GetCompliantColorSpace(ColorTransform(old_transform.display(),
old_transform.view(),
action->data().toString()));
SetColorTransform(new_transform);
}
void ManagedDisplayWidget::MenuColorspaceSelect(QAction *action)
{
SetColorTransform(color_manager()->GetCompliantColorSpace(ColorTransform(action->data().toString())));
}
void ManagedDisplayWidget::OnDestroy()
{
attached_renderer_->Destroy();
attached_renderer_->PostDestroy();
}
void ManagedDisplayWidget::SetColorTransform(const ColorTransform &transform)
{
color_transform_ = transform;
SetupColorProcessor();
ColorProcessorChangedEvent();
}
void ManagedDisplayWidget::OnInit()
{
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
QOpenGLContext* context = static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_)->context();
static_cast<OpenGLRenderer*>(attached_renderer_)->Init(context);
static_cast<OpenGLRenderer*>(attached_renderer_)->PostInit();
}
}
void ManagedDisplayWidget::EnableDefaultContextMenu()
{
connect(this, &ManagedDisplayWidget::customContextMenuRequested, this, &ManagedDisplayWidget::ShowDefaultContextMenu);
}
void ManagedDisplayWidget::ColorProcessorChangedEvent()
{
update();
}
void ManagedDisplayWidget::makeCurrent()
{
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_)->makeCurrent();
}
}
void ManagedDisplayWidget::doneCurrent()
{
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_)->doneCurrent();
}
}
QPaintDevice *ManagedDisplayWidget::paint_device() const
{
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
return static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_);
} else {
return nullptr;
}
}
void ManagedDisplayWidget::SetInnerMouseTracking(bool e)
{
if (wrapper_) {
wrapper_->setMouseTracking(e);
}
}
VideoParams ManagedDisplayWidget::GetViewportParams() const
{
int device_width = width() * devicePixelRatioF();
int device_height = height() * devicePixelRatioF();
PixelFormat device_format = static_cast<PixelFormat::Format>(OLIVE_CONFIG("OfflinePixelFormat").toInt());
return VideoParams(device_width, device_height, device_format, VideoParams::kInternalChannelCount);
}
void ManagedDisplayWidget::update()
{
if (RenderManager::instance()->backend() == RenderManager::kOpenGL) {
static_cast<ManagedDisplayWidgetOpenGL*>(inner_widget_)->update();
}
}
bool ManagedDisplayWidget::eventFilter(QObject *o, QEvent *e)
{
if (o != inner_widget_) {
return super::eventFilter(o, e);
}
switch (e->type()) {
case QEvent::FocusIn:
// HACK: QWindow focus isn't accounted for in QApplication::focusChanged, so we handle it
// manually here.
PanelManager::instance()->FocusChanged(nullptr, this);
break;
case QEvent::ContextMenu:
{
QContextMenuEvent *ctx = static_cast<QContextMenuEvent*>(e);
emit customContextMenuRequested(ctx->pos());
return true;
}
case QEvent::MouseButtonPress:
{
// HACK: QWindows don't seem to receive ContextMenu events on right click (only when pressing
// the menu button on the keyboard) so we handle it manually here
/*QMouseEvent *ev = static_cast<QMouseEvent*>(e);
if (ev->button() == Qt::RightButton) {
emit customContextMenuRequested(ev->pos());
return true;
}*/
break;
}
default:
break;
}
return super::eventFilter(o, e);
}
Menu* ManagedDisplayWidget::GetDisplayMenu(QMenu* parent, bool auto_connect)
{
QStringList displays = color_manager()->ListAvailableDisplays();
Menu* ocio_display_menu = new Menu(tr("Display"), parent);
if (auto_connect) {
connect(ocio_display_menu, &Menu::triggered, this, &ManagedDisplayWidget::MenuDisplaySelect);
}
foreach (const QString& d, displays) {
QAction* action = ocio_display_menu->addAction(d);
action->setCheckable(true);
action->setChecked(color_transform_.display() == d);
action->setData(d);
}
return ocio_display_menu;
}
Menu* ManagedDisplayWidget::GetViewMenu(QMenu* parent, bool auto_connect)
{
QStringList views = color_manager()->ListAvailableViews(color_transform_.display());
Menu* ocio_view_menu = new Menu(tr("View"), parent);
if (auto_connect) {
connect(ocio_view_menu, &Menu::triggered, this, &ManagedDisplayWidget::MenuViewSelect);
}
foreach (const QString& v, views) {
QAction* action = ocio_view_menu->addAction(v);
action->setCheckable(true);
action->setChecked(color_transform_.view() == v);
action->setData(v);
}
return ocio_view_menu;
}
Menu* ManagedDisplayWidget::GetLookMenu(QMenu* parent, bool auto_connect)
{
QStringList looks = color_manager()->ListAvailableLooks();
Menu* ocio_look_menu = new Menu(tr("Look"), parent);
if (auto_connect) {
connect(ocio_look_menu, &Menu::triggered, this, &ManagedDisplayWidget::MenuLookSelect);
}
// Setup "no look" action
QAction* no_look_action = ocio_look_menu->addAction(tr("(None)"));
no_look_action->setCheckable(true);
no_look_action->setChecked(color_transform_.look().isEmpty());
no_look_action->setData(QString());
// Set up the rest of the looks
foreach (const QString& l, looks) {
QAction* action = ocio_look_menu->addAction(l);
action->setCheckable(true);
action->setChecked(color_transform_.look() == l);
action->setData(l);
}
return ocio_look_menu;
}
void ManagedDisplayWidget::SetupColorProcessor()
{
color_service_ = nullptr;
if (color_manager_) {
// (Re)create color processor
try {
color_service_ = ColorProcessor::Create(color_manager_,
color_manager_->GetReferenceColorSpace(),
color_transform_);
} catch (OCIO::Exception& e) {
QMessageBox::critical(this,
tr("OpenColorIO Error"),
tr("Failed to set color configuration: %1").arg(e.what()),
QMessageBox::Ok);
}
} else {
color_service_ = nullptr;
}
emit ColorProcessorChanged(color_service_);
}
}
| 12,948
|
C++
|
.cpp
| 340
| 32.617647
| 120
| 0.704215
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,833
|
curveview.cpp
|
olive-editor_olive/app/widget/curvewidget/curveview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "curveview.h"
#include <cfloat>
#include <QHash>
#include <QMouseEvent>
#include <QPainterPath>
#include <QScrollBar>
#include <QtMath>
#include "common/decibel.h"
#include "common/qtutils.h"
#include "node/nodeundo.h"
#include "widget/keyframeview/keyframeviewundo.h"
namespace olive {
#define super KeyframeView
CurveView::CurveView(QWidget *parent) :
KeyframeView(parent),
dragging_bezier_pt_(nullptr)
{
setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
SetYAxisEnabled(true);
SetAutoSelectSiblings(false);
text_padding_ = QtUtils::QFontMetricsWidth(fontMetrics(), QStringLiteral("i"));
minimum_grid_space_ = QtUtils::QFontMetricsWidth(fontMetrics(), QStringLiteral("00000"));
}
void CurveView::ConnectInput(const NodeKeyframeTrackReference& ref)
{
if (connected_inputs_.contains(ref)) {
// Input wasn't connected, do nothing
return;
}
// Add keyframes from track
KeyframeViewInputConnection *track_con = AddKeyframesOfTrack(ref);
track_con->SetBrush(keyframe_colors_.value(ref));
track_connections_.insert(ref, track_con);
// Signal to CurveWidget to update its bezier/linear/hold buttons if a key type changes
connect(track_con, &KeyframeViewInputConnection::TypeChanged, this, &CurveView::SelectionChanged);
// Append to the list
connected_inputs_.append(ref);
}
void CurveView::DisconnectInput(const NodeKeyframeTrackReference& ref)
{
if (!connected_inputs_.contains(ref)) {
// Input wasn't connected, do nothing
return;
}
// Remove keyframes belonging to this element and track
RemoveKeyframesOfTrack(track_connections_.take(ref));
// Remove from the list
connected_inputs_.removeOne(ref);
}
void CurveView::SelectKeyframesOfInput(const NodeKeyframeTrackReference& ref)
{
DeselectAll();
foreach (KeyframeViewInputConnection *con, track_connections_) {
foreach (NodeKeyframe *key, con->GetKeyframes()) {
SelectKeyframe(key);
}
}
}
void CurveView::SetKeyframeTrackColor(const NodeKeyframeTrackReference &ref, const QColor &color)
{
// Insert color into hashmap
keyframe_colors_.insert(ref, color);
if (KeyframeViewInputConnection *con = track_connections_.value(ref)) {
// Update all keyframes
con->SetBrush(color);
}
}
void CurveView::drawBackground(QPainter *painter, const QRectF &rect)
{
if (timebase().isNull()) {
return;
}
painter->setRenderHint(QPainter::Antialiasing);
QVector<QLine> lines;
double x_interval = timebase().flipped().toDouble();
double y_interval = 100.0;
int x_grid_interval, y_grid_interval;
painter->setPen(QPen(palette().window().color(), 1));
do {
x_grid_interval = qRound(x_interval * GetScale() * timebase_dbl());
x_interval *= 2.0;
} while (x_grid_interval < minimum_grid_space_);
do {
y_grid_interval = qRound(y_interval * GetYScale());
y_interval *= 2.0;
} while (y_grid_interval < minimum_grid_space_);
int x_start = qCeil(rect.left() / x_grid_interval) * x_grid_interval;
int y_start = qCeil(rect.top() / y_grid_interval) * y_grid_interval;
QPointF scene_bottom_left = mapToScene(QPoint(0, qRound(rect.height())));
QPointF scene_top_right = mapToScene(QPoint(qRound(rect.width()), 0));
// Add vertical lines
for (int i=x_start;i<rect.right();i+=x_grid_interval) {
int value = qRound(static_cast<double>(i) / GetScale() / timebase_dbl());
painter->drawText(i + text_padding_, qRound(scene_bottom_left.y()) - text_padding_, QString::number(value));
lines.append(QLine(i, qRound(rect.top()), i, qRound(rect.bottom())));
}
// Add horizontal lines
for (int i=y_start;i<rect.bottom();i+=y_grid_interval) {
int value = qRound(static_cast<double>(i) / GetYScale());
painter->drawText(qRound(scene_bottom_left.x()) + text_padding_, i - text_padding_, QString::number(-value));
lines.append(QLine(qRound(rect.left()), i, qRound(rect.right()), i));
}
// Draw grid
painter->drawLines(lines);
// Draw keyframe lines
foreach (const NodeKeyframeTrackReference& ref, connected_inputs_) {
Node* node = ref.input().node();
const QString& input = ref.input().input();
if (node->IsInputKeyframing(input, ref.input().element())) {
const QVector<NodeKeyframeTrack>& tracks = node->GetKeyframeTracks(ref.input());
const NodeKeyframeTrack& track = tracks.at(ref.track());
if (!track.isEmpty()) {
painter->setPen(QPen(keyframe_colors_.value(ref),
qMax(1, fontMetrics().height() / 4)));
// Create a path
QPainterPath path;
// Draw straight line leading to first keyframe
QPointF first_key_pos = GetKeyframePosition(track.first());
path.moveTo(QPointF(scene_bottom_left.x(), first_key_pos.y()));
path.lineTo(first_key_pos);
// Draw lines between each keyframe
for (int i=1;i<track.size();i++) {
NodeKeyframe* before = track.at(i-1);
NodeKeyframe* after = track.at(i);
QPointF before_pos = GetKeyframePosition(before);
QPointF after_pos = GetKeyframePosition(after);
if (before->type() == NodeKeyframe::kHold) {
// Draw a hold keyframe (basically a right angle)
path.lineTo(after_pos.x(), before_pos.y());
path.lineTo(after_pos.x(), after_pos.y());
} else if (before->type() == NodeKeyframe::kBezier && after->type() == NodeKeyframe::kBezier) {
// Draw a cubic bezier
// Cubic beziers have two control points, so we can just use both
QPointF before_control_point = before_pos + ScalePoint(before->valid_bezier_control_out());
QPointF after_control_point = after_pos + ScalePoint(after->valid_bezier_control_in());
path.cubicTo(before_control_point, after_control_point, after_pos);
} else if (before->type() == NodeKeyframe::kBezier || after->type() == NodeKeyframe::kBezier) {
// Draw a quadratic bezier
// Quadratic beziers have a single control point, we just have to determine which it is
QPointF key_anchor;
QPointF control_point;
if (before->type() == NodeKeyframe::kBezier) {
key_anchor = before_pos;
control_point = before->valid_bezier_control_out();
} else {
key_anchor = after_pos;
control_point = after->valid_bezier_control_in();
}
// Scale control point
control_point = key_anchor + ScalePoint(control_point);
// Create the path from both keyframes
path.quadTo(control_point, after_pos);
} else {
// Linear to linear
path.lineTo(after_pos);
}
}
// Draw straight line leading from end keyframe
QPointF last_key_pos = GetKeyframePosition(track.last());
path.lineTo(QPointF(scene_top_right.x(), last_key_pos.y()));
painter->drawPath(path);
}
}
}
}
void CurveView::drawForeground(QPainter *painter, const QRectF &rect)
{
bezier_pts_.clear();
super::drawForeground(painter, rect);
}
void CurveView::ContextMenuEvent(Menu &m)
{
// View settings
QAction* zoom_fit_action = m.addAction(tr("Zoom to Fit"));
connect(zoom_fit_action, &QAction::triggered, this, &CurveView::ZoomToFit);
QAction* zoom_fit_selected_action = m.addAction(tr("Zoom to Fit Selected"));
connect(zoom_fit_selected_action, &QAction::triggered, this, &CurveView::ZoomToFitSelected);
QAction* reset_zoom_action = m.addAction(tr("Reset Zoom"));
connect(reset_zoom_action, &QAction::triggered, this, &CurveView::ResetZoom);
}
void CurveView::SceneRectUpdateEvent(QRectF &r)
{
double min_val, max_val;
bool got_val = false;
foreach (KeyframeViewInputConnection *con, track_connections_) {
foreach (NodeKeyframe *key, con->GetKeyframes()) {
qreal key_y = GetItemYFromKeyframeValue(key);
if (got_val) {
min_val = qMin(key_y, min_val);
max_val = qMax(key_y, max_val);
} else {
min_val = key_y;
max_val = key_y;
got_val = true;
}
}
}
if (got_val) {
r.setTop(min_val - this->height());
r.setBottom(max_val + this->height());
}
}
qreal CurveView::GetKeyframeSceneY(KeyframeViewInputConnection *track, NodeKeyframe *key)
{
return GetItemYFromKeyframeValue(key);
}
void CurveView::DrawKeyframe(QPainter *painter, NodeKeyframe *key, KeyframeViewInputConnection *track, const QRectF &key_rect)
{
if (IsKeyframeSelected(key) && key->type() == NodeKeyframe::kBezier) {
// Draw bezier control points if keyframe is selected
int control_point_size = QtUtils::QFontMetricsWidth(fontMetrics(), "o");
int half_sz = control_point_size / 2;
QRectF control_point_rect(-half_sz, -half_sz, control_point_size, control_point_size);
painter->setPen(palette().text().color());
painter->setBrush(Qt::NoBrush);
QRectF cp_in = control_point_rect.translated(key_rect.center() + ScalePoint(key->bezier_control_in()));
QRectF cp_out = control_point_rect.translated(key_rect.center() + ScalePoint(key->bezier_control_out()));
painter->drawLine(key_rect.center(), cp_in.center());
painter->drawLine(key_rect.center(), cp_out.center());
painter->drawEllipse(cp_in);
painter->drawEllipse(cp_out);
bezier_pts_.append({cp_in, key, NodeKeyframe::kInHandle});
bezier_pts_.append({cp_out, key, NodeKeyframe::kOutHandle});
}
super::DrawKeyframe(painter, key, track, key_rect);
}
bool CurveView::FirstChanceMousePress(QMouseEvent *event)
{
dragging_bezier_pt_ = nullptr;
QPointF scene_pt = mapToScene(event->pos());
foreach (const BezierPoint &b, bezier_pts_) {
if (b.rect.contains(scene_pt)) {
dragging_bezier_pt_ = &b;
break;
}
}
if (dragging_bezier_pt_) {
NodeKeyframe *key = dragging_bezier_pt_->keyframe;
dragging_bezier_point_start_ = (dragging_bezier_pt_->type == NodeKeyframe::kInHandle) ? key->bezier_control_in() : key->bezier_control_out();
dragging_bezier_point_opposing_start_ = (dragging_bezier_pt_->type == NodeKeyframe::kInHandle) ? key->bezier_control_out() : key->bezier_control_in();
drag_start_ = mapToScene(event->pos());
return true;
} else {
return false;
}
}
void CurveView::FirstChanceMouseMove(QMouseEvent *event)
{
// Calculate cursor difference and scale it
QPointF scene_pos = mapToScene(event->pos());
QPointF mouse_diff_scaled = GetScaledCursorPos(scene_pos - drag_start_);
if (event->modifiers() & Qt::ShiftModifier) {
// If holding shift, only move one axis
mouse_diff_scaled.setY(0);
}
// Flip the mouse Y because bezier control points are drawn bottom to top, not top to bottom
mouse_diff_scaled.setY(-mouse_diff_scaled.y());
QPointF new_bezier_pos = GenerateBezierControlPosition(dragging_bezier_pt_->type,
dragging_bezier_point_start_,
mouse_diff_scaled);
// If the user is NOT holding control, we set the other handle to the exact negative of this handle
QPointF new_opposing_pos;
NodeKeyframe::BezierType opposing_type = NodeKeyframe::get_opposing_bezier_type(dragging_bezier_pt_->type);
if (!(event->modifiers() & Qt::ControlModifier)) {
new_opposing_pos = GenerateBezierControlPosition(opposing_type,
dragging_bezier_point_opposing_start_,
-mouse_diff_scaled);
} else {
new_opposing_pos = dragging_bezier_point_opposing_start_;
}
dragging_bezier_pt_->keyframe->set_bezier_control(dragging_bezier_pt_->type,
new_bezier_pos);
dragging_bezier_pt_->keyframe->set_bezier_control(opposing_type,
new_opposing_pos);
Redraw();
}
void CurveView::FirstChanceMouseRelease(QMouseEvent *event)
{
MultiUndoCommand* command = new MultiUndoCommand();
// Create undo command with the current bezier point and the old one
command->add_child(new KeyframeSetBezierControlPoint(dragging_bezier_pt_->keyframe,
dragging_bezier_pt_->type,
dragging_bezier_pt_->keyframe->bezier_control(dragging_bezier_pt_->type),
dragging_bezier_point_start_));
if (!(event->modifiers() & Qt::ControlModifier)) {
auto opposing_type = NodeKeyframe::get_opposing_bezier_type(dragging_bezier_pt_->type);
command->add_child(new KeyframeSetBezierControlPoint(dragging_bezier_pt_->keyframe,
opposing_type,
dragging_bezier_pt_->keyframe->bezier_control(opposing_type),
dragging_bezier_point_opposing_start_));
}
dragging_bezier_pt_ = nullptr;
Core::instance()->undo_stack()->push(command, tr("Moved Keyframe Bezier Control Point"));
}
void CurveView::KeyframeDragStart(QMouseEvent *event)
{
drag_keyframe_values_.resize(GetSelectedKeyframes().size());
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
drag_keyframe_values_[i] = key->value();
}
drag_start_ = mapToScene(event->pos());
}
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 (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
key->set_value(drag_keyframe_values_.at(i));
}
return;
}
// Calculate cursor difference
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 (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
FloatSlider::DisplayType display = GetFloatDisplayTypeFromKeyframe(key);
Node* node = key->parent();
double original_val = FloatSlider::TransformValueToDisplay(drag_keyframe_values_.at(i).toDouble(), display);
const QString& input = key->input();
double new_val = FloatSlider::TransformDisplayToValue(original_val - scaled_diff, display);
double limited = new_val;
if (node->HasInputProperty(input, QStringLiteral("min"))) {
limited = qMax(limited, node->GetInputProperty(input, QStringLiteral("min")).toDouble());
}
if (node->HasInputProperty(input, QStringLiteral("max"))) {
limited = qMin(limited, node->GetInputProperty(input, QStringLiteral("max")).toDouble());
}
if (limited != new_val) {
scaled_diff = original_val - limited;
}
}
// Set values
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().front();
bool ok;
double num_value = tip_item->value().toDouble(&ok);
if (ok) {
tip = QStringLiteral("%1\n");
tip.append(FloatSlider::ValueToString(num_value + GetOffsetFromKeyframe(tip_item), GetFloatDisplayTypeFromKeyframe(tip_item), 2, true));
}
}
void CurveView::KeyframeDragRelease(QMouseEvent *event, MultiUndoCommand *command)
{
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)));
}
}
}
QPointF CurveView::GenerateBezierControlPosition(const NodeKeyframe::BezierType mode, const QPointF &start_point, const QPointF &scaled_cursor_diff)
{
QPointF new_bezier_pos = start_point;
new_bezier_pos += scaled_cursor_diff;
// LIMIT bezier handles from overlapping each other
if (mode == NodeKeyframe::kInHandle) {
if (new_bezier_pos.x() > 0) {
new_bezier_pos.setX(0);
}
} else {
if (new_bezier_pos.x() < 0) {
new_bezier_pos.setX(0);
}
}
return new_bezier_pos;
}
QPointF CurveView::GetScaledCursorPos(const QPointF &cursor_pos)
{
return QPointF(cursor_pos.x() / GetScale(),
cursor_pos.y() / GetYScale());
}
void CurveView::ZoomToFitInternal(bool selected_only)
{
bool got_val = false;
rational min_time, max_time;
double min_val, max_val;
foreach (KeyframeViewInputConnection *con, track_connections_) {
foreach (NodeKeyframe *key, con->GetKeyframes()) {
if (!selected_only || IsKeyframeSelected(key)) {
rational transformed_time = GetAdjustedTime(key->parent(),
GetTimeTarget(),
key->time(),
Node::kTransformTowardsOutput);
qreal key_y = GetUnscaledItemYFromKeyframeValue(key);
if (got_val) {
min_time = qMin(transformed_time, min_time);
max_time = qMax(transformed_time, max_time);
min_val = qMin(key_y, min_val);
max_val = qMax(key_y, max_val);
} else {
min_time = transformed_time;
max_time = transformed_time;
min_val = key_y;
max_val = key_y;
got_val = true;
}
}
}
}
// Prevent scaling if no keyframes were found
if (got_val) {
QRectF desired(QPointF(min_time.toDouble(), min_val), QPointF(max_time.toDouble(), max_val));
const double scale_divider = 0.5;
double scale_half_divider = scale_divider*0.5;
double new_x_scale = viewport()->width() / desired.width() * scale_divider;
double new_y_scale;
if (qFuzzyIsNull(desired.height())) {
// Catch divide by zero
new_y_scale = 1.0;
scale_half_divider = 0.5;
} else {
// Use height as normal
new_y_scale = viewport()->height() / desired.height() * scale_divider;
}
emit ScaleChanged(new_x_scale);
SetYScale(new_y_scale);
UpdateSceneRect();
int sb_x = desired.left() * new_x_scale - viewport()->width() * scale_half_divider;
QMetaObject::invokeMethod(horizontalScrollBar(), "setValue", Qt::QueuedConnection, Q_ARG(int, sb_x));
int sb_y = desired.top() * new_y_scale - viewport()->height() * scale_half_divider;
QMetaObject::invokeMethod(verticalScrollBar(), "setValue", Qt::QueuedConnection, Q_ARG(int, sb_y));
}
}
qreal CurveView::GetItemYFromKeyframeValue(NodeKeyframe *key)
{
return GetUnscaledItemYFromKeyframeValue(key) * GetYScale();
}
qreal CurveView::GetUnscaledItemYFromKeyframeValue(NodeKeyframe *key)
{
double val = key->value().toDouble();
val = FloatSlider::TransformValueToDisplay(val, GetFloatDisplayTypeFromKeyframe(key));
val += GetOffsetFromKeyframe(key);
return -val;
}
QPointF CurveView::ScalePoint(const QPointF &point)
{
// Flips Y coordinate because curves are drawn bottom to top
return QPointF(point.x() * GetScale(), - point.y() * GetYScale());
}
FloatSlider::DisplayType CurveView::GetFloatDisplayTypeFromKeyframe(NodeKeyframe *key)
{
Node* node = key->parent();
const QString& input = key->input();
if (node->HasInputProperty(input, QStringLiteral("view"))) {
// Try to get view from input (which will be normal if unset)
return static_cast<FloatSlider::DisplayType>(node->GetInputProperty(input, QStringLiteral("view")).toInt());
}
// Fallback to normal
return FloatSlider::kNormal;
}
double CurveView::GetOffsetFromKeyframe(NodeKeyframe *key)
{
Node *node = key->parent();
const QString &input = key->input();
if (node->HasInputProperty(input, QStringLiteral("offset"))) {
QVariant v = node->GetInputProperty(input, QStringLiteral("offset"));
// NOTE: Implement getting correct offset for the track based on the data type
QVector<QVariant> track_vals = NodeValue::split_normal_value_into_track_values(node->GetInputDataType(input), v);
return track_vals.at(key->track()).toDouble();
}
return 0;
}
QPointF CurveView::GetKeyframePosition(NodeKeyframe *key)
{
return QPointF(GetKeyframeSceneX(key), GetItemYFromKeyframeValue(key));
}
void CurveView::ZoomToFit()
{
ZoomToFitInternal(false);
}
void CurveView::ZoomToFitSelected()
{
ZoomToFitInternal(true);
}
void CurveView::ResetZoom()
{
emit ScaleChanged(1.0);
SetYScale(1.0);
}
}
| 21,651
|
C++
|
.cpp
| 501
| 36.944112
| 167
| 0.672682
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,834
|
curvewidget.cpp
|
olive-editor_olive/app/widget/curvewidget/curvewidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "curvewidget.h"
#include <QEvent>
#include <QLabel>
#include <QScrollBar>
#include <QSplitter>
#include <QVBoxLayout>
#include "core.h"
#include "common/qtutils.h"
#include "node/node.h"
#include "widget/keyframeview/keyframeviewundo.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
#define super TimeBasedWidget
CurveWidget::CurveWidget(QWidget *parent) :
super(parent)
{
QHBoxLayout* outer_layout = new QHBoxLayout(this);
QSplitter* splitter = new QSplitter();
outer_layout->addWidget(splitter);
tree_view_ = new NodeTreeView();
tree_view_->SetOnlyShowKeyframable(true);
tree_view_->SetShowKeyframeTracksAsRows(true);
connect(tree_view_, &NodeTreeView::InputSelectionChanged, this, &CurveWidget::InputSelectionChanged);
splitter->addWidget(tree_view_);
QWidget* workarea = new QWidget();
QVBoxLayout* layout = new QVBoxLayout(workarea);
layout->setContentsMargins(0, 0, 0, 0);
splitter->addWidget(workarea);
QHBoxLayout* top_controls = new QHBoxLayout();
key_control_ = new NodeParamViewKeyframeControl(false);
top_controls->addWidget(key_control_);
top_controls->addStretch();
linear_button_ = new QPushButton(tr("Linear"));
linear_button_->setCheckable(true);
linear_button_->setEnabled(false);
top_controls->addWidget(linear_button_);
connect(linear_button_, &QPushButton::clicked, this, &CurveWidget::KeyframeTypeButtonTriggered);
bezier_button_ = new QPushButton(tr("Bezier"));
bezier_button_->setCheckable(true);
bezier_button_->setEnabled(false);
top_controls->addWidget(bezier_button_);
connect(bezier_button_, &QPushButton::clicked, this, &CurveWidget::KeyframeTypeButtonTriggered);
hold_button_ = new QPushButton(tr("Hold"));
hold_button_->setCheckable(true);
hold_button_->setEnabled(false);
top_controls->addWidget(hold_button_);
connect(hold_button_, &QPushButton::clicked, this, &CurveWidget::KeyframeTypeButtonTriggered);
layout->addLayout(top_controls);
// We use a separate layout for the ruler+view combination so that there's no spacing between them
QVBoxLayout* ruler_view_layout = new QVBoxLayout();
ruler_view_layout->setContentsMargins(0, 0, 0, 0);
ruler_view_layout->setSpacing(0);
ruler_view_layout->addWidget(ruler());
view_ = new CurveView();
ConnectTimelineView(view_);
view_->SetSnapService(this);
ruler_view_layout->addWidget(view_);
layout->addLayout(ruler_view_layout);
// Connect ruler and view together
connect(view_, &CurveView::SelectionChanged, this, &CurveWidget::SelectionChanged);
connect(view_, &CurveView::Dragged, this, &CurveWidget::KeyframeViewDragged);
connect(view_, &CurveView::Released, this, &CurveWidget::KeyframeViewReleased);
// TimeBasedWidget's scrollbar has extra functionality that we can take advantage of
view_->setHorizontalScrollBar(scrollbar());
// Disable collapsing the main curve view (but allow collapsing the tree)
splitter->setCollapsible(1, false);
SetScale(120.0);
}
const double &CurveWidget::GetVerticalScale()
{
return view_->GetYScale();
}
void CurveWidget::SetVerticalScale(const double &vscale)
{
view_->SetYScale(vscale);
}
void CurveWidget::DeleteSelected()
{
view_->DeleteSelected();
}
Node *CurveWidget::GetSelectedNodeWithID(const QString &id)
{
for (auto it=view_->GetConnections().cbegin(); it!=view_->GetConnections().cend(); it++) {
Node *n = it.key().input().node();
if (n->id() == id) {
return n;
}
}
return nullptr;
}
bool CurveWidget::CopySelected(bool cut)
{
if (super::CopySelected(cut)) {
return true;
}
return view_->CopySelected(cut);
}
bool CurveWidget::Paste()
{
if (super::Paste()) {
return true;
}
return view_->Paste(std::bind(&CurveWidget::GetSelectedNodeWithID, this, std::placeholders::_1));
}
void CurveWidget::SetNodes(const QVector<Node *> &nodes)
{
tree_view_->SetNodes(nodes);
// Save new node list
nodes_ = nodes;
// Generate colors
foreach (Node *node, nodes_) {
foreach (const QString& input, node->inputs()) {
if (node->IsInputKeyframable(input) && !node->IsInputHidden(input)) {
int arr_sz = node->InputArraySize(input);
for (int i=-1; i<arr_sz; i++) {
// Generate a random color for this input
const QVector<NodeKeyframeTrack>& tracks = node->GetKeyframeTracks(input, i);
for (int j=0; j<tracks.size(); j++) {
NodeKeyframeTrackReference ref(NodeInput(node, input, i), j);
if (!keyframe_colors_.contains(ref)) {
QColor c = QColor::fromHsl(std::rand()%360, 255, 160);
keyframe_colors_.insert(ref, c);
tree_view_->SetKeyframeTrackColor(ref, c);
view_->SetKeyframeTrackColor(ref, c);
}
}
}
}
}
}
}
void CurveWidget::TimebaseChangedEvent(const rational &timebase)
{
super::TimebaseChangedEvent(timebase);
view_->SetTimebase(timebase);
}
void CurveWidget::ScaleChangedEvent(const double &scale)
{
super::ScaleChangedEvent(scale);
view_->SetScale(scale);
}
void CurveWidget::TimeTargetChangedEvent(ViewerOutput *target)
{
TimeTargetObject::TimeTargetChangedEvent(target);
key_control_->SetTimeTarget(target);
view_->SetTimeTarget(target);
}
void CurveWidget::ConnectedNodeChangeEvent(ViewerOutput *n)
{
super::ConnectedNodeChangeEvent(n);
key_control_->SetTimeTarget(n);
SetTimeTarget(n);
}
void CurveWidget::SetKeyframeButtonEnabled(bool enable)
{
linear_button_->setEnabled(enable);
bezier_button_->setEnabled(enable);
hold_button_->setEnabled(enable);
}
void CurveWidget::SetKeyframeButtonChecked(bool checked)
{
linear_button_->setChecked(checked);
bezier_button_->setChecked(checked);
hold_button_->setChecked(checked);
}
void CurveWidget::SetKeyframeButtonCheckedFromType(NodeKeyframe::Type type)
{
linear_button_->setChecked(type == NodeKeyframe::kLinear);
bezier_button_->setChecked(type == NodeKeyframe::kBezier);
hold_button_->setChecked(type == NodeKeyframe::kHold);
}
void CurveWidget::ConnectInput(Node *node, const QString &input, int element)
{
if (element == -1 && node->InputIsArray(input)) {
// This is the root element, connect all elements (if applicable)
int arr_sz = node->InputArraySize(input);
for (int i=-1; i<arr_sz; i++) {
ConnectInputInternal(node, input, i);
}
} else {
// This is a single element, just connect it as-is
ConnectInputInternal(node, input, element);
}
}
void CurveWidget::ConnectInputInternal(Node *node, const QString &input, int element)
{
NodeInput input_ref(node, input, element);
int track_count = NodeValue::get_number_of_keyframe_tracks(input_ref.GetDataType());
for (int i=0; i<track_count; i++) {
NodeKeyframeTrackReference track_ref(input_ref, i);
view_->ConnectInput(track_ref);
selected_tracks_.append(track_ref);
}
}
void CurveWidget::SelectionChanged()
{
const std::vector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
SetKeyframeButtonChecked(false);
SetKeyframeButtonEnabled(!selected.empty());
if (!selected.empty()) {
bool all_same_type = true;
NodeKeyframe::Type type = selected.front()->type();
for (size_t i=1;i<selected.size();i++) {
NodeKeyframe* prev_item = selected.at(i-1);
NodeKeyframe* this_item = selected.at(i);
if (prev_item->type() != this_item->type()) {
all_same_type = false;
break;
}
}
if (all_same_type) {
SetKeyframeButtonCheckedFromType(type);
}
}
}
void CurveWidget::KeyframeTypeButtonTriggered(bool checked)
{
QPushButton* key_btn = static_cast<QPushButton*>(sender());
if (!checked) {
// Keyframe buttons cannot be checked off, we undo this action here
key_btn->setChecked(true);
return;
}
// Get selected items and do nothing if there are none
const std::vector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
if (selected.empty()) {
return;
}
// Set all selected keyframes to this type
NodeKeyframe::Type new_type;
// Determine which type to set
if (key_btn == bezier_button_) {
new_type = NodeKeyframe::kBezier;
} else if (key_btn == hold_button_) {
new_type = NodeKeyframe::kHold;
} else {
new_type = NodeKeyframe::kLinear;
}
// Ensure only the appropriate button is checked
SetKeyframeButtonCheckedFromType(new_type);
MultiUndoCommand* command = new MultiUndoCommand();
foreach (NodeKeyframe* item, selected) {
command->add_child(new KeyframeSetTypeCommand(item, new_type));
}
Core::instance()->undo_stack()->push(command, tr("Changed Type of %1 Keyframe(s) to %2"));
}
void CurveWidget::InputSelectionChanged(const NodeKeyframeTrackReference& ref)
{
key_control_->SetInput(ref.input());
foreach (const NodeKeyframeTrackReference &c, selected_tracks_) {
view_->DisconnectInput(c);
}
selected_tracks_.clear();
if (ref.IsValid() && !ref.input().IsArray()) {
// This reference is a track, connect it only
view_->ConnectInput(ref);
selected_tracks_.append(ref);
} else if (ref.input().IsValid()) {
// This reference is a input, connect all tracks
ConnectInput(ref.input().node(), ref.input().input(), ref.input().element());
} else if (Node *node = ref.input().node()) {
// This is a node, add all inputs
foreach (const QString &input, node->inputs()) {
if (node->IsInputKeyframable(input) && !node->IsInputHidden(input)) {
ConnectInput(node, input, -1);
}
}
}
view_->ZoomToFit();
}
void CurveWidget::KeyframeViewDragged(int x, int y)
{
SetCatchUpScrollValue(x);
SetCatchUpScrollValue(view_->verticalScrollBar(), y, view_->height());
}
void CurveWidget::KeyframeViewReleased()
{
StopCatchUpScrollTimer();
StopCatchUpScrollTimer(view_->verticalScrollBar());
}
}
| 10,557
|
C++
|
.cpp
| 295
| 32.155932
| 103
| 0.720923
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,835
|
timelinewidget.cpp
|
olive-editor_olive/app/widget/timelinewidget/timelinewidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timelinewidget.h"
#include <cfloat>
#include <QSplitter>
#include <QVBoxLayout>
#include <QtMath>
#include "core.h"
#include "common/range.h"
#include "dialog/sequence/sequence.h"
#include "dialog/speedduration/speeddurationdialog.h"
#include "node/block/transition/transition.h"
#include "node/nodeundo.h"
#include "node/project/serializer/serializer.h"
#include "task/project/import/import.h"
#include "timeline/timelineundogeneral.h"
#include "timeline/timelineundopointer.h"
#include "timeline/timelineundoripple.h"
#include "timeline/timelineundoworkarea.h"
#include "tool/add.h"
#include "tool/beam.h"
#include "tool/edit.h"
#include "tool/pointer.h"
#include "tool/razor.h"
#include "tool/record.h"
#include "tool/ripple.h"
#include "tool/rolling.h"
#include "tool/slide.h"
#include "tool/slip.h"
#include "tool/trackselect.h"
#include "tool/transition.h"
#include "tool/zoom.h"
#include "tool/tool.h"
#include "trackview/trackview.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
#include "widget/nodeparamview/nodeparamview.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
#define super TimeBasedWidget
TimelineWidget::TimelineWidget(QWidget *parent) :
super(true, true, parent),
rubberband_(QRubberBand::Rectangle, this),
active_tool_(nullptr),
use_audio_time_units_(false),
subtitle_show_command_(nullptr),
subtitle_tentative_track_(nullptr)
{
QVBoxLayout* vert_layout = new QVBoxLayout(this);
vert_layout->setSpacing(0);
vert_layout->setContentsMargins(0, 0, 0, 0);
QHBoxLayout* ruler_and_time_layout = new QHBoxLayout();
vert_layout->addLayout(ruler_and_time_layout);
timecode_label_ = new RationalSlider();
timecode_label_->SetAlignment(Qt::AlignCenter);
timecode_label_->SetDisplayType(RationalSlider::kTime);
timecode_label_->setVisible(false);
timecode_label_->SetMinimum(0);
ruler_and_time_layout->addWidget(timecode_label_);
ruler_and_time_layout->addWidget(ruler());
ruler()->setFocusPolicy(Qt::TabFocus);
QWidget::setTabOrder(ruler(), timecode_label_);
// Create list of TimelineViews - these MUST correspond to the ViewType enum
view_splitter_ = new QSplitter(Qt::Vertical);
vert_layout->addWidget(view_splitter_);
// Video view
views_.append(AddTimelineAndTrackView(Qt::AlignBottom));
// Audio view
views_.append(AddTimelineAndTrackView(Qt::AlignTop));
// Subtitle view
views_.append(AddTimelineAndTrackView(Qt::AlignTop));
// Create tools
tools_.resize(olive::Tool::kCount);
tools_.fill(nullptr);
tools_.replace(olive::Tool::kPointer, new PointerTool(this));
tools_.replace(olive::Tool::kTrackSelect, new TrackSelectTool(this));
tools_.replace(olive::Tool::kEdit, new EditTool(this));
tools_.replace(olive::Tool::kRipple, new RippleTool(this));
tools_.replace(olive::Tool::kRolling, new RollingTool(this));
tools_.replace(olive::Tool::kRazor, new RazorTool(this));
tools_.replace(olive::Tool::kSlip, new SlipTool(this));
tools_.replace(olive::Tool::kSlide, new SlideTool(this));
tools_.replace(olive::Tool::kZoom, new ZoomTool(this));
tools_.replace(olive::Tool::kTransition, new TransitionTool(this));
tools_.replace(olive::Tool::kRecord, new RecordTool(this));
tools_.replace(olive::Tool::kAdd, new AddTool(this));
import_tool_ = new ImportTool(this);
// We add this to the list to make deleting all tools easier, it should never get accessed through the list under
// normal circumstances (but *technically* its index would be Tool::kCount)
tools_.append(import_tool_);
// Global scrollbar
connect(views_.first()->view()->horizontalScrollBar(), &QScrollBar::rangeChanged, scrollbar(), &QScrollBar::setRange);
vert_layout->addWidget(scrollbar());
foreach (TimelineAndTrackView* tview, views_) {
TimelineView* view = tview->view();
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->SetSnapService(this);
view->SetSelectionList(&selections_);
view->SetGhostList(&ghost_items_);
view_splitter_->addWidget(tview);
ConnectTimelineView(view);
connect(view, &TimelineView::customContextMenuRequested, this, &TimelineWidget::ShowContextMenu);
connect(view, &TimelineView::MousePressed, this, &TimelineWidget::ViewMousePressed);
connect(view, &TimelineView::MouseMoved, this, &TimelineWidget::ViewMouseMoved);
connect(view, &TimelineView::MouseReleased, this, &TimelineWidget::ViewMouseReleased);
connect(view, &TimelineView::MouseDoubleClicked, this, &TimelineWidget::ViewMouseDoubleClicked);
connect(view, &TimelineView::DragEntered, this, &TimelineWidget::ViewDragEntered);
connect(view, &TimelineView::DragMoved, this, &TimelineWidget::ViewDragMoved);
connect(view, &TimelineView::DragLeft, this, &TimelineWidget::ViewDragLeft);
connect(view, &TimelineView::DragDropped, this, &TimelineWidget::ViewDragDropped);
connect(tview->splitter(), &QSplitter::splitterMoved, this, &TimelineWidget::UpdateHorizontalSplitters);
}
// Split viewer 50/50
QList<int> view_sizes;
view_sizes.reserve(views_.size());
view_sizes.append(height()/2); // Video
view_sizes.append(height()/2); // Audio
view_sizes.append(0); // Subtitle (hidden by default)
view_splitter_->setSizes(view_sizes);
// Video and audio are not collapsible, subtitle is
view_splitter_->setCollapsible(Track::kVideo, false);
view_splitter_->setCollapsible(Track::kAudio, false);
view_splitter_->setCollapsible(Track::kSubtitle, true);
// FIXME: Magic number
SetScale(90.0);
SetAutoSetTimebase(false);
connect(Core::instance(), &Core::ToolChanged, this, &TimelineWidget::ToolChanged);
connect(Core::instance(), &Core::AddableObjectChanged, this, &TimelineWidget::AddableObjectChanged);
signal_block_change_timer_ = new QTimer(this);
signal_block_change_timer_->setInterval(1);
signal_block_change_timer_->setSingleShot(true);
connect(signal_block_change_timer_, &QTimer::timeout, this, [this]{
signal_block_change_timer_->stop();
if (OLIVE_CONFIG("SelectAlsoSeeks").toBool()) {
rational start = RATIONAL_MAX;
for (Block *b : selected_blocks_) {
start = std::min(start, b->in());
}
if (start != RATIONAL_MAX) {
GetConnectedNode()->SetPlayhead(start);
}
}
emit BlockSelectionChanged(selected_blocks_);
});
}
TimelineWidget::~TimelineWidget()
{
// Ensure no blocks are selected before any child widgets are destroyed (prevents corrupt ViewSelectionChanged() signal)
ConnectViewerNode(nullptr);
Clear();
qDeleteAll(tools_);
delete subtitle_show_command_;
}
void TimelineWidget::Clear()
{
// Emit that we've deselected any selected blocks
SignalDeselectedAllBlocks();
// Set null timebase
SetTimebase(0);
}
void TimelineWidget::TimebaseChangedEvent(const rational &timebase)
{
super::TimebaseChangedEvent(timebase);
timecode_label_->SetTimebase(timebase);
timecode_label_->setVisible(!timebase.isNull());
UpdateViewTimebases();
}
void TimelineWidget::resizeEvent(QResizeEvent *event)
{
super::resizeEvent(event);
// Update timecode label size
UpdateTimecodeWidthFromSplitters(views_.first()->splitter());
}
void TimelineWidget::TimeChangedEvent(const rational &t)
{
if (OLIVE_CONFIG("SeekAlsoSelects").toBool()) {
TimelineWidgetSelections sels;
QVector<Block*> new_blocks;
for (auto it=sequence()->GetTracks().cbegin(); it!=sequence()->GetTracks().cend(); it++) {
Track *track = *it;
if (track->IsLocked()) {
continue;
}
Block *b = track->VisibleBlockAtTime(sequence()->GetPlayhead());
if (!b || dynamic_cast<GapBlock*>(b)) {
continue;
}
new_blocks.push_back(b);
sels[track->ToReference()].insert(b->range());
}
if (selected_blocks_ != new_blocks) {
selected_blocks_ = new_blocks;
SetSelections(sels, false);
SignalBlockSelectionChange();
}
}
}
void TimelineWidget::ScaleChangedEvent(const double &scale)
{
super::ScaleChangedEvent(scale);
foreach (TimelineAndTrackView* view, views_) {
view->view()->SetScale(scale);
}
if (rubberband_.isVisible()) {
QMetaObject::invokeMethod(this, &TimelineWidget::ForceUpdateRubberBand, Qt::QueuedConnection);
}
}
void TimelineWidget::ConnectNodeEvent(ViewerOutput *n)
{
Sequence* s = static_cast<Sequence*>(n);
connect(s, &Sequence::TrackAdded, this, &TimelineWidget::AddTrack);
connect(s, &Sequence::TrackRemoved, this, &TimelineWidget::RemoveTrack);
connect(s, &Sequence::FrameRateChanged, this, &TimelineWidget::FrameRateChanged);
connect(s, &Sequence::SampleRateChanged, this, &TimelineWidget::SampleRateChanged);
connect(timecode_label_, &RationalSlider::ValueChanged, s, &Sequence::SetPlayhead);
connect(s, &Sequence::PlayheadChanged, timecode_label_, &RationalSlider::SetValue);
timecode_label_->SetValue(s->GetPlayhead());
ruler()->SetPlaybackCache(n->video_frame_cache());
SetTimebase(n->GetVideoParams().frame_rate_as_time_base());
for (int i=0;i<views_.size();i++) {
Track::Type track_type = static_cast<Track::Type>(i);
TimelineView* view = views_.at(i)->view();
TrackList* track_list = s->track_list(track_type);
TrackView* track_view = views_.at(i)->track_view();
track_view->ConnectTrackList(track_list);
view->ConnectTrackList(track_list);
// Defer to the track to make all the block UI items necessary
const QVector<Track*> tracks = s->track_list(track_type)->GetTracks();
foreach (Track* track, tracks) {
AddTrack(track);
}
}
}
void TimelineWidget::DisconnectNodeEvent(ViewerOutput *n)
{
Sequence* s = static_cast<Sequence*>(n);
disconnect(s, &Sequence::TrackAdded, this, &TimelineWidget::AddTrack);
disconnect(s, &Sequence::TrackRemoved, this, &TimelineWidget::RemoveTrack);
disconnect(s, &Sequence::FrameRateChanged, this, &TimelineWidget::FrameRateChanged);
disconnect(s, &Sequence::SampleRateChanged, this, &TimelineWidget::SampleRateChanged);
disconnect(timecode_label_, &RationalSlider::ValueChanged, s, &Sequence::SetPlayhead);
DeselectAll();
foreach (Track* track, s->GetTracks()) {
RemoveTrack(track);
}
ruler()->SetPlaybackCache(nullptr);
SetTimebase(0);
Clear();
foreach (TimelineAndTrackView* tview, views_) {
tview->track_view()->DisconnectTrackList();
tview->view()->ConnectTrackList(nullptr);
}
}
void TimelineWidget::SendCatchUpScrollEvent()
{
super::SendCatchUpScrollEvent();
if (rubberband_.isVisible()) {
this->ForceUpdateRubberBand();
}
}
void TimelineWidget::SelectAll()
{
QVector<Block*> newly_selected_blocks;
foreach (Block* block, added_blocks_) {
if (!selected_blocks_.contains(block)) {
newly_selected_blocks.append(block);
AddSelection(block);
}
}
SignalSelectedBlocks(newly_selected_blocks, false);
}
void TimelineWidget::DeselectAll()
{
// Clear selections
selections_.clear();
// Update all viewports
UpdateViewports();
// Clear list and emit signal
SignalDeselectedAllBlocks();
}
void TimelineWidget::RippleToIn()
{
RippleTo(Timeline::kTrimIn);
}
void TimelineWidget::RippleToOut()
{
RippleTo(Timeline::kTrimOut);
}
void TimelineWidget::EditToIn()
{
EditTo(Timeline::kTrimIn);
}
void TimelineWidget::EditToOut()
{
EditTo(Timeline::kTrimOut);
}
void TimelineWidget::SplitAtPlayhead()
{
if (!GetConnectedNode()) {
return;
}
const rational &playhead_time = GetConnectedNode()->GetPlayhead();
QVector<Block*> selected_blocks = GetSelectedBlocks();
// Prioritize blocks that are selected and overlap the playhead
QVector<Block*> blocks_to_split;
QVector<bool> block_is_selected;
bool some_blocks_are_selected = false;
// Get all blocks at the playhead
foreach (Track* track, sequence()->GetTracks()) {
if (track->IsLocked()) {
continue;
}
Block* b = track->BlockContainingTime(playhead_time);
if (dynamic_cast<ClipBlock*>(b)) {
bool selected = false;
// See if this block is selected
foreach (Block* item, selected_blocks) {
if (item == b) {
some_blocks_are_selected = true;
selected = true;
break;
}
}
blocks_to_split.append(b);
block_is_selected.append(selected);
}
}
// If some blocks are selected, we prioritize those and don't split the blocks that aren't
if (some_blocks_are_selected) {
for (int i=0;i<block_is_selected.size();i++) {
if (!block_is_selected.at(i)) {
blocks_to_split.removeAt(i);
block_is_selected.removeAt(i);
i--;
}
}
}
if (!blocks_to_split.isEmpty()) {
Core::instance()->undo_stack()->push(new BlockSplitPreservingLinksCommand(blocks_to_split, {playhead_time}), tr("Split Clips At Playhead"));
}
}
void TimelineWidget::ReplaceBlocksWithGaps(const QVector<Block *> &blocks,
bool remove_from_graph,
MultiUndoCommand *command,
bool handle_transitions)
{
foreach (Block* b, blocks) {
if (dynamic_cast<GapBlock*>(b)) {
// No point in replacing a gap with a gap, and TrackReplaceBlockWithGapCommand will clear
// up any extraneous gaps
continue;
}
Track* original_track = b->track();
command->add_child(new TrackReplaceBlockWithGapCommand(original_track, b, handle_transitions));
if (remove_from_graph) {
command->add_child(new NodeRemoveWithExclusiveDependenciesAndDisconnect(b));
}
}
}
void TimelineWidget::DeleteSelected(bool ripple)
{
if (ruler()->HasItemsSelected()) {
ruler()->DeleteSelected();
return;
}
QVector<Block*> selected_list = GetSelectedBlocks();
// No-op if nothing is selected
if (selected_list.isEmpty()) {
return;
}
QVector<Block*> clips_to_delete;
QVector<TransitionBlock*> transitions_to_delete;
bool all_gaps = true;
foreach (Block* b, selected_list) {
if (!dynamic_cast<GapBlock*>(b)) {
all_gaps = false;
}
if (dynamic_cast<ClipBlock*>(b)) {
clips_to_delete.append(b);
} else if (dynamic_cast<TransitionBlock*>(b)) {
transitions_to_delete.append(static_cast<TransitionBlock*>(b));
}
}
if (all_gaps) {
ripple = true;
}
MultiUndoCommand* command = new MultiUndoCommand();
// Remove all selections
command->add_child(new SetSelectionsCommand(this, TimelineWidgetSelections(), GetSelections()));
// For transitions, remove them but extend their attached blocks to fill their place
foreach (TransitionBlock* transition, transitions_to_delete) {
TransitionRemoveCommand *trc = new TransitionRemoveCommand(transition, true);
// Perform the transition removal now so that replacing blocks with gaps below won't get confused
trc->redo_now();
command->add_child(trc);
}
// Replace clips with gaps (effectively deleting them)
ReplaceBlocksWithGaps(clips_to_delete, true, command, false);
// Insert ripple command now that it's all cleaned up gaps
TimelineRippleDeleteGapsAtRegionsCommand *ripple_command = nullptr;
rational new_playhead = RATIONAL_MAX;
if (ripple) {
TimelineRippleDeleteGapsAtRegionsCommand::RangeList range_list;
foreach (Block* b, selected_list) {
range_list.append({b->track(), b->range()});
new_playhead = qMin(new_playhead, b->in());
}
ripple_command = new TimelineRippleDeleteGapsAtRegionsCommand(sequence(), range_list);
command->add_child(ripple_command);
}
Core::instance()->undo_stack()->push(command, tr("Deleted Clips"));
// Ensures any current drag operations are cancelled
ClearGhosts();
if (ripple_command && ripple_command->HasCommands() && new_playhead != RATIONAL_MAX) {
GetConnectedNode()->SetPlayhead(new_playhead);
}
}
void TimelineWidget::IncreaseTrackHeight()
{
if (!GetConnectedNode()) {
return;
}
// Increase the height of each track by one "unit"
foreach (Track* t, sequence()->GetTracks()) {
t->SetTrackHeight(t->GetTrackHeight() + Track::kTrackHeightInterval);
}
}
void TimelineWidget::DecreaseTrackHeight()
{
if (!GetConnectedNode()) {
return;
}
// Decrease the height of each track by one "unit"
foreach (Track* t, sequence()->GetTracks()) {
t->SetTrackHeight(qMax(t->GetTrackHeight() - Track::kTrackHeightInterval, Track::kTrackHeightMinimum));
}
}
void TimelineWidget::InsertFootageAtPlayhead(const QVector<ViewerOutput*>& footage)
{
auto command = new MultiUndoCommand();
import_tool_->PlaceAt(footage, GetConnectedNode()->GetPlayhead(), true, command, 0, true);
Core::instance()->undo_stack()->push(command, tr("Inserted Footage At Playhead"));
}
void TimelineWidget::OverwriteFootageAtPlayhead(const QVector<ViewerOutput *> &footage)
{
auto command = new MultiUndoCommand();
import_tool_->PlaceAt(footage, GetConnectedNode()->GetPlayhead(), false, command, 0, true);
Core::instance()->undo_stack()->push(command, tr("Overwrote Footage At Playhead"));
}
void TimelineWidget::ToggleLinksOnSelected()
{
QVector<Node*> blocks;
bool link = true;
foreach (Block* item, GetSelectedBlocks()) {
// Only clips can be linked
if (!dynamic_cast<ClipBlock*>(item)) {
continue;
}
// Prioritize unlinking, if any block has links, assume we're unlinking
if (link && item->HasLinks()) {
link = false;
}
blocks.append(item);
}
if (blocks.isEmpty()) {
return;
}
Core::instance()->undo_stack()->push(new NodeLinkManyCommand(blocks, link), tr("Linked Clips"));
}
void TimelineWidget::AddDefaultTransitionsToSelected()
{
QVector<ClipBlock*> blocks;
foreach (Block* item, GetSelectedBlocks()) {
// Only clips can be linked
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(item)) {
blocks.append(clip);
}
}
if (!blocks.isEmpty()) {
Core::instance()->undo_stack()->push(new TimelineAddDefaultTransitionCommand(blocks, timebase()), tr("Added Default Transitions"));
}
}
bool TimelineWidget::CopySelected(bool cut)
{
if (super::CopySelected(cut)) {
return true;
}
if (!GetConnectedNode() || selected_blocks_.isEmpty()) {
return false;
}
QVector<Node*> selected_nodes;
foreach (Block* block, selected_blocks_) {
selected_nodes.append(block);
QVector<Node*> deps = block->GetDependencies();
foreach (Node* d, deps) {
if (!selected_nodes.contains(d)) {
selected_nodes.append(d);
}
}
}
ProjectSerializer::SaveData sdata(ProjectSerializer::kOnlyClips);
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")] = QString::fromStdString((block->in() - earliest_in).toString());
properties[block][QStringLiteral("track")] = block->track()->ToReference().ToString();
}
sdata.SetProperties(properties);
ProjectSerializer::Copy(sdata);
if (cut) {
DeleteSelected();
}
return true;
}
bool TimelineWidget::Paste()
{
// TimeRuler gets first chance (markers, etc.)
if (super::Paste()) {
return true;
}
// Ensure we have a connected node
if (!GetConnectedNode()) {
return false;
}
// Attempt regular clip pasting
if (PasteInternal(false)) {
return true;
}
// Give last chance to NodeParamView
return NodeParamView::Paste(this, std::bind(&TimelineWidget::GenerateExistingPasteMap, this, std::placeholders::_1));
}
void TimelineWidget::PasteInsert()
{
PasteInternal(true);
}
void TimelineWidget::DeleteInToOut(bool ripple)
{
if (!GetConnectedNode()
|| !GetConnectedNode()->GetWorkArea()->enabled()) {
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
if (ripple) {
command->add_child(new TimelineRippleRemoveAreaCommand(
sequence(),
GetConnectedNode()->GetWorkArea()->in(),
GetConnectedNode()->GetWorkArea()->out()));
} else {
QVector<Track*> unlocked_tracks = sequence()->GetUnlockedTracks();
foreach (Track* track, unlocked_tracks) {
GapBlock* gap = new GapBlock();
gap->set_length_and_media_out(GetConnectedNode()->GetWorkArea()->length());
command->add_child(new NodeAddCommand(static_cast<Project*>(track->parent()),
gap));
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(track->type()),
track->Index(),
gap,
GetConnectedNode()->GetWorkArea()->in()));
}
}
// Clear workarea after this
command->add_child(new WorkareaSetEnabledCommand(GetConnectedNode()->project(),
GetConnectedNode()->GetWorkArea(),
false));
if (ripple) {
GetConnectedNode()->SetPlayhead(GetConnectedNode()->GetWorkArea()->in());
}
Core::instance()->undo_stack()->push(command, tr("Deleted In To Out"));
}
void TimelineWidget::ToggleSelectedEnabled()
{
QVector<Block*> items = GetSelectedBlocks();
if (items.isEmpty()) {
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
foreach (Block* i, items) {
command->add_child(new BlockEnableDisableCommand(i,
!i->is_enabled()));
}
Core::instance()->undo_stack()->push(command, tr("Toggled Clips Enabled"));
}
void TimelineWidget::SetColorLabel(int index)
{
MultiUndoCommand *command = new MultiUndoCommand();
foreach (Block* b, selected_blocks_) {
command->add_child(new NodeOverrideColorCommand(b, index));
}
Core::instance()->undo_stack()->push(command, tr("Set Colors of %1 Clips").arg(selected_blocks_.size()));
}
void TimelineWidget::NudgeLeft()
{
if (GetConnectedNode()) {
NudgeInternal(-timebase());
}
}
void TimelineWidget::NudgeRight()
{
if (GetConnectedNode()) {
NudgeInternal(timebase());
}
}
void TimelineWidget::MoveInToPlayhead()
{
MoveToPlayheadInternal(false);
}
void TimelineWidget::MoveOutToPlayhead()
{
MoveToPlayheadInternal(true);
}
void TimelineWidget::ShowSpeedDurationDialogForSelectedClips()
{
QVector<ClipBlock*> clips;
foreach (Block *b, selected_blocks_) {
ClipBlock *c = dynamic_cast<ClipBlock*>(b);
if (c) {
clips.append(c);
}
}
if (!clips.isEmpty()) {
SpeedDurationDialog sdd(clips, timebase(), this);
sdd.exec();
}
}
void TimelineWidget::RecordingCallback(const QString &filename, const TimeRange &time, const Track::Reference &track)
{
ProjectImportTask task(GetConnectedNode()->project()->root(), {filename});
task.Start();
auto subimport_command = task.GetCommand();
if (task.GetImportedFootage().empty()) {
qCritical() << "Failed to import recorded audio file" << filename;
delete subimport_command;
} else {
subimport_command->redo_now();
auto import_command = new MultiUndoCommand();
import_command->add_child(subimport_command);
import_tool_->PlaceAt({task.GetImportedFootage().front()}, time.in(), false, import_command, track.index());
Core::instance()->undo_stack()->push(import_command, tr("Recorded Audio Clip"));
}
}
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::AddTentativeSubtitleTrack()
{
if (!subtitle_show_command_) {
// Determine if we need to do anything
QList<int> sz = view_splitter_->sizes();
bool should_adjust_splitter = (sz[Track::kSubtitle] == 0);
bool should_add_sub_track = (sequence() && sequence()->track_list(Track::kSubtitle)->GetTrackCount() == 0);
if (should_adjust_splitter || should_add_sub_track) {
// Create command
subtitle_show_command_ = new MultiUndoCommand();
if (should_adjust_splitter) {
sz[Track::kSubtitle] = height() / Track::kCount;
subtitle_show_command_->add_child(new SetSplitterSizesCommand(view_splitter_, sz));
}
if (should_add_sub_track) {
TimelineAddTrackCommand *track_add_cmd = new TimelineAddTrackCommand(sequence()->track_list(Track::kSubtitle));
subtitle_tentative_track_ = track_add_cmd->track();
subtitle_show_command_->add_child(track_add_cmd);
}
subtitle_show_command_->redo_now();
}
}
}
void TimelineWidget::NestSelectedClips()
{
if (!GetConnectedNode()) {
return;
}
QVector<Block*> blocks = this->selected_blocks_;
if (blocks.empty()) {
return;
}
QVector<Track::Reference> tracks(blocks.size());
QVector<TimeRange> times(blocks.size());
QVector<int> track_offset(Track::kCount, INT_MAX);
rational start_time = RATIONAL_MAX;
rational end_time = RATIONAL_MIN;
for (int i=0; i<blocks.size(); i++) {
Block *b = blocks.at(i);
Track::Reference tf = b->track()->ToReference();;
tracks[i] = tf;
times[i] = b->range();
int &to = track_offset[tf.type()];
to = std::min(to, tf.index());
start_time = std::min(start_time, b->in());
end_time = std::max(end_time, b->out());
}
auto move_to_nest_command = new MultiUndoCommand();
// Remove blocks from this sequence
ReplaceBlocksWithGaps(blocks, false, move_to_nest_command);
// Create new sequence
Project *project = this->GetConnectedNode()->project();
Sequence *nest = Core::CreateNewSequenceForProject(tr("Nested Sequence %1"), project);
nest->SetVideoParams(GetConnectedNode()->GetVideoParams());
nest->SetAudioParams(GetConnectedNode()->GetAudioParams());
move_to_nest_command->add_child(new NodeAddCommand(project, nest));
// Add to same folder
move_to_nest_command->add_child(new FolderAddChild(this->GetConnectedNode()->folder(), nest));
// Place blocks in new sequence
for (int i=0; i<blocks.size(); i++) {
Block *b = blocks.at(i);
const TimeRange &range = times.at(i);
Track::Reference track = tracks.at(i);
move_to_nest_command->add_child(new TrackPlaceBlockCommand(nest->track_list(track.type()),
track.index() - track_offset.at(track.type()),
b, range.in() - start_time));
}
// Do this command now, because we later do checks and actions that rely on these having been done
move_to_nest_command->redo_now();
auto meta_command = new MultiUndoCommand();
meta_command->add_child(move_to_nest_command);
// Find first free track index
bool empty = false;
int index = -1;
while (!empty) {
index++;
empty = true;
for (int i=0; i<Track::kCount; i++) {
if (track_offset.at(i) == INT_MAX) {
// No clips on this track
continue;
}
TrackList *list = sequence()->track_list(static_cast<Track::Type>(i));
if (index < list->GetTrackCount() && !list->GetTrackAt(index)->IsRangeFree(TimeRange(start_time, end_time))) {
empty = false;
break;
}
}
}
// Place new sequence in this sequence
import_tool_->PlaceAt({nest}, start_time, false, meta_command, index);
Core::instance()->undo_stack()->push(meta_command, tr("Nested Clips"));
}
void TimelineWidget::ClearTentativeSubtitleTrack()
{
if (subtitle_show_command_) {
subtitle_show_command_->undo_now();
delete subtitle_show_command_;
subtitle_show_command_ = nullptr;
subtitle_tentative_track_ = nullptr;
}
}
void TimelineWidget::InsertGapsAt(const rational &earliest_point, const rational &insert_length, MultiUndoCommand *command)
{
for (int i=0;i<Track::kCount;i++) {
command->add_child(new TrackListInsertGaps(sequence()->track_list(static_cast<Track::Type>(i)),
earliest_point,
insert_length));
}
}
Track *TimelineWidget::GetTrackFromReference(const Track::Reference &ref) const
{
return sequence()->track_list(ref.type())->GetTrackAt(ref.index());
}
int TimelineWidget::GetTrackY(const Track::Reference &ref)
{
return views_.at(ref.type())->view()->GetTrackY(ref.index());
}
int TimelineWidget::GetTrackHeight(const Track::Reference &ref)
{
return views_.at(ref.type())->view()->GetTrackHeight(ref.index());
}
void TimelineWidget::CenterOn(qreal scene_pos)
{
scrollbar()->setValue(qRound(scene_pos - scrollbar()->width()/2));
}
void TimelineWidget::ClearGhosts()
{
if (!ghost_items_.isEmpty()) {
foreach (TimelineViewGhostItem* ghost, ghost_items_) {
delete ghost;
}
ghost_items_.clear();
}
HideSnaps();
}
TimelineTool *TimelineWidget::GetActiveTool()
{
return tools_.at(Core::instance()->tool());
}
void TimelineWidget::ViewMousePressed(TimelineViewMouseEvent *event)
{
active_tool_ = GetActiveTool();
if (GetConnectedNode() && active_tool_ != nullptr) {
active_tool_->MousePress(event);
UpdateViewports();
}
if (event->GetButton() != Qt::LeftButton) {
// Suspend tool immediately if the cursor isn't the primary button
active_tool_->MouseRelease(event);
UpdateViewports();
active_tool_ = nullptr;
}
}
void TimelineWidget::ViewMouseMoved(TimelineViewMouseEvent *event)
{
if (GetConnectedNode()) {
if (active_tool_) {
active_tool_->MouseMove(event);
UpdateViewports();
SetCatchUpScrollValue(event->GetScreenPos().x());
} else {
// Mouse is not down, attempt a hover event
TimelineTool* hover_tool = GetActiveTool();
if (hover_tool) {
hover_tool->HoverMove(event);
}
}
}
}
void TimelineWidget::ViewMouseReleased(TimelineViewMouseEvent *event)
{
StopCatchUpScrollTimer();
if (active_tool_) {
if (GetConnectedNode()) {
active_tool_->MouseRelease(event);
UpdateViewports();
}
active_tool_ = nullptr;
}
}
void TimelineWidget::ViewMouseDoubleClicked(TimelineViewMouseEvent *event)
{
// kHand tool will return nullptr
if (!GetActiveTool()) {
// Only kHand should return a nullptr
Q_ASSERT(Core::instance()->tool() == olive::Tool::kHand);
return;
}
if (GetConnectedNode()) {
GetActiveTool()->MouseDoubleClick(event);
UpdateViewports();
}
}
void TimelineWidget::ViewDragEntered(TimelineViewMouseEvent *event)
{
import_tool_->DragEnter(event);
UpdateViewports();
}
void TimelineWidget::ViewDragMoved(TimelineViewMouseEvent *event)
{
import_tool_->DragMove(event);
UpdateViewports();
SetCatchUpScrollValue(event->GetScreenPos().x());
}
void TimelineWidget::ViewDragLeft(QDragLeaveEvent *event)
{
StopCatchUpScrollTimer();
import_tool_->DragLeave(event);
UpdateViewports();
}
void TimelineWidget::ViewDragDropped(TimelineViewMouseEvent *event)
{
StopCatchUpScrollTimer();
import_tool_->DragDrop(event);
UpdateViewports();
}
void TimelineWidget::AddBlock(Block *block)
{
// Set up clip with view parameters (clip item will automatically size its rect accordingly)
if (!added_blocks_.contains(block)) {
connect(block, &Block::LinksChanged, this, &TimelineWidget::BlockUpdated);
connect(block, &Block::LabelChanged, this, &TimelineWidget::BlockUpdated);
connect(block, &Block::ColorChanged, this, &TimelineWidget::BlockUpdated);
connect(block, &Block::EnabledChanged, this, &TimelineWidget::BlockUpdated);
connect(block, &Block::PreviewChanged, this, &TimelineWidget::BlockUpdated);
added_blocks_.append(block);
if (selections_[block->track()->ToReference()].contains(block->range()) && !selected_blocks_.contains(block)) {
selected_blocks_.append(block);
}
}
}
void TimelineWidget::RemoveBlock(Block *block)
{
// Disconnect all signals
disconnect(block, &Block::LinksChanged, this, &TimelineWidget::BlockUpdated);
disconnect(block, &Block::LabelChanged, this, &TimelineWidget::BlockUpdated);
disconnect(block, &Block::ColorChanged, this, &TimelineWidget::BlockUpdated);
disconnect(block, &Block::EnabledChanged, this, &TimelineWidget::BlockUpdated);
disconnect(block, &Block::PreviewChanged, this, &TimelineWidget::BlockUpdated);
// Take item from map
added_blocks_.removeOne(block);
// If selected, deselect it
int select_index = selected_blocks_.indexOf(block);
if (select_index > -1) {
selected_blocks_.removeAt(select_index);
RemoveSelection(block);
SignalBlockSelectionChange();
}
}
void TimelineWidget::AddTrack(Track *track)
{
foreach (Block* b, track->Blocks()) {
AddBlock(b);
}
connect(track, &Track::IndexChanged, this, &TimelineWidget::TrackUpdated);
connect(track, &Track::IndexChanged, this, &TimelineWidget::TrackIndexChanged);
connect(track, &Track::BlocksRefreshed, this, &TimelineWidget::TrackUpdated);
connect(track, &Track::TrackHeightChanged, this, &TimelineWidget::TrackUpdated);
connect(track, &Track::BlockAdded, this, &TimelineWidget::AddBlock);
connect(track, &Track::BlockRemoved, this, &TimelineWidget::RemoveBlock);
}
void TimelineWidget::RemoveTrack(Track *track)
{
disconnect(track, &Track::IndexChanged, this, &TimelineWidget::TrackUpdated);
disconnect(track, &Track::IndexChanged, this, &TimelineWidget::TrackIndexChanged);
disconnect(track, &Track::BlocksRefreshed, this, &TimelineWidget::TrackUpdated);
disconnect(track, &Track::TrackHeightChanged, this, &TimelineWidget::TrackUpdated);
disconnect(track, &Track::BlockAdded, this, &TimelineWidget::AddBlock);
disconnect(track, &Track::BlockRemoved, this, &TimelineWidget::RemoveBlock);
RemoveSelection(TimeRange(0, RATIONAL_MAX), track->ToReference());
foreach (Block* b, track->Blocks()) {
RemoveBlock(b);
}
}
void TimelineWidget::TrackUpdated()
{
UpdateViewports(static_cast<Track*>(sender())->type());
}
void TimelineWidget::BlockUpdated()
{
UpdateViewports(static_cast<Block*>(sender())->track()->type());
}
void TimelineWidget::UpdateHorizontalSplitters()
{
QSplitter* sender_splitter = static_cast<QSplitter*>(sender());
foreach (TimelineAndTrackView* tview, views_) {
QSplitter* recv_splitter = tview->splitter();
if (recv_splitter != sender_splitter) {
recv_splitter->blockSignals(true);
recv_splitter->setSizes(sender_splitter->sizes());
recv_splitter->blockSignals(false);
}
}
UpdateTimecodeWidthFromSplitters(sender_splitter);
}
void TimelineWidget::UpdateTimecodeWidthFromSplitters(QSplitter* s)
{
timecode_label_->setFixedWidth(s->sizes().first() + s->handleWidth());
}
void TimelineWidget::ShowContextMenu()
{
Menu menu(this);
QVector<Block*> selected = GetSelectedBlocks();
if (!selected.isEmpty()) {
MenuShared::instance()->AddItemsForEditMenu(&menu, true);
menu.addSeparator();
MenuShared::instance()->AddColorCodingMenu(&menu);
menu.addSeparator();
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(selected.first())) {
{
Menu *cache_menu = new Menu(tr("Cache"), &menu);
menu.addMenu(cache_menu);
QAction *autocache_action = cache_menu->addAction(tr("Auto-Cache"));
autocache_action->setCheckable(true);
autocache_action->setChecked(clip->IsAutocaching());
connect(autocache_action, &QAction::triggered, this, &TimelineWidget::SetSelectedClipsAutocaching);
cache_menu->addSeparator();
auto cache_clip = cache_menu->addAction(tr("Cache All"));
connect(cache_clip, &QAction::triggered, this, &TimelineWidget::CacheClips);
auto cache_inout = cache_menu->addAction(tr("Cache In/Out"));
connect(cache_inout, &QAction::triggered, this, &TimelineWidget::CacheClipsInOut);
auto cache_discard = cache_menu->addAction(tr("Discard"));
connect(cache_discard, &QAction::triggered, this, &TimelineWidget::CacheDiscard);
}
if (clip->connected_viewer()) {
QAction *reveal_in_footage_viewer = menu.addAction(tr("Reveal in Footage Viewer"));
reveal_in_footage_viewer->setData(reinterpret_cast<quintptr>(clip->connected_viewer()));
reveal_in_footage_viewer->setProperty("range", QVariant::fromValue(clip->media_range()));
connect(reveal_in_footage_viewer, &QAction::triggered, this, &TimelineWidget::RevealInFootageViewer);
QAction *reveal_in_project = menu.addAction(tr("Reveal in Project"));
reveal_in_project->setData(reinterpret_cast<quintptr>(clip->connected_viewer()));
connect(reveal_in_project, &QAction::triggered, this, &TimelineWidget::RevealInProject);
if (Sequence *sequence = dynamic_cast<Sequence*>(clip->connected_viewer())) {
QAction *multicam_enabled = menu.addAction(tr("Multi-Cam"));
multicam_enabled->setCheckable(true);
MultiCamNode *mcn = nullptr;
auto paths = clip->FindWaysNodeArrivesHere(sequence);
for (const NodeInput &i : paths) {
if ((mcn = dynamic_cast<MultiCamNode*>(i.node()))) {
break;
}
}
multicam_enabled->setChecked(mcn);
connect(multicam_enabled, &QAction::triggered, this, &TimelineWidget::MulticamEnabledTriggered);
}
}
}
menu.addSeparator();
QAction* properties_action = menu.addAction(tr("Properties"));
connect(properties_action, &QAction::triggered, this, &TimelineWidget::ShowSpeedDurationDialogForSelectedClips);
}
if (selected.isEmpty()) {
QAction* toggle_audio_units = menu.addAction(tr("Use Audio Time Units"));
toggle_audio_units->setCheckable(true);
toggle_audio_units->setChecked(use_audio_time_units_);
connect(toggle_audio_units, &QAction::triggered, this, &TimelineWidget::SetUseAudioTimeUnits);
{
Menu *thumbnail_menu = new Menu(tr("Show Thumbnails"), &menu);
menu.addMenu(thumbnail_menu);
thumbnail_menu->AddActionWithData(tr("Disabled"), Timeline::kThumbnailOff, OLIVE_CONFIG("TimelineThumbnailMode"));
thumbnail_menu->AddActionWithData(tr("Only At In Points"), Timeline::kThumbnailInOut, OLIVE_CONFIG("TimelineThumbnailMode"));
thumbnail_menu->AddActionWithData(tr("Enabled"), Timeline::kThumbnailOn, OLIVE_CONFIG("TimelineThumbnailMode"));
connect(thumbnail_menu, &Menu::triggered, this, &TimelineWidget::SetViewThumbnailsEnabled);
}
QAction* show_waveforms = menu.addAction(tr("Show Waveforms"));
show_waveforms->setCheckable(true);
show_waveforms->setChecked(OLIVE_CONFIG("TimelineWaveformMode").toInt() == Timeline::kWaveformsEnabled);
connect(show_waveforms, &QAction::triggered, this, &TimelineWidget::SetViewWaveformsEnabled);
menu.addSeparator();
QAction* properties_action = menu.addAction(tr("Properties"));
connect(properties_action, &QAction::triggered, this, &TimelineWidget::ShowSequenceDialog);
}
menu.exec(QCursor::pos());
}
void TimelineWidget::DeferredScrollAction()
{
scrollbar()->setValue(deferred_scroll_value_);
}
void TimelineWidget::ShowSequenceDialog()
{
if (!GetConnectedNode()) {
return;
}
SequenceDialog sd(sequence(), SequenceDialog::kExisting, this);
sd.exec();
}
void TimelineWidget::SetUseAudioTimeUnits(bool use)
{
use_audio_time_units_ = use;
// Update timebases
UpdateViewTimebases();
}
void TimelineWidget::ToolChanged()
{
HideSnaps();
SetViewBeamCursor(TimelineCoordinate(0, Track::kNone, -1));
SetViewTransitionOverlay(nullptr, nullptr);
AddableObjectChanged();
}
void TimelineWidget::AddableObjectChanged()
{
// Special cast for subtitle adding - ensure section is visible
if (Core::instance()->tool() == Tool::kAdd && Core::instance()->GetSelectedAddableObject() == Tool::kAddableSubtitle) {
AddTentativeSubtitleTrack();
} else {
ClearTentativeSubtitleTrack();
}
}
void TimelineWidget::SetViewWaveformsEnabled(bool e)
{
OLIVE_CONFIG("TimelineWaveformMode") = e ? Timeline::kWaveformsEnabled : Timeline::kWaveformsDisabled;
UpdateViewports();
}
void TimelineWidget::SetViewThumbnailsEnabled(QAction *action)
{
OLIVE_CONFIG("TimelineThumbnailMode") = action->data();
UpdateViewports();
}
void TimelineWidget::FrameRateChanged()
{
SetTimebase(GetConnectedNode()->GetVideoParams().frame_rate_as_time_base());
}
void TimelineWidget::SampleRateChanged()
{
UpdateViewTimebases();
}
void TimelineWidget::TrackIndexChanged(int old, int now)
{
Track* track = static_cast<Track*>(sender());
Track::Reference old_ref(track->type(), old);
Track::Reference new_ref(track->type(), now);
auto track_selections = selections_.take(old_ref);
if (!track_selections.isEmpty()) {
selections_.insert(new_ref, track_selections);
}
}
void TimelineWidget::SignalBlockSelectionChange()
{
signal_block_change_timer_->stop();
signal_block_change_timer_->start();
}
void TimelineWidget::RevealInFootageViewer()
{
QAction *a = static_cast<QAction*>(sender());
ViewerOutput *item_to_reveal = reinterpret_cast<ViewerOutput*>(a->data().value<quintptr>());
TimeRange r = a->property("range").value<TimeRange>();
emit RevealViewerInFootageViewer(item_to_reveal, r);
}
void TimelineWidget::RevealInProject()
{
QAction *a = static_cast<QAction*>(sender());
ViewerOutput *item_to_reveal = reinterpret_cast<ViewerOutput*>(a->data().value<quintptr>());
emit RevealViewerInProject(item_to_reveal);
}
void TimelineWidget::RenameSelectedBlocks()
{
MultiUndoCommand *command = new MultiUndoCommand();
QVector<Node*> nodes(selected_blocks_.size());
for (int i=0; i<nodes.size(); i++) {
nodes[i] = selected_blocks_[i];
}
Core::instance()->LabelNodes(nodes);
Core::instance()->undo_stack()->push(command, tr("Renamed %1 Clip(s)").arg(nodes.size()));
}
void TimelineWidget::TrackAboutToBeDeleted(Track *track)
{
if (track == subtitle_tentative_track_) {
// User is deleting the tentative subtitle track. Technically they shouldn't do this, but they
// might if they misinterpret it as permanent. If so, we handle it cleanly by pushing our
// command as if the action really were permanent.
Core::instance()->undo_stack()->push(TakeSubtitleSectionCommand(), tr("Created Subtitle Track"));
}
}
void TimelineWidget::SetSelectedClipsAutocaching(bool e)
{
MultiUndoCommand *command = new MultiUndoCommand();
for (Block *b : selected_blocks_) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(clip, ClipBlock::kAutoCacheInput)), e));
}
}
Core::instance()->undo_stack()->push(command, e ? tr("Enabled Auto-Caching On %1 Clip(s)").arg(selected_blocks_.size()) : tr("Disabled Auto-Caching On %1 Clip(s)").arg(selected_blocks_.size()));
}
void TimelineWidget::CacheClips()
{
for (Block *b : selected_blocks_) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
clip->RequestInvalidatedFromConnected(true);
}
}
}
void TimelineWidget::CacheClipsInOut()
{
if (!this->sequence() || !this->sequence()->GetWorkArea()->enabled()) {
return;
}
TimeTargetObject tto;
tto.SetTimeTarget(this->sequence());
const TimeRange &r = this->sequence()->GetWorkArea()->range();
for (Block *b : qAsConst(selected_blocks_)) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
if (Node *connected = clip->GetConnectedOutput(clip->kBufferIn)) {
TimeRange adjusted = tto.GetAdjustedTime(this->sequence(), connected, r, Node::kTransformTowardsInput);
clip->RequestInvalidatedFromConnected(true, adjusted);
}
}
}
}
void TimelineWidget::CacheDiscard()
{
if (QMessageBox::question(this, tr("Discard Cache"),
tr("This will discard all cache for this clip. "
"If the clip has auto-cache enabled, it will be recached immediately. "
"This cannot be undone.\n\n"
"Do you wish to continue?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
for (Block *b : selected_blocks_) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
clip->DiscardCache();
}
}
}
}
void TimelineWidget::MulticamEnabledTriggered(bool e)
{
MultiUndoCommand *command = new MultiUndoCommand();
for (Block *b : qAsConst(selected_blocks_)) {
if (ClipBlock *c = dynamic_cast<ClipBlock*>(b)) {
if (Sequence *s = dynamic_cast<Sequence*>(c->connected_viewer())) {
if (e) {
// Adding multicams
// Create multicam node and add it to the graph
MultiCamNode *n = new MultiCamNode();
n->SetSequenceType(c->GetTrackType());
command->add_child(new NodeAddCommand(s->parent(), n));
// For each output the sequence has to this clip, disconnect it and
// connect to the multicam instead
QVector<NodeInput> inputs = c->FindWaysNodeArrivesHere(s);
for (const NodeInput &i : inputs) {
command->add_child(new NodeEdgeRemoveCommand(s, i));
command->add_child(new NodeEdgeAddCommand(n, i));
}
command->add_child(new NodeEdgeAddCommand(s, NodeInput(n, n->kSequenceInput)));
// Move sequence node one unit back, and place multicam in sequence's spot
QPointF sequence_pos = c->GetNodePositionInContext(s);
command->add_child(new NodeSetPositionCommand(s, c, sequence_pos - QPointF(1, 0)));
command->add_child(new NodeSetPositionCommand(n, c, sequence_pos));
} else {
// Removing multicams
// Locate first multicam that specifically ends up at this clip
QVector<NodeInput> inputs = c->FindWaysNodeArrivesHere(s);
for (const NodeInput &i : inputs) {
if (MultiCamNode *mcn = dynamic_cast<MultiCamNode*>(i.node())) {
for (auto it=mcn->output_connections().cbegin(); it!=mcn->output_connections().cend(); it++) {
command->add_child(new NodeEdgeRemoveCommand(it->first, it->second));
command->add_child(new NodeEdgeAddCommand(s, it->second));
}
command->add_child(new NodeRemoveAndDisconnectCommand(mcn));
}
}
}
}
}
}
Core::instance()->undo_stack()->push(command, e ? tr("Multi-Cam Enabled On %1 Clip(s)").arg(selected_blocks_.size()) : tr("Multi-Cam Disabled On %1 Clip(s)").arg(selected_blocks_.size()));
}
void TimelineWidget::ForceUpdateRubberBand()
{
if (rubberband_.isVisible()) {
this->MoveRubberBandSelect(rubberband_enable_selecting_, rubberband_select_links_);
}
}
void TimelineWidget::AddGhost(TimelineViewGhostItem *ghost)
{
ghost_items_.append(ghost);
UpdateViewports(ghost->GetTrack().type());
}
void TimelineWidget::UpdateViewTimebases()
{
for (int i=0;i<views_.size();i++) {
TimelineAndTrackView* view = views_.at(i);
if (GetConnectedNode() && use_audio_time_units_ && i == Track::kAudio) {
view->view()->SetTimebase(GetConnectedNode()->GetAudioParams().sample_rate_as_time_base());
} else {
view->view()->SetTimebase(timebase());
}
}
}
void TimelineWidget::NudgeInternal(rational amount)
{
if (!selected_blocks_.isEmpty()) {
// Validate
foreach (Block* b, selected_blocks_) {
if (b->in() + amount < 0) {
amount = -b->in();
}
}
if (amount.isNull()) {
return;
}
MultiUndoCommand *command = new MultiUndoCommand();
foreach (Block* b, selected_blocks_) {
command->add_child(new TrackReplaceBlockWithGapCommand(b->track(), b, false));
}
foreach (Block* b, selected_blocks_) {
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(b->track()->type()), b->track()->Index(), b, b->in() + amount));
}
// Nudge selections
TimelineWidgetSelections new_sel = GetSelections();
new_sel.ShiftTime(amount);
command->add_child(new TimelineWidget::SetSelectionsCommand(this, new_sel, GetSelections()));
Core::instance()->undo_stack()->push(command, tr("Nudged Clips"));
}
}
void TimelineWidget::MoveToPlayheadInternal(bool out)
{
if (GetConnectedNode() && !selected_blocks_.isEmpty()) {
MultiUndoCommand *command = new MultiUndoCommand();
// Remove each block from the graph
QHash<Track*, rational> earliest_pts;
foreach (Block *b, selected_blocks_) {
command->add_child(new TrackReplaceBlockWithGapCommand(b->track(), b, false));
rational r = earliest_pts.value(b->track(), out ? RATIONAL_MIN : RATIONAL_MAX);
rational compare = out ? b->out() : b->in();
if ((compare < r) == !out) {
earliest_pts.insert(b->track(), compare);
}
}
foreach (Block *b, selected_blocks_) {
rational shift_amt = GetConnectedNode()->GetPlayhead() - earliest_pts.value(b->track());
rational new_in = b->in() + shift_amt;
bool can_shift = true;
if (new_in < 0) {
// Handle clips threatening to go below 0
rational new_out = new_in + b->length();
if (new_out <= 0) {
can_shift = false;
} else {
command->add_child(new BlockResizeWithMediaInCommand(b, new_out));
new_in = 0;
}
}
if (can_shift) {
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(b->track()->type()), b->track()->Index(), b, new_in));
}
}
// Shift selections
TimelineWidgetSelections new_sel = GetSelections();
for (auto it=new_sel.begin(); it!=new_sel.end(); it++) {
rational track_adj = GetConnectedNode()->GetPlayhead() - earliest_pts.value(GetTrackFromReference(it.key()), GetConnectedNode()->GetPlayhead());
if (!track_adj.isNull()) {
it.value().shift(track_adj);
}
}
command->add_child(new SetSelectionsCommand(this, new_sel, GetSelections()));
Core::instance()->undo_stack()->push(command, tr("Moved Clip(s) To Point"));
}
}
void TimelineWidget::SetViewBeamCursor(const TimelineCoordinate &coord)
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->SetBeamCursor(coord);
}
}
void TimelineWidget::SetViewTransitionOverlay(ClipBlock *out, ClipBlock *in)
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->SetTransitionOverlay(out, in);
}
}
void TimelineWidget::SetBlockLinksSelected(ClipBlock* block, bool selected)
{
foreach (Block* link, block->block_links()) {
if (selected) {
AddSelection(link);
} else {
RemoveSelection(link);
}
}
}
void TimelineWidget::QueueScroll(int value)
{
// (using a hacky singleShot so the scroll occurs after the scene and its scrollbars have updated)
deferred_scroll_value_ = value;
QTimer::singleShot(0, this, &TimelineWidget::DeferredScrollAction);
}
TimelineView *TimelineWidget::GetFirstTimelineView()
{
return views_.first()->view();
}
rational TimelineWidget::GetTimebaseForTrackType(Track::Type type)
{
return views_.at(type)->view()->timebase();
}
const QRect& TimelineWidget::GetRubberBandGeometry() const
{
return rubberband_.geometry();
}
void TimelineWidget::SignalSelectedBlocks(QVector<Block *> input, bool filter)
{
if (input.isEmpty()) {
return;
}
if (filter) {
// If filtering, remove all the blocks that are already selected
for (int i=0; i<input.size(); i++) {
Block* b = input.at(i);
if (selected_blocks_.contains(b)) {
input.removeAt(i);
i--;
}
}
}
selected_blocks_.append(input);
SignalBlockSelectionChange();
}
void TimelineWidget::SignalDeselectedBlocks(const QVector<Block *> &deselected_blocks)
{
if (deselected_blocks.isEmpty()) {
return;
}
foreach (Block* b, deselected_blocks) {
selected_blocks_.removeOne(b);
}
SignalBlockSelectionChange();
}
void TimelineWidget::SignalDeselectedAllBlocks()
{
if (!selected_blocks_.isEmpty()) {
selected_blocks_.clear();
SignalBlockSelectionChange();
}
}
QVector<Timeline::EditToInfo> TimelineWidget::GetEditToInfo(const rational& playhead_time,
Timeline::MovementMode mode)
{
// Get list of unlocked tracks
QVector<Track*> tracks = sequence()->GetUnlockedTracks();
// Create list to cache nearest times and the blocks at this point
QVector<Timeline::EditToInfo> info_list(tracks.size());
for (int i=0;i<tracks.size();i++) {
Timeline::EditToInfo &info = info_list[i];
Track* track = tracks.at(i);
info.track = track;
Block* b;
// Determine what block is at this time (for "trim in", we want to catch blocks that start at
// the time, for "trim out" we don't)
if (mode == Timeline::kTrimIn) {
b = track->NearestBlockBeforeOrAt(playhead_time);
} else {
b = track->NearestBlockBefore(playhead_time);
}
// If we have a block here, cache how close it is to the track
if (b) {
rational this_track_closest_point;
if (mode == Timeline::kTrimIn) {
this_track_closest_point = b->in();
} else {
this_track_closest_point = b->out();
}
info.nearest_time = this_track_closest_point;
}
info.nearest_block = b;
}
return info_list;
}
void TimelineWidget::RippleTo(Timeline::MovementMode mode)
{
if (!GetConnectedNode()) {
return;
}
rational playhead_time = GetConnectedNode()->GetPlayhead();
QVector<Timeline::EditToInfo> tracks = GetEditToInfo(playhead_time, mode);
if (tracks.isEmpty()) {
return;
}
// Find each track's nearest point and determine the overall timeline's nearest point
rational closest_point_to_playhead = (mode == Timeline::kTrimIn) ? RATIONAL_MIN : RATIONAL_MAX;
foreach (const Timeline::EditToInfo& info, tracks) {
if (info.nearest_block) {
if (mode == Timeline::kTrimIn) {
closest_point_to_playhead = qMax(info.nearest_time, closest_point_to_playhead);
} else {
closest_point_to_playhead = qMin(info.nearest_time, closest_point_to_playhead);
}
}
}
if (closest_point_to_playhead == RATIONAL_MIN || closest_point_to_playhead == RATIONAL_MAX) {
// Assume no blocks will be acted upon
return;
}
// If we're not inserting gaps and the edit point is right on the nearest in point, we enter a
// single-frame mode where we remove one frame only
if (closest_point_to_playhead == playhead_time) {
if (mode == Timeline::kTrimIn) {
playhead_time += timebase();
} else {
playhead_time -= timebase();
}
}
// For standard rippling, we can cache here the region that will be rippled out
rational in_ripple = qMin(closest_point_to_playhead, playhead_time);
rational out_ripple = qMax(closest_point_to_playhead, playhead_time);
TimelineRippleRemoveAreaCommand* c = new TimelineRippleRemoveAreaCommand(sequence(),
in_ripple,
out_ripple);
Core::instance()->undo_stack()->push(c, tr("Rippled Clip(s) To Point"));
// If we rippled, ump to where new cut is if applicable
if (mode == Timeline::kTrimIn) {
GetConnectedNode()->SetPlayhead(closest_point_to_playhead);
} else if (mode == Timeline::kTrimOut && closest_point_to_playhead == GetConnectedNode()->GetPlayhead()) {
GetConnectedNode()->SetPlayhead(playhead_time);
}
}
void TimelineWidget::EditTo(Timeline::MovementMode mode)
{
const rational playhead_time = GetConnectedNode()->GetPlayhead();
// Get list of unlocked tracks
QVector<Timeline::EditToInfo> tracks = GetEditToInfo(playhead_time, mode);
if (tracks.isEmpty()) {
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
foreach (const Timeline::EditToInfo& info, tracks) {
if (info.nearest_block
&& !dynamic_cast<GapBlock*>(info.nearest_block)
&& info.nearest_time != playhead_time) {
rational new_len;
if (mode == Timeline::kTrimIn) {
new_len = playhead_time - info.nearest_time;
} else {
new_len = info.nearest_time - playhead_time;
}
new_len = info.nearest_block->length() - new_len;
command->add_child(new BlockTrimCommand(info.track,
info.nearest_block,
new_len,
mode));
}
}
Core::instance()->undo_stack()->push(command, tr("Cut Clip(s) To Point"));
}
void TimelineWidget::UpdateViewports(const Track::Type &type)
{
if (type == Track::kNone) {
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->viewport()->update();
}
} else {
views_.at(type)->view()->viewport()->update();
}
}
bool TimelineWidget::PasteInternal(bool insert)
{
if (!GetConnectedNode()) {
return false;
}
ProjectSerializer::Result res = ProjectSerializer::Paste(ProjectSerializer::kOnlyClips, GetConnectedNode()->project());
if (res.GetLoadData().nodes.isEmpty()) {
return false;
}
MultiUndoCommand *command = new MultiUndoCommand();
Project *project = GetConnectedNode()->project();
foreach (Node *n, res.GetLoadData().nodes) {
command->add_child(new NodeAddCommand(project, n));
if (n->IsItem() && !n->folder()) {
command->add_child(new FolderAddChild(project->root(), n));
}
}
for (auto it = res.GetLoadData().promised_connections.cbegin(); it != res.GetLoadData().promised_connections.cend(); it++) {
auto oc = *it;
command->add_child(new NodeEdgeAddCommand(oc.first, oc.second));
}
rational paste_start = GetConnectedNode()->GetPlayhead();
if (insert) {
rational paste_end = paste_start;
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")].toStdString());
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")].toStdString());
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()->push(command, tr("Pasted %1 Clip(s)").arg(res.GetLoadData().properties.size()));
return true;
}
TimelineAndTrackView *TimelineWidget::AddTimelineAndTrackView(Qt::Alignment alignment)
{
TimelineAndTrackView *v = new TimelineAndTrackView(alignment);
connect(v->track_view(), &TrackView::AboutToDeleteTrack, this, &TimelineWidget::TrackAboutToBeDeleted);
return v;
}
QHash<Node *, Node *> TimelineWidget::GenerateExistingPasteMap(const ProjectSerializer::Result &r)
{
QHash<Node *, Node *> m;
for (Node *n : r.GetLoadData().nodes) {
for (Block *b : qAsConst(this->selected_blocks_)) {
for (auto it=b->GetContextPositions().cbegin(); it!=b->GetContextPositions().cend(); it++) {
if (it.key()->id() == n->id() && !m.contains(it.key())) {
m.insert(it.key(), n);
break;
}
}
}
}
return m;
}
QByteArray TimelineWidget::SaveSplitterState() const
{
return view_splitter_->saveState();
}
void TimelineWidget::RestoreSplitterState(const QByteArray &state)
{
view_splitter_->restoreState(state);
}
void TimelineWidget::StartRubberBandSelect(const QPoint &global_cursor_start)
{
// Store scene positions for each view
rubberband_scene_pos_.resize(views_.size());
for (int i = 0; i < rubberband_scene_pos_.size(); i++) {
TimelineView *v = views_.at(i)->view();
rubberband_scene_pos_[i] = v->UnscalePoint(v->mapToScene(v->mapFromGlobal(global_cursor_start)));
}
rubberband_.show();
// We don't touch any blocks that are already selected. If you want these to be deselected by
// default, call DeselectAll() before calling StartRubberBandSelect()
rubberband_old_selections_ = selections_;
}
void TimelineWidget::MoveRubberBandSelect(bool enable_selecting, bool select_links)
{
QPoint rubberband_now = QCursor::pos();
TimelineView *fv = views_.first()->view();
const QPointF &rubberband_scene_start = rubberband_scene_pos_.at(0);
QPointF rubberband_now_scaled = fv->UnscalePoint(fv->mapToScene(fv->mapFromGlobal(rubberband_now)));
QPoint rubberband_local_start = fv->mapTo(this, fv->mapFromScene(fv->ScalePoint(rubberband_scene_start)));
QPoint rubberband_local_now = fv->mapTo(this, fv->mapFromScene(fv->ScalePoint(rubberband_now_scaled)));
rubberband_.setGeometry(QRect(rubberband_local_start, rubberband_local_now).normalized());
rubberband_enable_selecting_ = enable_selecting;
rubberband_select_links_ = select_links;
if (!enable_selecting) {
return;
}
// Get current items in rubberband
QVector<Block*> items_in_rubberband;
for (int i = 0; i < views_.size(); i++) {
TimelineView *v = views_.at(i)->view();
QRectF r = QRectF(v->ScalePoint(rubberband_scene_pos_.at(i)), v->mapToScene(v->mapFromGlobal(rubberband_now))).normalized();
items_in_rubberband.append(v->GetItemsAtSceneRect(r));
}
// Reset selection to whatever it was before
SetSelections(rubberband_old_selections_, false);
// Add any blocks in rubberband
rubberband_now_selected_.clear();
foreach (Block* b, items_in_rubberband) {
if (dynamic_cast<GapBlock*>(b)) {
continue;
}
Track* t = b->track();
if (t->IsLocked()) {
continue;
}
if (!rubberband_now_selected_.contains(b)) {
AddSelection(b);
rubberband_now_selected_.append(b);
}
ClipBlock *c = dynamic_cast<ClipBlock*>(b);
if (c && select_links) {
foreach (Block* link, c->block_links()) {
if (!rubberband_now_selected_.contains(link)) {
AddSelection(link);
rubberband_now_selected_.append(link);
}
}
}
}
}
void TimelineWidget::EndRubberBandSelect()
{
rubberband_.hide();
// Emit any blocks that were newly selected
SignalSelectedBlocks(rubberband_now_selected_);
rubberband_now_selected_.clear();
rubberband_old_selections_.clear();
}
void TimelineWidget::AddSelection(const TimeRange &time, const Track::Reference &track)
{
selections_[track].insert(time);
UpdateViewports(track.type());
}
void TimelineWidget::AddSelection(Block *item)
{
if (item->track()) {
AddSelection(item->range(), item->track()->ToReference());
}
}
void TimelineWidget::RemoveSelection(const TimeRange &time, const Track::Reference &track)
{
selections_[track].remove(time);
UpdateViewports(track.type());
}
void TimelineWidget::RemoveSelection(Block *item)
{
if (item->track()) {
RemoveSelection(item->range(), item->track()->ToReference());
}
}
void TimelineWidget::SetSelections(const TimelineWidgetSelections &s, bool process_block_changes)
{
if (selections_ == s) {
return;
}
if (!GetConnectedNode()) {
return;
}
if (process_block_changes) {
QVector<Block*> deselected;
QVector<Block*> selected;
foreach (Block *b, selected_blocks_) {
if (!s[b->track()->ToReference()].contains(b->range())) {
deselected.append(b);
}
}
// NOTE: This loop could do with some optimization
for (auto it=s.cbegin(); it!=s.cend(); it++) {
Track *track = GetTrackFromReference(it.key());
if (track) {
const TimeRangeList &ranges = it.value();
foreach (Block *b, track->Blocks()) {
if (!selected_blocks_.contains(b) && ranges.contains(b->range())) {
selected.append(b);
}
}
}
}
SignalDeselectedBlocks(deselected);
SignalSelectedBlocks(selected);
}
selections_ = s;
UpdateViewports();
}
Block *TimelineWidget::GetItemAtScenePos(const TimelineCoordinate& coord)
{
return views_.at(coord.GetTrack().type())->view()->GetItemAtScenePos(coord.GetFrame(), coord.GetTrack().index());
}
void TimelineWidget::SetSplitterSizesCommand::redo()
{
old_sizes_ = splitter_->sizes();
splitter_->setSizes(new_sizes_);
}
void TimelineWidget::SetSplitterSizesCommand::undo()
{
splitter_->setSizes(old_sizes_);
}
}
| 65,960
|
C++
|
.cpp
| 1,735
| 33.148703
| 196
| 0.691569
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,836
|
timelinewidgetselections.cpp
|
olive-editor_olive/app/widget/timelinewidget/timelinewidgetselections.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timelinewidgetselections.h"
namespace olive {
void TimelineWidgetSelections::ShiftTime(const rational &diff)
{
for (auto it=this->begin(); it!=this->end(); it++) {
it.value().shift(diff);
}
}
void TimelineWidgetSelections::ShiftTracks(Track::Type type, int diff)
{
TimelineWidgetSelections cached_selections;
{
// Take all selections of this track type
auto it = this->begin();
while (it != this->end()) {
if (it.key().type() == type) {
cached_selections.insert(it.key(), it.value());
it = this->erase(it);
} else {
it++;
}
}
}
// Then re-insert them with the diff applied
for (auto it=cached_selections.cbegin(); it!=cached_selections.cend(); it++) {
Track::Reference ref(it.key().type(), it.key().index() + diff);
this->insert(ref, it.value());
}
}
void TimelineWidgetSelections::TrimIn(const rational &diff)
{
for (auto it=this->begin(); it!=this->end(); it++) {
it.value().trim_in(diff);
}
}
void TimelineWidgetSelections::TrimOut(const rational &diff)
{
for (auto it=this->begin(); it!=this->end(); it++) {
it.value().trim_out(diff);
}
}
void TimelineWidgetSelections::Subtract(const TimelineWidgetSelections &selections)
{
for (auto it=selections.cbegin(); it!=selections.cend(); it++) {
const Track::Reference &track = it.key();
const TimeRangeList &their_list = it.value();
if (this->contains(track)) {
TimeRangeList &our_list = (*this)[it.key()];
our_list.remove(their_list);
}
}
}
}
| 2,260
|
C++
|
.cpp
| 67
| 30.119403
| 83
| 0.690717
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,837
|
timelineandtrackview.cpp
|
olive-editor_olive/app/widget/timelinewidget/timelineandtrackview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timelineandtrackview.h"
#include <QHBoxLayout>
#include <QScrollBar>
namespace olive {
TimelineAndTrackView::TimelineAndTrackView(Qt::Alignment vertical_alignment, QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
splitter_ = new QSplitter(Qt::Horizontal);
splitter_->setChildrenCollapsible(false);
layout->addWidget(splitter_);
track_view_ = new TrackView(vertical_alignment);
splitter_->addWidget(track_view_);
view_ = new TimelineView(vertical_alignment);
splitter_->addWidget(view_);
connect(view_->verticalScrollBar(), &QScrollBar::valueChanged, this, &TimelineAndTrackView::ViewValueChanged);
connect(track_view_->verticalScrollBar(), &QScrollBar::valueChanged, this, &TimelineAndTrackView::TracksValueChanged);
splitter_->setSizes({1, width()});
}
QSplitter *TimelineAndTrackView::splitter() const
{
return splitter_;
}
TimelineView *TimelineAndTrackView::view() const
{
return view_;
}
TrackView *TimelineAndTrackView::track_view() const
{
return track_view_;
}
void TimelineAndTrackView::ViewValueChanged(int v)
{
track_view_->verticalScrollBar()->setValue(v - view_->verticalScrollBar()->minimum());
}
void TimelineAndTrackView::TracksValueChanged(int v)
{
view_->verticalScrollBar()->setValue(view_->verticalScrollBar()->minimum() + v);
}
}
| 2,121
|
C++
|
.cpp
| 56
| 35.410714
| 120
| 0.773105
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,838
|
trackview.cpp
|
olive-editor_olive/app/widget/timelinewidget/trackview/trackview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "trackview.h"
#include <QDebug>
#include <QResizeEvent>
#include <QScrollBar>
#include <QSplitter>
#include <QVBoxLayout>
#include "trackviewitem.h"
namespace olive {
TrackView::TrackView(Qt::Alignment vertical_alignment, QWidget *parent) :
QScrollArea(parent),
list_(nullptr),
alignment_(vertical_alignment)
{
setAlignment(Qt::AlignLeft | alignment_);
QWidget* central = new QWidget();
setWidget(central);
setWidgetResizable(true);
QVBoxLayout* layout = new QVBoxLayout(central);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
if (alignment_ == Qt::AlignBottom) {
layout->addStretch();
connect(verticalScrollBar(), &QScrollBar::rangeChanged, this, &TrackView::ScrollbarRangeChanged);
last_scrollbar_max_ = verticalScrollBar()->maximum();
}
splitter_ = new TrackViewSplitter(alignment_);
splitter_->setChildrenCollapsible(false);
layout->addWidget(splitter_);
if (alignment_ == Qt::AlignTop) {
layout->addStretch();
}
connect(splitter_, &TrackViewSplitter::TrackHeightChanged, this, &TrackView::TrackHeightChanged);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
void TrackView::ConnectTrackList(TrackList *list)
{
if (list_ != nullptr) {
// Remove tracks
for (int i=0; i<list_->GetTrackCount(); i++) {
splitter_->Remove(0);
}
disconnect(list_, &TrackList::TrackAdded, this, &TrackView::InsertTrack);
disconnect(list_, &TrackList::TrackRemoved, this, &TrackView::RemoveTrack);
}
list_ = list;
if (list_ != nullptr) {
foreach (Track* track, list_->GetTracks()) {
InsertTrack(track);
}
connect(list_, &TrackList::TrackAdded, this, &TrackView::InsertTrack);
connect(list_, &TrackList::TrackRemoved, this, &TrackView::RemoveTrack);
}
}
void TrackView::DisconnectTrackList()
{
ConnectTrackList(nullptr);
}
void TrackView::resizeEvent(QResizeEvent *e)
{
QScrollArea::resizeEvent(e);
splitter_->SetSpacerHeight(height()/2);
}
void TrackView::ScrollbarRangeChanged(int, int max)
{
if (max != last_scrollbar_max_) {
int ba_val = last_scrollbar_max_ - verticalScrollBar()->value();
int new_val = max - ba_val;
verticalScrollBar()->setValue(new_val);
emit verticalScrollBar()->valueChanged(new_val);
last_scrollbar_max_ = max;
}
}
void TrackView::TrackHeightChanged(int index, int height)
{
list_->GetTrackAt(index)->SetTrackHeightInPixels(height);
}
void TrackView::InsertTrack(Track *track)
{
TrackViewItem *tvi = new TrackViewItem(track);
connect(tvi, &TrackViewItem::AboutToDeleteTrack, this, &TrackView::AboutToDeleteTrack);
splitter_->Insert(track->Index(),
track->GetTrackHeightInPixels(),
tvi);
}
void TrackView::RemoveTrack(Track *track)
{
splitter_->Remove(track->Index());
}
}
| 3,597
|
C++
|
.cpp
| 104
| 31.163462
| 101
| 0.734027
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,839
|
trackviewsplitter.cpp
|
olive-editor_olive/app/widget/timelinewidget/trackview/trackviewsplitter.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "trackviewsplitter.h"
#include <QDebug>
#include <QPainter>
#include "node/output/track/track.h"
namespace olive {
TrackViewSplitter::TrackViewSplitter(Qt::Alignment vertical_alignment, QWidget* parent) :
QSplitter(Qt::Vertical, parent),
alignment_(vertical_alignment),
spacer_height_(0)
{
setHandleWidth(1);
int initial_height = 0;
// Add empty spacer so we get a splitter handle after the last element
QWidget* spacer = new QWidget();
addWidget(spacer);
setFixedHeight(initial_height);
}
void TrackViewSplitter::HandleReceiver(TrackViewSplitterHandle *h, int diff)
{
int ele_id = -1;
for (int i=0;i<count();i++) {
if (handle(i) == h) {
ele_id = i;
break;
}
}
// The handle index is actually always one above the element index
if (alignment_ == Qt::AlignTop) {
ele_id--;
} else if (alignment_ == Qt::AlignBottom) {
diff = -diff;
}
QList<int> element_sizes = sizes();
int old_ele_sz = element_sizes.at(ele_id);
// Transform element size by diff
int new_ele_sz = old_ele_sz + diff;
// Limit by track minimum height
new_ele_sz = qMax(new_ele_sz, Track::GetMinimumTrackHeightInPixels());
if (alignment_ == Qt::AlignBottom) {
ele_id = count() - ele_id - 1;
}
SetTrackHeight(ele_id, new_ele_sz);
emit TrackHeightChanged(ele_id, new_ele_sz);
}
void TrackViewSplitter::SetTrackHeight(int index, int h)
{
QList<int> element_sizes = sizes();
if (alignment_ == Qt::AlignBottom) {
index = count() - index - 1;
}
int old_ele_sz = element_sizes.at(index);
int diff = h - old_ele_sz;
// Set new size on element
element_sizes.replace(index, h);
setSizes(element_sizes);
// Increase height by the difference
setFixedHeight(height() + diff);
}
void TrackViewSplitter::SetHeightWithSizes(QList<int> sizes)
{
int start_height = 0;
// Add spacer height too
if (alignment_ == Qt::AlignBottom) {
sizes.replace(0, spacer_height_);
} else {
sizes.replace(sizes.size() - 1, spacer_height_);
}
foreach (int s, sizes) {
start_height += s + handleWidth();
}
// The spacer doesn't need a handle width
start_height -= handleWidth();
setFixedHeight(start_height);
setSizes(sizes);
}
void TrackViewSplitter::Insert(int index, int height, QWidget *item)
{
QList<int> sz = sizes();
if (alignment_ == Qt::AlignBottom) {
index = count() - index;
}
sz.insert(index, height);
insertWidget(index, item);
SetHeightWithSizes(sz);
}
void TrackViewSplitter::Remove(int index)
{
QList<int> sz = sizes();
if (alignment_ == Qt::AlignBottom) {
index = count() - 1 - index;
}
sz.removeAt(index);
delete widget(index);
SetHeightWithSizes(sz);
}
void TrackViewSplitter::SetSpacerHeight(int height)
{
spacer_height_ = height;
SetHeightWithSizes(sizes());
}
QSplitterHandle *TrackViewSplitter::createHandle()
{
return new TrackViewSplitterHandle(orientation(), this);
}
TrackViewSplitterHandle::TrackViewSplitterHandle(Qt::Orientation orientation, QSplitter *parent) :
QSplitterHandle(orientation, parent),
dragging_(false)
{
}
void TrackViewSplitterHandle::mousePressEvent(QMouseEvent *)
{
}
void TrackViewSplitterHandle::mouseMoveEvent(QMouseEvent *)
{
if (dragging_) {
static_cast<TrackViewSplitter*>(parent())->HandleReceiver(this, QCursor::pos().y() - drag_y_);
}
drag_y_ = QCursor::pos().y();
dragging_ = true;
}
void TrackViewSplitterHandle::mouseReleaseEvent(QMouseEvent *)
{
dragging_ = false;
}
void TrackViewSplitterHandle::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.fillRect(rect(), palette().base());
}
}
| 4,339
|
C++
|
.cpp
| 144
| 27.208333
| 98
| 0.721284
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,840
|
trackviewitem.cpp
|
olive-editor_olive/app/widget/timelinewidget/trackview/trackviewitem.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "trackviewitem.h"
#include <QDebug>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>
#include "core.h"
#include "timeline/timelineundogeneral.h"
#include "ui/icons/icons.h"
#include "widget/menu/menu.h"
namespace olive {
TrackViewItem::TrackViewItem(Track* track, QWidget *parent) :
QWidget(parent),
track_(track)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
stack_ = new QStackedWidget();
layout->addWidget(stack_);
label_ = new ClickableLabel();
connect(label_, &ClickableLabel::MouseDoubleClicked, this, &TrackViewItem::LabelClicked);
connect(track_, &Track::LabelChanged, this, &TrackViewItem::UpdateLabel);
connect(track_, &Track::IndexChanged, this, &TrackViewItem::UpdateLabel);
UpdateLabel();
stack_->addWidget(label_);
line_edit_ = new FocusableLineEdit();
connect(line_edit_, &FocusableLineEdit::Confirmed, this, &TrackViewItem::LineEditConfirmed);
connect(line_edit_, &FocusableLineEdit::Cancelled, this, &TrackViewItem::LineEditCancelled);
stack_->addWidget(line_edit_);
mute_button_ = CreateMSLButton(Qt::red);
mute_button_->setChecked(track->IsMuted());
UpdateMuteButton(track->IsMuted());
connect(mute_button_, &QPushButton::toggled, track_, &Track::SetMuted);
connect(mute_button_, &QPushButton::toggled, this, &TrackViewItem::UpdateMuteButton);
layout->addWidget(mute_button_);
/*solo_button_ = CreateMSLButton(tr("S"), Qt::yellow);
layout->addWidget(solo_button_);*/
lock_button_ = CreateMSLButton(Qt::gray);
lock_button_->setChecked(track->IsLocked());
UpdateLockButton(track->IsLocked());
connect(lock_button_, &QPushButton::toggled, track_, &Track::SetLocked);
connect(lock_button_, &QPushButton::toggled, this, &TrackViewItem::UpdateLockButton);
layout->addWidget(lock_button_);
setMinimumHeight(mute_button_->height());
setContextMenuPolicy(Qt::CustomContextMenu);
connect(track, &Track::MutedChanged, mute_button_, &QPushButton::setChecked);
connect(this, &QWidget::customContextMenuRequested, this, &TrackViewItem::ShowContextMenu);
}
QPushButton *TrackViewItem::CreateMSLButton(const QColor& checked_color) const
{
QPushButton* button = new QPushButton();
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
button->setCheckable(true);
button->setStyleSheet(QStringLiteral("QPushButton::checked { background: %1; }").arg(checked_color.name()));
int size = button->sizeHint().height();
size = qRound(size * 0.75);
button->setFixedSize(size, size);
return button;
}
void TrackViewItem::LabelClicked()
{
stack_->setCurrentWidget(line_edit_);
line_edit_->setFocus();
line_edit_->selectAll();
}
void TrackViewItem::LineEditConfirmed()
{
line_edit_->blockSignals(true);
track_->SetLabel(line_edit_->text());
UpdateLabel();
stack_->setCurrentWidget(label_);
line_edit_->blockSignals(false);
}
void TrackViewItem::LineEditCancelled()
{
line_edit_->blockSignals(true);
stack_->setCurrentWidget(label_);
line_edit_->blockSignals(false);
}
void TrackViewItem::UpdateLabel()
{
label_->setText(track_->GetLabelOrName());
}
void TrackViewItem::ShowContextMenu(const QPoint &p)
{
Menu m(this);
QAction *delete_action = m.addAction(tr("&Delete"));
connect(delete_action, &QAction::triggered, this, &TrackViewItem::DeleteTrack, Qt::QueuedConnection);
m.addSeparator();
QAction *delete_unused_action = m.addAction(tr("Delete All &Empty"));
connect(delete_unused_action, &QAction::triggered, this, &TrackViewItem::DeleteAllEmptyTracks, Qt::QueuedConnection);
m.exec(mapToGlobal(p));
}
void TrackViewItem::DeleteTrack()
{
emit AboutToDeleteTrack(track_);
Core::instance()->undo_stack()->push(new TimelineRemoveTrackCommand(track_), tr("Deleted Track \"%1\"").arg(track_->GetLabelOrName()));
}
void TrackViewItem::DeleteAllEmptyTracks()
{
Sequence *sequence = track_->sequence();
QVector<Track*> tracks_to_remove;
QStringList track_names_to_remove;
foreach (Track *t, sequence->GetTracks()) {
if (t->Blocks().isEmpty()) {
tracks_to_remove.append(t);
track_names_to_remove.append(t->GetLabelOrName());
}
}
if (tracks_to_remove.isEmpty()) {
QMessageBox::information(this, tr("Delete All Empty"), tr("No tracks are currently empty"));
} else {
if (QMessageBox::question(this, tr("Delete All Empty"),
tr("This will delete the following tracks:\n\n%1\n\nDo you wish to continue?").arg(track_names_to_remove.join('\n')),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) {
MultiUndoCommand *command = new MultiUndoCommand();
foreach (Track *track, tracks_to_remove) {
command->add_child(new TimelineRemoveTrackCommand(track));
}
Core::instance()->undo_stack()->push(command, tr("Deleted All Empty Tracks"));
}
}
}
void TrackViewItem::UpdateMuteButton(bool e)
{
mute_button_->setIcon(e ? icon::EyeClosed : icon::EyeOpened);
}
void TrackViewItem::UpdateLockButton(bool e)
{
lock_button_->setIcon(e ? icon::LockClosed : icon::LockOpened);
}
}
| 5,915
|
C++
|
.cpp
| 148
| 36.682432
| 147
| 0.734498
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,841
|
tool.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/tool.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "node/block/transition/transition.h"
namespace olive {
const int TimelineTool::kDefaultDistanceFromOutput = -4;
TimelineTool::TimelineTool(TimelineWidget *parent) :
dragging_(false),
parent_(parent)
{
}
TimelineTool::~TimelineTool()
{
}
TimelineWidget *TimelineTool::parent()
{
return parent_;
}
Sequence *TimelineTool::sequence()
{
return parent_->sequence();
}
Timeline::MovementMode TimelineTool::FlipTrimMode(const Timeline::MovementMode &trim_mode)
{
if (trim_mode == Timeline::kTrimIn) {
return Timeline::kTrimOut;
}
if (trim_mode == Timeline::kTrimOut) {
return Timeline::kTrimIn;
}
return trim_mode;
}
rational TimelineTool::SnapMovementToTimebase(const rational &start, rational movement, const rational &timebase)
{
rational proposed_position = start + movement;
rational snapped = Timecode::snap_time_to_timebase(proposed_position, timebase);
if (proposed_position != snapped) {
movement += snapped - proposed_position;
}
return movement;
}
rational TimelineTool::ValidateTimeMovement(rational movement)
{
bool first_ghost = true;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (ghost->GetMode() != Timeline::kMove) {
continue;
}
// Prevents any ghosts from going below 0:00:00 time
if (ghost->GetIn() + movement < 0) {
movement = -ghost->GetIn();
} else if (first_ghost) {
// Ensure ghost is snapped to a grid
movement = SnapMovementToTimebase(ghost->GetIn(), movement, parent()->GetTimebaseForTrackType(ghost->GetTrack().type()));
first_ghost = false;
}
}
return movement;
}
int TimelineTool::ValidateTrackMovement(int movement, const QVector<TimelineViewGhostItem*>& ghosts)
{
foreach (TimelineViewGhostItem* ghost, ghosts) {
if (ghost->GetMode() != Timeline::kMove) {
continue;
}
if (!ghost->GetCanMoveTracks()) {
return 0;
} else if (ghost->GetTrack().index() + movement < 0) {
// Prevents any ghosts from going to a non-existent negative track
movement = -ghost->GetTrack().index();
}
}
return movement;
}
void TimelineTool::GetGhostData(rational *earliest_point, rational *latest_point)
{
rational ep = RATIONAL_MAX;
rational lp = RATIONAL_MIN;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
ep = qMin(ep, ghost->GetAdjustedIn());
lp = qMax(lp, ghost->GetAdjustedOut());
}
if (earliest_point) {
*earliest_point = ep;
}
if (latest_point) {
*latest_point = lp;
}
}
void TimelineTool::InsertGapsAtGhostDestination(olive::MultiUndoCommand *command)
{
rational earliest_point, latest_point;
GetGhostData(&earliest_point, &latest_point);
parent()->InsertGapsAt(earliest_point, latest_point - earliest_point, command);
}
}
| 3,573
|
C++
|
.cpp
| 108
| 29.740741
| 127
| 0.732049
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,842
|
record.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/record.cpp
|
#include "record.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
RecordTool::RecordTool(TimelineWidget *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 && 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;
}
}
}
| 1,929
|
C++
|
.cpp
| 69
| 24.652174
| 121
| 0.688213
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,843
|
beam.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/beam.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "beam.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
BeamTool::BeamTool(TimelineWidget *parent) :
TimelineTool(parent)
{
}
void BeamTool::HoverMove(TimelineViewMouseEvent *event)
{
parent()->SetViewBeamCursor(ValidatedCoordinate(event->GetCoordinates(true)));
}
TimelineCoordinate BeamTool::ValidatedCoordinate(TimelineCoordinate coord)
{
if (Core::instance()->snapping()) {
rational movement;
parent()->SnapPoint({coord.GetFrame()}, &movement);
if (!movement.isNull()) {
coord.SetFrame(coord.GetFrame() + movement);
}
}
return coord;
}
}
| 1,322
|
C++
|
.cpp
| 37
| 32.891892
| 80
| 0.763551
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,844
|
ripple.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/ripple.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "node/block/gap/gap.h"
#include "timeline/timelineundoripple.h"
#include "ripple.h"
namespace olive {
RippleTool::RippleTool(TimelineWidget* parent) :
PointerTool(parent)
{
SetMovementAllowed(false);
SetGapTrimmingAllowed(true);
}
void RippleTool::InitiateDrag(Block *clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers)
{
InitiateDragInternal(clicked_item, trim_mode, modifiers, true, true, false);
if (!parent()->HasGhosts()) {
return;
}
// Find the earliest ripple
rational earliest_ripple = RATIONAL_MAX;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
rational ghost_ripple_point;
if (trim_mode == Timeline::kTrimIn) {
ghost_ripple_point = ghost->GetIn();
} else {
ghost_ripple_point = ghost->GetOut();
}
earliest_ripple = qMin(earliest_ripple, ghost_ripple_point);
}
// For each track that does NOT have a ghost, we need to make one for Gaps
foreach (Track* track, sequence()->GetTracks()) {
if (track->IsLocked()) {
continue;
}
// Determine if we've already created a ghost on this track
bool ghost_on_this_track_exists = false;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (parent()->GetTrackFromReference(ghost->GetTrack()) == track) {
ghost_on_this_track_exists = true;
break;
}
}
// If there's no ghost on this track, create one
if (!ghost_on_this_track_exists) {
// Find the block that starts just after or at the ripple point
Block* block_after_ripple = track->NearestBlockAfterOrAt(earliest_ripple);
// Exception for out-transitions, do not create a gap between them
if (block_after_ripple) {
if (ClipBlock *prev_clip = dynamic_cast<ClipBlock*>(block_after_ripple->previous())) {
if (prev_clip->out_transition() == block_after_ripple) {
block_after_ripple = block_after_ripple->next();
}
}
}
// If block is null, there will be no blocks after to ripple
if (block_after_ripple) {
TimelineViewGhostItem* ghost;
if (dynamic_cast<GapBlock*>(block_after_ripple)) {
// If this Block is already a Gap, ghost it now
ghost = AddGhostFromBlock(block_after_ripple, trim_mode);
} else {
// Well we need to ripple SOMETHING, it'll either be the previous block if it's a gap
// or we'll have to create a new gap ourselves
Block* previous = block_after_ripple->previous();
if (dynamic_cast<GapBlock*>(previous)) {
// Previous is a gap, that'll make a fine substitute
ghost = AddGhostFromBlock(previous, trim_mode);
} else {
// Previous is not a gap, we'll have to insert one there ourselves
ghost = AddGhostFromNull(block_after_ripple->in(), block_after_ripple->in(), track->ToReference(), trim_mode);
ghost->SetData(TimelineViewGhostItem::kReferenceBlock, QtUtils::PtrToValue(block_after_ripple));
}
}
}
}
}
}
void RippleTool::FinishDrag(TimelineViewMouseEvent *event)
{
Q_UNUSED(event)
if (parent()->HasGhosts()) {
QVector< QHash<Track*, TrackListRippleToolCommand::RippleInfo> > info_list(Track::kCount);
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (!ghost->HasBeenAdjusted()) {
continue;
}
Track* track = parent()->GetTrackFromReference(ghost->GetTrack());
TrackListRippleToolCommand::RippleInfo info;
Block* b = QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kAttachedBlock));
if (b) {
info.block = b;
info.append_gap = false;
} else {
info.block = QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kReferenceBlock));
info.append_gap = true;
}
info_list[track->type()].insert(track, info);
}
MultiUndoCommand* command = new MultiUndoCommand();
rational movement;
if (drag_movement_mode() == Timeline::kTrimOut) {
movement = parent()->GetGhostItems().first()->GetOutAdjustment();
} else {
movement = parent()->GetGhostItems().first()->GetInAdjustment();
}
for (int i=0;i<info_list.size();i++) {
if (!info_list.at(i).isEmpty()) {
command->add_child(new TrackListRippleToolCommand(sequence()->track_list(static_cast<Track::Type>(i)),
info_list.at(i),
movement,
drag_movement_mode()));
}
}
if (command->child_count() > 0) {
TimelineWidgetSelections new_sel = parent()->GetSelections();
TimelineViewGhostItem* reference_ghost = parent()->GetGhostItems().first();
if (drag_movement_mode() == Timeline::kTrimIn) {
new_sel.TrimOut(-reference_ghost->GetInAdjustment());
} else {
new_sel.TrimOut(reference_ghost->GetOutAdjustment());
}
command->add_child(new TimelineWidget::SetSelectionsCommand(parent(), new_sel, parent()->GetSelections(), false));
Core::instance()->undo_stack()->push(command, qApp->translate("RippleTool", "Rippled Clips"));
} else {
delete command;
}
}
}
}
| 6,131
|
C++
|
.cpp
| 142
| 35.957746
| 122
| 0.655914
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,845
|
razor.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/razor.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "razor.h"
#include "node/nodeundo.h"
#include "timeline/timelineundosplit.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
RazorTool::RazorTool(TimelineWidget* parent) :
BeamTool(parent)
{
}
void RazorTool::MousePress(TimelineViewMouseEvent *event)
{
split_tracks_.clear();
MouseMove(event);
}
void RazorTool::MouseMove(TimelineViewMouseEvent *event)
{
if (!dragging_) {
drag_start_ = ValidatedCoordinate(event->GetCoordinates(true));
dragging_ = true;
}
// Split at the current cursor track
Track::Reference split_track = event->GetTrack();
if (!split_tracks_.contains(split_track)) {
split_tracks_.append(split_track);
}
}
void RazorTool::MouseRelease(TimelineViewMouseEvent *event)
{
Q_UNUSED(event)
// Always split at the same time
rational split_time = drag_start_.GetFrame();
QVector<Block*> blocks_to_split;
foreach (const Track::Reference& track_ref, split_tracks_) {
Track* track = parent()->GetTrackFromReference(track_ref);
if (track == nullptr || track->IsLocked()) {
continue;
}
Block* block_at_time = track->NearestBlockBefore(split_time);
// Ensure there's a valid block here
ClipBlock *clip_at_time;
if (block_at_time
&& block_at_time->out() != split_time
&& (clip_at_time = dynamic_cast<ClipBlock*>(block_at_time))
&& !blocks_to_split.contains(block_at_time)) {
blocks_to_split.append(block_at_time);
// Add links if no alt is held
if (!(event->GetModifiers() & Qt::AltModifier)) {
foreach (Block* link, clip_at_time->block_links()) {
if (!blocks_to_split.contains(link)) {
blocks_to_split.append(link);
}
}
}
}
}
split_tracks_.clear();
if (!blocks_to_split.isEmpty()) {
Core::instance()->undo_stack()->push(new BlockSplitPreservingLinksCommand(blocks_to_split, {split_time}), qApp->translate("RazorTool", "Split Clips"));
}
dragging_ = false;
}
}
| 2,716
|
C++
|
.cpp
| 76
| 31.605263
| 155
| 0.704667
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,846
|
add.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/add.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "add.h"
#include "core.h"
#include "node/block/subtitle/subtitle.h"
#include "node/factory.h"
#include "node/generator/shape/shapenode.h"
#include "node/generator/solid/solid.h"
#include "node/generator/text/textv3.h"
#include "node/nodeundo.h"
#include "timeline/timelineundopointer.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
AddTool::AddTool(TimelineWidget *parent) :
BeamTool(parent),
ghost_(nullptr)
{
}
void AddTool::MousePress(TimelineViewMouseEvent *event)
{
const Track::Reference& track = event->GetTrack();
// Check if track is locked
Track* t = parent()->GetTrackFromReference(track);
if (t && t->IsLocked()) {
return;
}
Track::Type add_type = Track::kNone;
switch (Core::instance()->GetSelectedAddableObject()) {
case Tool::kAddableBars:
case Tool::kAddableSolid:
case Tool::kAddableTitle:
case Tool::kAddableShape:
add_type = Track::kVideo;
break;
case Tool::kAddableTone:
add_type = Track::kAudio;
break;
case Tool::kAddableSubtitle:
add_type = Track::kSubtitle;
break;
case Tool::kAddableEmpty:
// Leave as "none", which means this block can be placed on any track
break;
case Tool::kAddableCount:
// Return so we do nothing
return;
}
if (add_type == Track::kNone
|| add_type == track.type()) {
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 AddTool::MouseMove(TimelineViewMouseEvent *event)
{
if (!ghost_) {
return;
}
MouseMoveInternal(event->GetFrame(), event->GetModifiers() & Qt::AltModifier);
}
void AddTool::MouseRelease(TimelineViewMouseEvent *event)
{
if (ghost_) {
if (!ghost_->GetAdjustedLength().isNull()) {
MultiUndoCommand* command = new MultiUndoCommand();
if (MultiUndoCommand *subtitle_section_command = parent()->TakeSubtitleSectionCommand()) {
command->add_child(subtitle_section_command);
}
Sequence *s = parent()->sequence();
QRectF r;
if (Core::instance()->GetSelectedAddableObject() == Tool::kAddableTitle) {
VideoParams svp = s->GetVideoParams();
r = QRectF(0, 0, svp.width(), svp.height());
r.adjust(svp.width()/10, svp.height()/10, -svp.width()/10, -svp.height()/10);
}
CreateAddableClip(command, s, ghost_->GetTrack(), ghost_->GetAdjustedIn(), ghost_->GetAdjustedLength(), r);
Core::instance()->undo_stack()->push(command, qApp->translate("AddTool", "Added Clip"));
}
parent()->ClearGhosts();
snap_points_.clear();
ghost_ = nullptr;
}
}
Node *AddTool::CreateAddableClip(MultiUndoCommand *command, Sequence *sequence, const Track::Reference &track, const rational &in, const rational &length, const QRectF &rect)
{
ClipBlock* clip;
if (Core::instance()->GetSelectedAddableObject() == Tool::kAddableSubtitle) {
clip = new SubtitleBlock();
} else {
clip = new ClipBlock();
clip->SetLabel(olive::Tool::GetAddableObjectName(Core::instance()->GetSelectedAddableObject()));
}
clip->set_length_and_media_out(length);
Project* graph = sequence->parent();
command->add_child(new NodeAddCommand(graph, clip));
command->add_child(new NodeSetPositionCommand(clip, clip, QPointF(0, 0)));
command->add_child(new TrackPlaceBlockCommand(sequence->track_list(track.type()),
track.index(),
clip,
in));
Node *node_to_add = nullptr;
switch (Core::instance()->GetSelectedAddableObject()) {
case Tool::kAddableEmpty:
// Empty, nothing to be done
break;
case Tool::kAddableSolid:
node_to_add = new SolidGenerator();
break;
case Tool::kAddableShape:
node_to_add = new ShapeNode();
break;
case Tool::kAddableTitle:
node_to_add = new TextGeneratorV3();
break;
case Tool::kAddableBars:
case Tool::kAddableTone:
// Not implemented yet
qWarning() << "Unimplemented add object:" << Core::instance()->GetSelectedAddableObject();
break;
case Tool::kAddableSubtitle:
// The block itself is the node we want
break;
case Tool::kAddableCount:
// Invalid value, do nothing
break;
}
if (node_to_add) {
QPointF extra_node_offset(kDefaultDistanceFromOutput, 0);
command->add_child(new NodeAddCommand(graph, node_to_add));
command->add_child(new NodeEdgeAddCommand(node_to_add, NodeInput(clip, ClipBlock::kBufferIn)));
command->add_child(new NodeSetPositionCommand(node_to_add, clip, extra_node_offset));
if (!rect.isNull()) {
if (ShapeNodeBase *shape = dynamic_cast<ShapeNodeBase*>(node_to_add)) {
shape->SetRect(rect, sequence->GetVideoParams(), command);
}
}
}
return node_to_add;
}
void AddTool::MouseMoveInternal(const rational &cursor_frame, bool outwards)
{
// Calculate movement
rational movement = cursor_frame - drag_start_point_;
// Validation: Ensure in point never goes below 0
if (movement < -ghost_->GetIn() || (outwards && -movement < -ghost_->GetIn())) {
movement = -ghost_->GetIn();
}
// Snap movement
bool snapped;
if (Core::instance()->snapping()) {
snapped = parent()->SnapPoint(snap_points_, &movement);
} else {
snapped = false;
}
// If alt is held, our movement goes both ways (outwards)
if (!snapped && outwards) {
// Snap backwards too
movement = -movement;
parent()->SnapPoint(snap_points_, &movement);
// We don't need to un-neg here because outwards means all future processing will be done both pos and neg
}
// Make adjustment
if (!movement) {
ghost_->SetInAdjustment(0);
ghost_->SetOutAdjustment(0);
} else if (movement > 0) {
ghost_->SetInAdjustment(outwards ? -movement : 0);
ghost_->SetOutAdjustment(movement);
} else if (movement < 0) {
ghost_->SetInAdjustment(movement);
ghost_->SetOutAdjustment(outwards ? -movement : 0);
}
}
}
| 6,925
|
C++
|
.cpp
| 191
| 31.617801
| 174
| 0.686781
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,847
|
trackselect.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/trackselect.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "trackselect.h"
#include "node/block/gap/gap.h"
#include "node/output/track/track.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
TrackSelectTool::TrackSelectTool(TimelineWidget *parent) :
PointerTool(parent)
{
}
void TrackSelectTool::MousePress(TimelineViewMouseEvent *event)
{
QVector<Block*> blocks;
bool forward = !(event->GetModifiers() & Qt::ControlModifier);
parent()->DeselectAll();
if (event->GetModifiers() & Qt::ShiftModifier) {
// Track only
Track *track = parent()->GetTrackFromReference(event->GetTrack());
if (track) {
SelectBlocksOnTrack(track, event, &blocks, forward);
}
} else {
// All tracks
foreach (Track *track, parent()->sequence()->GetTracks()) {
SelectBlocksOnTrack(track, event, &blocks, forward);
}
}
if (!blocks.isEmpty()) {
parent()->SignalSelectedBlocks(blocks);
set_drag_movement_mode(Timeline::kMove);
SetClickedItem(blocks.first());
drag_start_ = event->GetCoordinates();
} else {
set_drag_movement_mode(Timeline::kNone);
}
}
void TrackSelectTool::SelectBlocksOnTrack(Track *track, TimelineViewMouseEvent *event, QVector<Block*> *blocks, bool forward)
{
Block *b = track->NearestBlockBeforeOrAt(event->GetFrame());
if (!b && !track->Blocks().isEmpty() && !forward) {
// Fallback to first or last block in track
b = track->Blocks().last();
}
while (b) {
if (!dynamic_cast<GapBlock*>(b)) {
if (!blocks->contains(b)) {
parent()->AddSelection(b);
blocks->append(b);
}
if (!(event->GetModifiers() & Qt::AltModifier)) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
foreach (Block *link, clip->block_links()) {
if (!blocks->contains(link)) {
parent()->AddSelection(link);
blocks->append(link);
}
}
}
}
}
b = forward ? b->next() : b->previous();
}
}
}
| 2,681
|
C++
|
.cpp
| 77
| 30.168831
| 125
| 0.676983
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,848
|
import.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/import.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "import.h"
#include <QCheckBox>
#include <QMessageBox>
#include <QMimeData>
#include <QToolTip>
#include "config/config.h"
#include "common/qtutils.h"
#include "core.h"
#include "dialog/sequence/sequence.h"
#include "node/audio/volume/volume.h"
#include "node/block/subtitle/subtitle.h"
#include "node/distort/transform/transformdistortnode.h"
#include "node/generator/matrix/matrix.h"
#include "node/math/math/math.h"
#include "node/nodeundo.h"
#include "node/project/sequence/sequence.h"
#include "timeline/timelineundopointer.h"
#include "window/mainwindow/mainwindow.h"
#include "window/mainwindow/mainwindowundo.h"
namespace olive {
ImportTool::ImportTool(TimelineWidget *parent) :
TimelineTool(parent)
{
// Calculate width used for importing to give ghosts a slight lead-in so the ghosts aren't right on the cursor
import_pre_buffer_ = QtUtils::QFontMetricsWidth(parent->fontMetrics(), "HHHHHHHH");
}
void ImportTool::DragEnter(TimelineViewMouseEvent *event)
{
QStringList mime_formats = event->GetMimeData()->formats();
// Listen for MIME data from a ProjectViewModel
if (mime_formats.contains(Project::kItemMimeType)) {
// Data is drag/drop data from a ProjectViewModel
QByteArray model_data = event->GetMimeData()->data(Project::kItemMimeType);
// Use QDataStream to deserialize the data
QDataStream stream(&model_data, QIODevice::ReadOnly);
// Variables to deserialize into
quintptr item_ptr;
QVector<Track::Reference> enabled_streams;
// Set drag start position
drag_start_ = event->GetCoordinates();
snap_points_.clear();
while (!stream.atEnd()) {
stream >> enabled_streams >> item_ptr;
// Get Item object
Node* item = reinterpret_cast<Node*>(item_ptr);
// Check if Item is Footage
ViewerOutput* f = dynamic_cast<ViewerOutput*>(item);
if (f && f->GetTotalStreamCount()) {
// If the Item is Footage, we can create a Ghost from it
dragged_footage_.append({f, enabled_streams});
}
}
// Create a reasonable amount of space to inset the cursor by when importing
ghost_offset_ = drag_start_.GetFrame();
if (!event->GetBypassImportBuffer()) {
ghost_offset_ -= parent()->SceneToTime(import_pre_buffer_);
}
PrepGhosts(ghost_offset_, drag_start_.GetTrack().index());
if (parent()->HasGhosts() || !parent()->GetConnectedNode()) {
// We only clear the tentative track if the mimedata is about to be destroyed (i.e. the drag
// is cancelled). If we do this in DragLeave, it leads to undesirable behavior if the cursor
// is going between views (subtitle track rapidly appearing and disappearing)
QObject::connect(event->GetMimeData(), &QObject::destroyed, parent(), &TimelineWidget::ClearTentativeSubtitleTrack);
event->accept();
} else {
event->ignore();
}
} else {
// FIXME: Implement dropping from file
event->ignore();
}
}
void ImportTool::DragMove(TimelineViewMouseEvent *event)
{
if (!dragged_footage_.isEmpty()) {
if (parent()->HasGhosts()) {
rational time_movement = event->GetFrame() - drag_start_.GetFrame();
// Keep ghost offset no lower than 0
if (ghost_offset_ + time_movement < 0) {
time_movement = -ghost_offset_;
}
int track_movement = event->GetTrack().index() - drag_start_.GetTrack().index();
time_movement = ValidateTimeMovement(time_movement);
track_movement = ValidateTrackMovement(track_movement, parent()->GetGhostItems());
// If snapping is enabled, check for snap points
if (Core::instance()->snapping()) {
parent()->SnapPoint(snap_points_, &time_movement);
time_movement = ValidateTimeMovement(time_movement);
track_movement = ValidateTrackMovement(track_movement, parent()->GetGhostItems());
}
rational earliest_ghost = RATIONAL_MAX;
// Move ghosts to the mouse cursor
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
ghost->SetInAdjustment(time_movement);
ghost->SetOutAdjustment(time_movement);
ghost->SetTrackAdjustment(track_movement);
earliest_ghost = qMin(earliest_ghost, ghost->GetAdjustedIn());
}
// Generate tooltip (showing earliest in point of imported clip)
rational tooltip_timebase = parent()->GetTimebaseForTrackType(event->GetTrack().type());
QString tooltip_text = QString::fromStdString(Timecode::time_to_timecode(earliest_ghost,
tooltip_timebase,
Core::instance()->GetTimecodeDisplay()));
// Force tooltip to update (otherwise the tooltip won't move as written in the documentation, and could get in the way
// of the cursor)
QToolTip::hideText();
QToolTip::showText(QCursor::pos(),
tooltip_text,
parent());
}
event->accept();
} else {
event->ignore();
}
}
void ImportTool::DragLeave(QDragLeaveEvent* event)
{
if (!dragged_footage_.isEmpty()) {
parent()->ClearGhosts();
dragged_footage_.clear();
event->accept();
} else {
event->ignore();
}
}
void ImportTool::DragDrop(TimelineViewMouseEvent *event)
{
if (!dragged_footage_.isEmpty()) {
auto command = new MultiUndoCommand();
DropGhosts(event->GetModifiers() & Qt::ControlModifier, command);
Core::instance()->undo_stack()->push(command, qApp->translate("ImportTool", "Dropped Footage Into Sequence"));
event->accept();
} else {
event->ignore();
}
}
void ImportTool::PlaceAt(const QVector<ViewerOutput *> &footage, const rational &start, bool insert, MultiUndoCommand *command, int track_offset, bool jump_to_end)
{
DraggedFootageData refs;
foreach (ViewerOutput* f, footage) {
refs.append({f, f->GetEnabledStreamsAsReferences()});
}
PlaceAt(refs, start, insert, command, track_offset, jump_to_end);
}
void ImportTool::PlaceAt(const DraggedFootageData &footage, const rational &start, bool insert, MultiUndoCommand *command, int track_offset, bool jump_to_end)
{
dragged_footage_ = footage;
if (dragged_footage_.isEmpty()) {
return;
}
PrepGhosts(start, track_offset);
rational max(0);
if (jump_to_end) {
for (TimelineViewGhostItem* ghost : parent()->GetGhostItems()) {
max = std::max(max, ghost->GetAdjustedOut());
}
}
DropGhosts(insert, command);
if (jump_to_end) {
this->sequence()->SetPlayhead(max);
}
}
void ImportTool::FootageToGhosts(rational ghost_start, const DraggedFootageData &sorted, const rational& dest_tb, const int& track_start)
{
for (auto it=sorted.cbegin(); it!=sorted.cend(); it++) {
ViewerOutput* footage = it->first;
if (footage == sequence() || (sequence() && footage->InputsFrom(sequence(), true))) {
// Prevent cyclical dependency
continue;
}
// Each stream is offset by one track per track "type", we keep track of them in this vector
QVector<int> track_offsets(Track::kCount);
track_offsets.fill(track_start);
rational footage_duration;
rational ghost_in;
TimelineWorkArea* wk = footage->GetWorkArea();
if (wk->enabled()) {
footage_duration = wk->length();
ghost_in = wk->in();
} else {
footage_duration = footage->GetLength();
if (footage_duration.isNull()) {
// Fallback to still length if legngth was 0
footage_duration = OLIVE_CONFIG("DefaultStillLength").value<rational>();
}
}
// Snap footage duration to timebase
rational snap_mvmt = SnapMovementToTimebase(footage_duration, 0, dest_tb);
if (!snap_mvmt.isNull()) {
footage_duration += snap_mvmt;
}
// Create ghosts
foreach (const Track::Reference& ref, it->second) {
Track::Type track_type = ref.type();
Track::Reference dest_track(track_type, track_offsets.at(track_type));
if (track_type == Track::kVideo || track_type == Track::kAudio) {
auto ghost = CreateGhost(TimeRange(ghost_start, ghost_start + footage_duration), ghost_in, dest_track);
// Increment track count for this track type
track_offsets[track_type]++;
TimelineViewGhostItem::AttachedFootage af = {it->first, ref.ToString()};
ghost->SetData(TimelineViewGhostItem::kAttachedFootage, QVariant::fromValue(af));
} else if (track_type == Track::kSubtitle) {
SubtitleParams sp = footage->GetSubtitleParams(ref.index());
for (const Subtitle &sub : sp) {
auto ghost = CreateGhost(sub.time() + ghost_start, 0, dest_track);
ghost->SetData(TimelineViewGhostItem::kAttachedFootage, QVariant::fromValue(sub));
}
parent()->AddTentativeSubtitleTrack();
}
}
// Stack each ghost one after the other
ghost_start += footage_duration;
}
}
void ImportTool::PrepGhosts(const rational& frame, const int& track_index)
{
if (parent()->GetConnectedNode()) {
FootageToGhosts(frame,
dragged_footage_,
parent()->GetConnectedNode()->GetVideoParams().time_base(),
track_index);
}
}
void ImportTool::DropGhosts(bool insert, MultiUndoCommand *parent_command)
{
auto command = new MultiUndoCommand();
if (MultiUndoCommand *c = parent()->TakeSubtitleSectionCommand()) {
command->add_child(c);
}
Project* dst_graph = nullptr;
Sequence* sequence = this->sequence();
bool open_sequence = false;
if (sequence) {
dst_graph = sequence->parent();
} else {
// There's no active timeline here, ask the user what to do
DropWithoutSequenceBehavior behavior = static_cast<DropWithoutSequenceBehavior>(OLIVE_CONFIG("DropWithoutSequenceBehavior").toInt());
if (behavior == kDWSAsk) {
QCheckBox* dont_ask_again_box = new QCheckBox(QCoreApplication::translate("ImportTool", "Don't ask me again"));
QMessageBox mbox(parent());
mbox.setIcon(QMessageBox::Question);
mbox.setWindowTitle(QCoreApplication::translate("ImportTool", "No Active Sequence"));
mbox.setText(QCoreApplication::translate("ImportTool", "No sequence is currently open. Would you like to create one?"));
mbox.setCheckBox(dont_ask_again_box);
QPushButton* auto_params_btn = mbox.addButton(QCoreApplication::translate("ImportTool", "Automatically Detect Parameters From Footage"), QMessageBox::YesRole);
QPushButton* manual_params_btn = mbox.addButton(QCoreApplication::translate("ImportTool", "Set Parameters Manually"), QMessageBox::NoRole);
mbox.addButton(QMessageBox::Cancel);
mbox.exec();
if (mbox.clickedButton() == auto_params_btn) {
behavior = kDWSAuto;
} else if (mbox.clickedButton() == manual_params_btn) {
behavior = kDWSManual;
} else {
behavior = kDWSDisable;
}
if (behavior != kDWSDisable && dont_ask_again_box->isChecked()) {
OLIVE_CONFIG("DropWithoutSequenceBehavior") = behavior;
}
}
if (behavior != kDWSDisable) {
Project* active_project = Core::instance()->GetActiveProject();
if (active_project) {
Sequence* new_sequence = Core::instance()->CreateNewSequenceForProject(active_project);
new_sequence->set_default_parameters();
bool sequence_is_valid = true;
// Even if the user selected manual, set from footage anyway so the user has a useful
// starting point
QVector<ViewerOutput*> footage_only;
for (auto it=dragged_footage_.cbegin(); it!=dragged_footage_.cend(); it++) {
if (!footage_only.contains(it->first)) {
footage_only.append(it->first);
}
}
new_sequence->set_parameters_from_footage(footage_only);
// If the user selected manual, show them a dialog with parameters
if (behavior == kDWSManual) {
SequenceDialog sd(new_sequence, SequenceDialog::kNew, parent());
sd.SetUndoable(false);
if (sd.exec() != QDialog::Accepted) {
sequence_is_valid = false;
}
}
if (sequence_is_valid) {
dst_graph = Core::instance()->GetActiveProject();
command->add_child(new NodeAddCommand(dst_graph, new_sequence));
command->add_child(new FolderAddChild(Core::instance()->GetSelectedFolderInActiveProject(), new_sequence));
command->add_child(new NodeSetPositionCommand(new_sequence, new_sequence, QPointF(0, 0)));
new_sequence->add_default_nodes(command);
FootageToGhosts(0, dragged_footage_, new_sequence->GetVideoParams().time_base(), 0);
if (MultiUndoCommand *c = parent()->TakeSubtitleSectionCommand()) {
command->add_child(c);
}
sequence = new_sequence;
// Set this as the sequence to open
open_sequence = true;
} else {
// If the sequence is valid, ownership is passed to AddItemCommand.
// Otherwise, we're responsible for deleting it.
delete new_sequence;
}
}
}
}
std::list<ClipBlock*> imported_clips;
if (dst_graph) {
QVector<Block*> block_items(parent()->GetGhostItems().size());
// Check if we're inserting (only valid if we're not creating this sequence ourselves)
if (insert && !open_sequence) {
InsertGapsAtGhostDestination(command);
}
for (int i=0;i<parent()->GetGhostItems().size();i++) {
TimelineViewGhostItem* ghost = parent()->GetGhostItems().at(i);
Block* block = nullptr;
Track::Type track_type = ghost->GetAdjustedTrack().type();
if (track_type == Track::kVideo || track_type == Track::kAudio) {
TimelineViewGhostItem::AttachedFootage footage_stream = ghost->GetData(TimelineViewGhostItem::kAttachedFootage).value<TimelineViewGhostItem::AttachedFootage>();
ClipBlock* clip = new ClipBlock();
block = clip;
clip->set_media_in(ghost->GetMediaIn());
command->add_child(new NodeAddCommand(dst_graph, clip));
// Position clip in its own context
command->add_child(new NodeSetPositionCommand(clip, clip, QPointF(0, 0)));
int dep_pos = kDefaultDistanceFromOutput;
// Position footage in its context
command->add_child(new NodeSetPositionCommand(footage_stream.footage, clip, QPointF(dep_pos, 0)));
dep_pos++;
switch (Track::Reference::TypeFromString(footage_stream.output)) {
case Track::kVideo:
{
TransformDistortNode* transform = new TransformDistortNode();
command->add_child(new NodeAddCommand(dst_graph, transform));
command->add_child(new NodeSetValueHintCommand(transform, TransformDistortNode::kTextureInput, -1, Node::ValueHint({NodeValue::kTexture}, footage_stream.output)));
command->add_child(new NodeEdgeAddCommand(footage_stream.footage, NodeInput(transform, TransformDistortNode::kTextureInput)));
command->add_child(new NodeEdgeAddCommand(transform, NodeInput(clip, ClipBlock::kBufferIn)));
command->add_child(new NodeSetPositionCommand(transform, clip, QPointF(dep_pos, 0)));
break;
}
case Track::kAudio:
{
VolumeNode* volume_node = new VolumeNode();
command->add_child(new NodeAddCommand(dst_graph, volume_node));
command->add_child(new NodeSetValueHintCommand(volume_node, VolumeNode::kSamplesInput, -1, Node::ValueHint({NodeValue::kSamples}, footage_stream.output)));
command->add_child(new NodeEdgeAddCommand(footage_stream.footage, NodeInput(volume_node, VolumeNode::kSamplesInput)));
command->add_child(new NodeEdgeAddCommand(volume_node, NodeInput(clip, ClipBlock::kBufferIn)));
command->add_child(new NodeSetPositionCommand(volume_node, clip, QPointF(dep_pos, 0)));
break;
}
default:
break;
}
// Link any clips so far that share the same Footage with this one
for (int j=0;j<i;j++) {
TimelineViewGhostItem::AttachedFootage footage_compare = parent()->GetGhostItems().at(j)->GetData(TimelineViewGhostItem::kAttachedFootage).value<TimelineViewGhostItem::AttachedFootage>();
if (footage_compare.footage == footage_stream.footage) {
Block::Link(block_items.at(j), clip);
}
}
imported_clips.push_back(clip);
} else if (track_type == Track::kSubtitle) {
Subtitle src = ghost->GetData(TimelineViewGhostItem::kAttachedFootage).value<Subtitle>();
SubtitleBlock *sub = new SubtitleBlock();
sub->SetText(src.text());
block = sub;
command->add_child(new NodeAddCommand(dst_graph, sub));
command->add_child(new NodeSetPositionCommand(sub, sub, QPointF(0, 0)));
}
block->set_length_and_media_out(ghost->GetLength());
command->add_child(new TrackPlaceBlockCommand(sequence->track_list(ghost->GetAdjustedTrack().type()),
ghost->GetAdjustedTrack().index(),
block,
ghost->GetAdjustedIn()));
block_items.replace(i, block);
}
}
if (open_sequence) {
command->add_child(new OpenSequenceCommand(sequence));
}
// Do command now because RequestInvalidatedFromConnected relies on track type, which will be
// "none" before this command is done because it won't be connected to any track
command->redo_now();
parent_command->add_child(command);
while (!imported_clips.empty()) {
imported_clips.front()->RequestInvalidatedFromConnected();
imported_clips.pop_front();
}
parent()->ClearGhosts();
dragged_footage_.clear();
}
TimelineViewGhostItem* ImportTool::CreateGhost(const TimeRange &range, const rational &media_in, const Track::Reference &track)
{
TimelineViewGhostItem* ghost = new TimelineViewGhostItem();
ghost->SetIn(range.in());
ghost->SetOut(range.out());
ghost->SetMediaIn(media_in);
ghost->SetTrack(track);
snap_points_.push_back(ghost->GetIn());
snap_points_.push_back(ghost->GetOut());
ghost->SetMode(Timeline::kMove);
parent()->AddGhost(ghost);
return ghost;
}
}
| 19,074
|
C++
|
.cpp
| 416
| 38.826923
| 197
| 0.67354
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,849
|
pointer.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/pointer.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include <QDebug>
#include <QToolTip>
#include "common/qtutils.h"
#include "common/range.h"
#include "config/config.h"
#include "core.h"
#include "node/block/gap/gap.h"
#include "node/block/transition/transition.h"
#include "node/nodeundo.h"
#include "pointer.h"
#include "timeline/timelineundopointer.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
PointerTool::PointerTool(TimelineWidget *parent) :
TimelineTool(parent),
movement_allowed_(true),
trimming_allowed_(true),
track_movement_allowed_(true),
gap_trimming_allowed_(false),
can_rubberband_select_(false),
rubberband_selecting_(false)
{
}
void PointerTool::MousePress(TimelineViewMouseEvent *event)
{
const Track::Reference& track_ref = event->GetTrack();
// Determine if item clicked on is selectable
clicked_item_ = parent()->GetItemAtScenePos(event->GetCoordinates());
ClipBlock *clip_clicked_item = dynamic_cast<ClipBlock*>(clicked_item_);
can_rubberband_select_ = false;
bool selectable_item = (clicked_item_
&& !parent()->GetTrackFromReference(track_ref)->IsLocked());
if (selectable_item) {
// Cache the clip's type for use later
drag_track_type_ = track_ref.type();
// If we haven't started dragging yet, we'll initiate a drag here
// Record where the drag started in timeline coordinates
drag_start_ = event->GetCoordinates();
// Determine whether we're trimming or moving based on the position of the cursor
drag_movement_mode_ = IsCursorInTrimHandle(clicked_item_,
event->GetSceneX());
// If we're not in a trim mode, we must be in a move mode (provided the tool allows movement and
// the block is not a gap)
if (drag_movement_mode_ == Timeline::kNone
&& movement_allowed_
&& !dynamic_cast<GapBlock*>(clicked_item_)) {
drag_movement_mode_ = Timeline::kMove;
}
// If this item is already selected, no further selection needs to be made
if (parent()->IsBlockSelected(clicked_item_)) {
// Collect item deselections
QVector<Block*> deselected_blocks;
// If shift is held, deselect it
if (event->GetModifiers() & Qt::ShiftModifier) {
parent()->RemoveSelection(clicked_item_);
deselected_blocks.append(clicked_item_);
// If not holding alt, deselect all links as well
if (clip_clicked_item && !(event->GetModifiers() & Qt::AltModifier)) {
parent()->SetBlockLinksSelected(clip_clicked_item, false);
deselected_blocks.append(clip_clicked_item->block_links());
}
}
parent()->SignalDeselectedBlocks(deselected_blocks);
return;
}
}
// If not holding shift, deselect all clips
if (!(event->GetModifiers() & Qt::ShiftModifier)) {
parent()->DeselectAll();
}
if (selectable_item) {
// Collect item selections
QVector<Block*> selected_blocks;
// Select this item
parent()->AddSelection(clicked_item_);
selected_blocks.append(clicked_item_);
// If not holding alt, select all links as well
if (clip_clicked_item && !(event->GetModifiers() & Qt::AltModifier)) {
parent()->SetBlockLinksSelected(clip_clicked_item, true);
selected_blocks.append(clip_clicked_item->block_links());
}
parent()->SignalSelectedBlocks(selected_blocks);
}
can_rubberband_select_ = (event->GetButton() == Qt::LeftButton // Only rubberband select from the primary mouse button
&& (!selectable_item || drag_movement_mode_ == Timeline::kNone)); // And if no item was selected OR the item isn't draggable
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)
{
if (can_rubberband_select_) {
if (!rubberband_selecting_) {
// If we clicked an item but are rubberband selecting anyway, deselect it now
if (clicked_item_) {
parent()->RemoveSelection(clicked_item_);
parent()->SignalDeselectedBlocks({clicked_item_});
clicked_item_ = nullptr;
}
parent()->StartRubberBandSelect(drag_global_start_);
rubberband_selecting_ = true;
}
// Process rubberband select
parent()->MoveRubberBandSelect(true, !(event->GetModifiers() & Qt::AltModifier));
} else {
// Process drag
if (!dragging_) {
// Now that the cursor has moved, we will assume the intention is to drag
// Clear snap points
snap_points_.clear();
// If we're performing an action, we can initiate ghosts
if (drag_movement_mode_ != Timeline::kNone) {
InitiateDrag(clicked_item_, drag_movement_mode_, event->GetModifiers());
}
// Set dragging to true here so no matter what, the drag isn't re-initiated until it's completed
dragging_ = true;
}
if (dragging_ && !parent()->GetGhostItems().isEmpty()) {
// We're already dragging AND we have ghosts to work with
ProcessDrag(event->GetCoordinates());
}
}
}
void PointerTool::MouseRelease(TimelineViewMouseEvent *event)
{
if (rubberband_selecting_) {
// Finish rubberband select
parent()->EndRubberBandSelect();
rubberband_selecting_ = false;
return;
}
if (dragging_) {
// If we were dragging, process the end of the drag
if (!parent()->GetGhostItems().isEmpty()) {
FinishDrag(event);
}
// Clean up
parent()->ClearGhosts();
snap_points_.clear();
dragging_ = false;
}
}
void PointerTool::HoverMove(TimelineViewMouseEvent *event)
{
if (trimming_allowed_) {
// No dragging, but we still want to process cursors
Block* block_at_cursor = parent()->GetItemAtScenePos(event->GetCoordinates());
if (block_at_cursor) {
switch (IsCursorInTrimHandle(block_at_cursor, event->GetSceneX())) {
case Timeline::kTrimIn:
parent()->setCursor(Qt::SizeHorCursor);
break;
case Timeline::kTrimOut:
parent()->setCursor(Qt::SizeHorCursor);
break;
default:
parent()->unsetCursor();
}
} else {
parent()->unsetCursor();
}
} else {
parent()->unsetCursor();
}
}
void SetGhostToSlideMode(TimelineViewGhostItem* g)
{
g->SetCanMoveTracks(false);
g->SetData(TimelineViewGhostItem::kGhostIsSliding, true);
}
void PointerTool::InitiateDragInternal(Block *clicked_item,
Timeline::MovementMode trim_mode,
Qt::KeyboardModifiers modifiers,
bool dont_roll_trims,
bool allow_nongap_rolling,
bool slide_instead_of_moving)
{
// Get list of selected blocks
QVector<Block*> clips = parent()->GetSelectedBlocks();
if (trim_mode == Timeline::kMove) {
// Gaps are not allowed to move, and since we only allow moving one block type at a time,
// dragging a gap is a no-op
if (dynamic_cast<GapBlock*>(clicked_item)) {
return;
}
bool sliding_due_to_transition = false;
if (!slide_instead_of_moving) {
// If the user tries to move a transition without moving the clip it belongs to, we turn
// this into a slide
foreach (Block* block, clips) {
if (TransitionBlock* transit = dynamic_cast<TransitionBlock*>(block)) {
if (!CanTransitionMove(transit, clips)) {
slide_instead_of_moving = true;
break;
}
} else if (ClipBlock *clip = dynamic_cast<ClipBlock*>(block)) {
if ((clip->in_transition() && !CanTransitionMove(clip->in_transition(), clips))
|| (clip->out_transition() && !CanTransitionMove(clip->out_transition(), clips))) {
slide_instead_of_moving = true;
break;
}
}
}
sliding_due_to_transition = slide_instead_of_moving;
}
if (slide_instead_of_moving) {
// This is a slide. What we do here is move clips within their own track, between the clips
// that they're already next to. We don't allow changing tracks or changing the order of
// blocks.
//
// For slides to be legal, we make all blocks "contiguous". This means that only one series
// of blocks can move at a time and prevents.
QHash<Track*, Block*> earliest_block_on_track;
QHash<Track*, Block*> latest_block_on_track;
foreach (Block* this_block, clips) {
Block* current_earliest = earliest_block_on_track.value(this_block->track(), nullptr);
if (!current_earliest || this_block->in() < current_earliest->in()) {
earliest_block_on_track.insert(this_block->track(), this_block);
}
Block* current_latest = latest_block_on_track.value(this_block->track(), nullptr);
if (!current_latest || this_block->out() > current_earliest->out()) {
latest_block_on_track.insert(this_block->track(), this_block);
}
}
for (auto i=earliest_block_on_track.constBegin(); i!=earliest_block_on_track.constEnd(); i++) {
// Make a contiguous stream
Track* track = i.key();
Block* earliest = i.value();
Block* latest = latest_block_on_track.value(i.key());
// First we add the block that's out trimming, the one prior to the earliest
{
TimelineViewGhostItem* earliest_ghost;
bool slide_with_earliest_previous = true;
if (sliding_due_to_transition && earliest->previous()) {
if (TransitionBlock *transit = dynamic_cast<TransitionBlock *>(earliest)) {
if (earliest->previous() != transit->connected_out_block()) {
slide_with_earliest_previous = false;
}
} else if (ClipBlock *clip = dynamic_cast<ClipBlock*>(earliest)) {
if (earliest->previous() != clip->in_transition()) {
slide_with_earliest_previous = false;
}
}
}
if (earliest->previous() && slide_with_earliest_previous) {
earliest_ghost = AddGhostFromBlock(earliest->previous(), Timeline::kTrimOut);
} else {
earliest_ghost = AddGhostFromNull(earliest->in(), earliest->in(), track->ToReference(), Timeline::kTrimOut);
}
SetGhostToSlideMode(earliest_ghost);
}
// Then we add the block that's in trimming, the one after the latest
if (latest->next()) {
TimelineViewGhostItem* latest_ghost;
bool slide_with_latest_next = true;
if (sliding_due_to_transition) {
if (TransitionBlock *transit = dynamic_cast<TransitionBlock *>(latest)) {
if (latest->next() != transit->connected_in_block()) {
slide_with_latest_next = false;
}
} else if (ClipBlock *clip = dynamic_cast<ClipBlock*>(latest)) {
if (latest->next() != clip->out_transition()) {
slide_with_latest_next = false;
}
}
}
if (slide_with_latest_next) {
latest_ghost = AddGhostFromBlock(latest->next(), Timeline::kTrimIn);
} else {
latest_ghost = AddGhostFromNull(latest->out(), latest->out(), track->ToReference(), Timeline::kTrimIn);
}
SetGhostToSlideMode(latest_ghost);
}
// Finally, we add all of the moving blocks in between
Block* b = nullptr;
do {
// On first run-through, set to earliest only. From then on, set to the next of the last
// in the loop.
if (b) {
b = b->next();
} else {
b = earliest;
}
TimelineViewGhostItem* between_ghost = AddGhostFromBlock(b, Timeline::kMove);
SetGhostToSlideMode(between_ghost);
} while (b != latest);
}
} else {
// Prepare for a standard pointer move by creating ghosts for them and any related blocks
foreach (Block* block, clips) {
if (dynamic_cast<GapBlock*>(block)) {
continue;
}
// Create ghost for this block
auto ghost = AddGhostFromBlock(block, trim_mode, true);
Q_UNUSED(ghost)
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(block)) {
if (clip->out_transition()) {
AddGhostFromBlock(clip->out_transition(), trim_mode, true);
}
if (clip->in_transition()) {
AddGhostFromBlock(clip->in_transition(), trim_mode, true);
}
}
}
}
} else {
// "Multi-trim" is trimming a clip on more than one track. Only the earliest (for in trimming)
// or latest (for out trimming) clip on each track can be trimmed. Therefore, it's only enabled
// if the clicked item is the earliest/latest on its track.
bool multitrim_enabled = IsClipTrimmable(clicked_item, clips, trim_mode);
// Create ghosts for trimming
for (Block* clip_item : clips) {
if (clip_item != clicked_item
&& (!multitrim_enabled || !IsClipTrimmable(clip_item, clips, trim_mode))) {
// Either multitrim is disabled or this clip is NOT the earliest/latest in its track. We
// won't include it.
continue;
}
Block* block = clip_item;
// Create ghost for this block
TimelineViewGhostItem* ghost = AddGhostFromBlock(block, trim_mode);
// If this side of the clip has a transition, we treat it more like a slide for that
// transition than a trim/roll
bool treat_trim_as_slide = false;
ClipBlock *cb = dynamic_cast<ClipBlock*>(block);
if (cb) {
// See if this clip has a transition attached, and move it with the trim if so
TransitionBlock* connected_transition;
// Get appropriate transition for the side of the clip
if (trim_mode == Timeline::kTrimIn) {
connected_transition = cb->in_transition();
} else {
connected_transition = cb->out_transition();
}
if (connected_transition) {
// We found a transition, we'll make this a "slide" action
TimelineViewGhostItem* transition_ghost = AddGhostFromBlock(connected_transition, Timeline::kMove);
// This will in effect be a slide with the transition moving between two other blocks
SetGhostToSlideMode(ghost);
SetGhostToSlideMode(transition_ghost);
treat_trim_as_slide = true;
// Further processing will apply to this transition rather than the clip
block = connected_transition;
}
}
// Standard pointer trimming in reality is a "roll" edit with an adjacent gap (one that may
// or may not exist already)
if (!dont_roll_trims) {
Block* adjacent = nullptr;
// Determine which block is adjacent
if (trim_mode == Timeline::kTrimIn) {
adjacent = block->previous();
} else {
adjacent = block->next();
}
// See if we can roll the adjacent or if we'll need to create our own gap
if (!dynamic_cast<GapBlock*>(block)
&& !allow_nongap_rolling && adjacent && !dynamic_cast<GapBlock*>(adjacent)
&& !(dynamic_cast<TransitionBlock*>(block)
&& ((trim_mode == Timeline::kTrimIn && static_cast<TransitionBlock*>(block)->connected_out_block() == adjacent)
|| (trim_mode == Timeline::kTrimOut && static_cast<TransitionBlock*>(block)->connected_in_block() == adjacent)))) {
adjacent = nullptr;
}
Timeline::MovementMode flipped_mode = FlipTrimMode(trim_mode);
QVector<TimelineViewGhostItem*> adjacent_ghosts;
if (adjacent) {
adjacent_ghosts.append(AddGhostFromBlock(adjacent, flipped_mode));
// Select adjacent's links if applicable
// FIXME: The check for `clips.size() == 1` may not be necessary, but I don't know yet.
// I'm only including it to prevent any potentially unintended behavior.
if (clips.size() == 1 && !(modifiers & Qt::AltModifier)) {
if (ClipBlock *adjacent_clip = dynamic_cast<ClipBlock*>(adjacent)) {
for (Block *adjacent_link : adjacent_clip->block_links()) {
adjacent_ghosts.append(AddGhostFromBlock(adjacent_link, flipped_mode));
}
}
}
} else if (trim_mode == Timeline::kTrimIn || block->next()) {
rational null_ghost_pos = (trim_mode == Timeline::kTrimIn) ? block->in() : block->out();
adjacent_ghosts.append(AddGhostFromNull(null_ghost_pos, null_ghost_pos, clip_item->track()->ToReference(), flipped_mode));
}
// If we have an adjacent block (for any reason), this is a roll edit and the adjacent is
// expected to fill the remaining space (no gap needs to be created)
ghost->SetData(TimelineViewGhostItem::kTrimIsARollEdit, static_cast<bool>(adjacent));
for (TimelineViewGhostItem *adjacent_ghost : adjacent_ghosts) {
if (adjacent_ghost) {
if (treat_trim_as_slide) {
// We're sliding a transition rather than a pure trim/roll
SetGhostToSlideMode(adjacent_ghost);
} else if (dynamic_cast<GapBlock*>(block)) {
ghost->SetData(TimelineViewGhostItem::kTrimShouldBeIgnored, true);
} else {
adjacent_ghost->SetData(TimelineViewGhostItem::kTrimShouldBeIgnored, true);
}
}
}
}
}
}
}
bool PointerTool::CanTransitionMove(TransitionBlock *transit, const QVector<Block *> &clips)
{
Block *out = transit->connected_out_block();
Block *in = transit->connected_in_block();
if ((out && !clips.contains(out)) || (in && !clips.contains(in))) {
return false;
}
return true;
}
void PointerTool::ProcessDrag(const TimelineCoordinate &mouse_pos)
{
// Calculate track movement
int track_movement = track_movement_allowed_
? mouse_pos.GetTrack().index() - drag_start_.GetTrack().index()
: 0;
// Determine frame movement
rational time_movement = mouse_pos.GetFrame() - drag_start_.GetFrame();
// Validate movement (enforce all ghosts moving in legal ways)
time_movement = ValidateTimeMovement(time_movement);
time_movement = ValidateInTrimming(time_movement);
time_movement = ValidateOutTrimming(time_movement);
// Perform snapping if enabled (adjusts time_movement if it's close to any potential snap points)
if (Core::instance()->snapping()) {
parent()->SnapPoint(snap_points_, &time_movement);
time_movement = ValidateTimeMovement(time_movement);
time_movement = ValidateInTrimming(time_movement);
time_movement = ValidateOutTrimming(time_movement);
}
// Validate ghosts that are being moved (clips from other track types do NOT get moved)
if (track_movement != 0) {
QVector<TimelineViewGhostItem*> validate_track_ghosts = parent()->GetGhostItems();
for (int i=0;i<validate_track_ghosts.size();i++) {
if (validate_track_ghosts.at(i)->GetTrack().type() != drag_track_type_) {
validate_track_ghosts.removeAt(i);
i--;
}
}
track_movement = ValidateTrackMovement(track_movement, validate_track_ghosts);
}
// Perform movement
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
switch (ghost->GetMode()) {
case Timeline::kNone:
break;
case Timeline::kTrimIn:
ghost->SetInAdjustment(time_movement);
ghost->SetMediaInAdjustment(time_movement);
break;
case Timeline::kTrimOut:
ghost->SetOutAdjustment(time_movement);
break;
case Timeline::kMove:
{
ghost->SetInAdjustment(time_movement);
ghost->SetOutAdjustment(time_movement);
// Track movement is only legal for moving, not for trimming
// Also, we only move the clips on the same track type that the drag started from
if (ghost->GetTrack().type() == drag_track_type_) {
ghost->SetTrackAdjustment(track_movement);
}
break;
}
}
}
// Regenerate tooltip and force it to update (otherwise the tooltip won't move as written in the
// documentation, and could get in the way of the cursor)
rational tooltip_timebase = parent()->GetTimebaseForTrackType(drag_start_.GetTrack().type());
QToolTip::hideText();
QToolTip::showText(QCursor::pos(),
QString::fromStdString(Timecode::time_to_timecode(time_movement,
tooltip_timebase,
Core::instance()->GetTimecodeDisplay(),
true)),
parent());
}
struct GhostBlockPair {
TimelineViewGhostItem* ghost;
Block* block;
};
void PointerTool::FinishDrag(TimelineViewMouseEvent *event)
{
QList<GhostBlockPair> blocks_moving;
QList<GhostBlockPair> blocks_sliding;
QList<GhostBlockPair> blocks_trimming;
// Sort ghosts depending on which ones are trimming, which are moving, and which are sliding
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (ghost->HasBeenAdjusted()) {
Block* b = QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kAttachedBlock));
if (ghost->GetData(TimelineViewGhostItem::kGhostIsSliding).toBool()) {
blocks_sliding.append({ghost, b});
} else if (ghost->GetMode() == Timeline::kMove) {
blocks_moving.append({ghost, b});
} else if (Timeline::IsATrimMode(ghost->GetMode())) {
blocks_trimming.append({ghost, b});
}
}
}
if (blocks_moving.isEmpty()
&& blocks_trimming.isEmpty()
&& blocks_sliding.isEmpty()) {
// No blocks were adjusted, so nothing to do
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
if (!blocks_trimming.isEmpty()) {
foreach (const GhostBlockPair& p, blocks_trimming) {
TimelineViewGhostItem* ghost = p.ghost;
if (!ghost->GetData(TimelineViewGhostItem::kTrimShouldBeIgnored).toBool()) {
// Must be an ordinary trim/roll
BlockTrimCommand* c = new BlockTrimCommand(parent()->GetTrackFromReference(ghost->GetAdjustedTrack()),
p.block,
ghost->GetAdjustedLength(),
ghost->GetMode());
if (event->GetModifiers() & Qt::ControlModifier) {
}
c->SetTrimIsARollEdit(ghost->GetData(TimelineViewGhostItem::kTrimIsARollEdit).toBool());
command->add_child(c);
}
}
if (blocks_moving.isEmpty() && blocks_sliding.isEmpty()) {
// Trim selections (deferring to moving/sliding blocks when necessary)
TimelineWidgetSelections new_sel = parent()->GetSelections();
TimelineViewGhostItem* reference_ghost = blocks_trimming.first().ghost;
if (reference_ghost->GetMode() == Timeline::kTrimIn) {
new_sel.TrimIn(reference_ghost->GetInAdjustment());
} else {
new_sel.TrimOut(reference_ghost->GetOutAdjustment());
}
command->add_child(new TimelineWidget::SetSelectionsCommand(parent(), new_sel, parent()->GetSelections()));
}
}
if (!blocks_moving.isEmpty()) {
// See if we're duplicated because ALT is held (only moved blocks can duplicate)
bool duplicate_clips = (event->GetModifiers() & Qt::AltModifier);
bool inserting = (event->GetModifiers() & Qt::ControlModifier);
// If we're not duplicating, "remove" the clips and replace them with gaps
if (!duplicate_clips) {
QVector<Block*> blocks_to_delete(blocks_moving.size());
for (int i=0; i<blocks_moving.size(); i++) {
blocks_to_delete[i] = blocks_moving.at(i).block;
}
parent()->ReplaceBlocksWithGaps(blocks_to_delete, false, command, false);
}
if (inserting) {
// If we're inserting, ripple everything at the destination with gaps
InsertGapsAtGhostDestination(command);
}
QMap<Node*, Node*> relinks;
// Now we can re-add each clip
foreach (const GhostBlockPair& p, blocks_moving) {
Block* block = p.block;
if (duplicate_clips) {
// Duplicate rather than move
// Place the copy instead of the original block
Block *new_block = static_cast<Block*>(Node::CopyNodeInGraph(block, command));
relinks.insert(block, new_block);
block = new_block;
if (ClipBlock *new_clip = dynamic_cast<ClipBlock*>(block)) {
new_clip->AddCachePassthroughFrom(static_cast<ClipBlock*>(p.block));
}
}
const Track::Reference& track_ref = p.ghost->GetAdjustedTrack();
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(track_ref.type()),
track_ref.index(),
block,
p.ghost->GetAdjustedIn()));
}
if (!relinks.empty()) {
for (auto it=relinks.cbegin(); it!=relinks.cend(); it++) {
// Re-connect links on duplicate clips
for (auto jt=it.key()->links().cbegin(); jt!=it.key()->links().cend(); jt++) {
Node *link = *jt;
Node *copy_link = relinks.value(link);
if (copy_link) {
command->add_child(new NodeLinkCommand(it.value(), copy_link, true));
}
}
// Re-connect transitions where applicable
if (ClipBlock *og_clip = dynamic_cast<ClipBlock *>(it.key())) {
ClipBlock *cp_clip = static_cast<ClipBlock *>(it.value());
TransitionBlock *og_in_transition = og_clip->in_transition();
TransitionBlock *og_out_transition = og_clip->out_transition();
if (og_in_transition && relinks.contains(og_in_transition)) {
TransitionBlock *cp_in_transition = static_cast<TransitionBlock *>(relinks.value(og_in_transition));
command->add_child(new NodeEdgeAddCommand(cp_clip, NodeInput(cp_in_transition, TransitionBlock::kInBlockInput)));
}
if (og_out_transition && relinks.contains(og_out_transition)) {
TransitionBlock *cp_out_transition = static_cast<TransitionBlock *>(relinks.value(og_out_transition));
command->add_child(new NodeEdgeAddCommand(cp_clip, NodeInput(cp_out_transition, TransitionBlock::kOutBlockInput)));
}
}
}
}
// Adjust selections
TimelineWidgetSelections new_sel = parent()->GetSelections();
new_sel.ShiftTime(blocks_moving.first().ghost->GetInAdjustment());
new_sel.ShiftTracks(drag_track_type_, blocks_moving.first().ghost->GetTrackAdjustment());
command->add_child(new TimelineWidget::SetSelectionsCommand(parent(), new_sel, parent()->GetSelections()));
}
if (!blocks_sliding.isEmpty()) {
// Assume that the blocks are contiguous per track as set up in InitiateGhostsInternal()
// All we need to do is sort them by track and order them
QHash<Track::Reference, QList<Block*> > slide_info;
QHash<Track::Reference, Block*> in_adjacents;
QHash<Track::Reference, Block*> out_adjacents;
rational movement;
foreach (const GhostBlockPair& p, blocks_sliding) {
const Track::Reference& track = p.ghost->GetTrack();
switch (p.ghost->GetMode()) {
case Timeline::kNone:
break;
case Timeline::kMove:
{
// These all should have moved uniformly, so as long as this is set, it should be fine
movement = p.ghost->GetInAdjustment();
QList<Block*>& blocks_on_this_track = slide_info[track];
bool inserted = false;
for (int i=0;i<blocks_on_this_track.size();i++) {
if (blocks_on_this_track.at(i)->in() > p.block->in()) {
blocks_on_this_track.insert(i, p.block);
inserted = true;
break;
}
}
if (!inserted) {
blocks_on_this_track.append(p.block);
}
break;
}
case Timeline::kTrimIn:
out_adjacents.insert(track, p.block);
break;
case Timeline::kTrimOut:
in_adjacents.insert(track, p.block);
break;
}
}
if (!movement.isNull()) {
for (auto i=slide_info.constBegin(); i!=slide_info.constEnd(); i++) {
command->add_child(new TrackSlideCommand(parent()->GetTrackFromReference(i.key()),
i.value(),
in_adjacents.value(i.key()),
out_adjacents.value(i.key()),
movement));
}
// Adjust selections
TimelineWidgetSelections new_sel = parent()->GetSelections();
new_sel.ShiftTime(movement);
command->add_child(new TimelineWidget::SetSelectionsCommand(parent(), new_sel, parent()->GetSelections()));
}
}
Core::instance()->undo_stack()->push(command, qApp->translate("PointerTool", "Moved Clips"));
}
Timeline::MovementMode PointerTool::IsCursorInTrimHandle(Block *block, qreal cursor_x)
{
const double kTrimHandle = QtUtils::QFontMetricsWidth(parent()->fontMetrics(), "H");
double block_left = parent()->TimeToScene(block->in());
double block_right = parent()->TimeToScene(block->out());
double block_width = block_right - block_left;
// Block is too narrow, no trimming allowed
if (block_width <= kTrimHandle * 2) {
return Timeline::kNone;
}
if (trimming_allowed_ && cursor_x <= block_left + kTrimHandle) {
return Timeline::kTrimIn;
} else if (trimming_allowed_ && cursor_x >= block_right - kTrimHandle) {
return Timeline::kTrimOut;
} else {
return Timeline::kNone;
}
}
void PointerTool::InitiateDrag(Block *clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers)
{
InitiateDragInternal(clicked_item, trim_mode, modifiers, false, false, false);
}
TimelineViewGhostItem *PointerTool::GetExistingGhostFromBlock(Block *block)
{
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kAttachedBlock)) == block) {
return ghost;
}
}
return nullptr;
}
//#define HIDE_GAP_GHOSTS
TimelineViewGhostItem* PointerTool::AddGhostFromBlock(Block* block, Timeline::MovementMode mode, bool check_if_exists)
{
// Ignore null blocks or blocks that aren't attached to a track because there's nothing we can
// do with either of those
if (!block || !block->track()) {
return nullptr;
}
TimelineViewGhostItem* ghost;
// Check if we've already made a ghost for this block
if (check_if_exists) {
if ((ghost = GetExistingGhostFromBlock(block))) {
return ghost;
}
}
// Otherwise, it's time to make a ghost for this block
ghost = TimelineViewGhostItem::FromBlock(block);
#ifdef HIDE_GAP_GHOSTS
if (block->type() == Block::kGap) {
ghost->SetInvisible(true);
}
#endif
AddGhostInternal(ghost, mode);
return ghost;
}
TimelineViewGhostItem* PointerTool::AddGhostFromNull(const rational &in, const rational &out, const Track::Reference& track, Timeline::MovementMode mode)
{
TimelineViewGhostItem* ghost = new TimelineViewGhostItem();
ghost->SetIn(in);
ghost->SetOut(out);
ghost->SetTrack(track);
#ifdef HIDE_GAP_GHOSTS
ghost->SetInvisible(true);
#endif
AddGhostInternal(ghost, mode);
return ghost;
}
void PointerTool::AddGhostInternal(TimelineViewGhostItem* ghost, Timeline::MovementMode mode)
{
ghost->SetMode(mode);
// Prepare snap points (optimizes snapping for later)
switch (mode) {
case Timeline::kMove:
snap_points_.push_back(ghost->GetIn());
snap_points_.push_back(ghost->GetOut());
break;
case Timeline::kTrimIn:
snap_points_.push_back(ghost->GetIn());
break;
case Timeline::kTrimOut:
snap_points_.push_back(ghost->GetOut());
break;
default:
break;
}
parent()->AddGhost(ghost);
}
bool PointerTool::IsClipTrimmable(Block *clip,
const QVector<Block*>& items,
const Timeline::MovementMode& mode)
{
foreach (Block* compare, items) {
if (clip->track() == compare->track()
&& clip != compare
&& ((compare->in() < clip->in() && mode == Timeline::kTrimIn)
|| (compare->out() > clip->out() && mode == Timeline::kTrimOut))) {
return false;
}
}
return true;
}
rational PointerTool::ValidateInTrimming(rational movement)
{
bool first_ghost = true;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (ghost->GetMode() != Timeline::kTrimIn) {
continue;
}
rational earliest_in = RATIONAL_MIN;
rational latest_in = ghost->GetOut();
rational ghost_timebase = parent()->GetTimebaseForTrackType(ghost->GetTrack().type());
// If the ghost must be at least one frame in size, limit the latest allowed in point
if (!ghost->CanHaveZeroLength()) {
latest_in -= ghost_timebase;
}
// Clamp adjusted value between the earliest and latest values
rational adjusted = ghost->GetIn() + movement;
rational clamped = std::clamp(adjusted, earliest_in, latest_in);
if (clamped != adjusted) {
movement = clamped - ghost->GetIn();
}
if (first_ghost) {
movement = SnapMovementToTimebase(ghost->GetIn(), movement, ghost_timebase);
first_ghost = false;
}
}
return movement;
}
rational PointerTool::ValidateOutTrimming(rational movement)
{
bool first_ghost = true;
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (ghost->GetMode() != Timeline::kTrimOut) {
continue;
}
// Determine earliest and latest out points
rational earliest_out = ghost->GetIn();
rational ghost_timebase = parent()->GetTimebaseForTrackType(ghost->GetTrack().type());
if (!ghost->CanHaveZeroLength()) {
earliest_out += ghost_timebase;
}
rational latest_out = RATIONAL_MAX;
// Clamp adjusted value between the earliest and latest values
rational adjusted = ghost->GetOut() + movement;
rational clamped = std::clamp(adjusted, earliest_out, latest_out);
if (clamped != adjusted) {
movement = clamped - ghost->GetOut();
}
if (first_ghost) {
movement = SnapMovementToTimebase(ghost->GetOut(), movement, ghost_timebase);
first_ghost = false;
}
}
return movement;
}
}
| 35,576
|
C++
|
.cpp
| 828
| 35.164251
| 153
| 0.639676
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,850
|
rolling.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/rolling.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "node/block/gap/gap.h"
#include "node/nodeundo.h"
#include "rolling.h"
namespace olive {
RollingTool::RollingTool(TimelineWidget* parent) :
PointerTool(parent)
{
SetMovementAllowed(false);
SetGapTrimmingAllowed(true);
}
void RollingTool::InitiateDrag(Block *clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers)
{
InitiateDragInternal(clicked_item, trim_mode, modifiers, false, true, false);
}
}
| 1,207
|
C++
|
.cpp
| 30
| 37.8
| 118
| 0.785592
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,851
|
transition.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/transition.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "node/block/transition/crossdissolve/crossdissolvetransition.h"
#include "node/block/transition/transition.h"
#include "node/factory.h"
#include "node/nodeundo.h"
#include "timeline/timelineundopointer.h"
#include "transition.h"
namespace olive {
TransitionTool::TransitionTool(TimelineWidget *parent) :
AddTool(parent)
{
}
void TransitionTool::HoverMove(TimelineViewMouseEvent *event)
{
ClipBlock *primary = nullptr;
ClipBlock *secondary = nullptr;
Timeline::MovementMode trim_mode = Timeline::kNone;
rational transition_start_point;
GetBlocksAtCoord(event->GetCoordinates(), &primary, &secondary, &trim_mode, &transition_start_point);
if (trim_mode == Timeline::kTrimIn) {
std::swap(primary, secondary);
}
parent()->SetViewTransitionOverlay(primary, secondary);
}
void TransitionTool::MousePress(TimelineViewMouseEvent *event)
{
ClipBlock *primary, *secondary;
Timeline::MovementMode trim_mode;
rational transition_start_point;
if (!GetBlocksAtCoord(event->GetCoordinates(), &primary, &secondary, &trim_mode, &transition_start_point)) {
return;
}
// Create ghost
ghost_ = new TimelineViewGhostItem();
ghost_->SetTrack(event->GetTrack());
ghost_->SetIn(transition_start_point);
ghost_->SetOut(transition_start_point);
ghost_->SetMode(trim_mode);
ghost_->SetData(TimelineViewGhostItem::kAttachedBlock, QtUtils::PtrToValue(primary));
dual_transition_ = (secondary);
if (secondary)
ghost_->SetData(TimelineViewGhostItem::kReferenceBlock, QtUtils::PtrToValue(secondary));
parent()->AddGhost(ghost_);
snap_points_.push_back(transition_start_point);
// Set the drag start point
drag_start_point_ = event->GetFrame();
}
void TransitionTool::MouseMove(TimelineViewMouseEvent *event)
{
if (!ghost_) {
return;
}
MouseMoveInternal(event->GetFrame(), dual_transition_);
}
void TransitionTool::MouseRelease(TimelineViewMouseEvent *event)
{
const Track::Reference& track = ghost_->GetTrack();
if (ghost_) {
if (!ghost_->GetAdjustedLength().isNull()) {
TransitionBlock* transition;
if (Core::instance()->GetSelectedTransition().isEmpty()) {
// Fallback if the user hasn't selected one yet
transition = new CrossDissolveTransition();
} else {
transition = static_cast<TransitionBlock*>(NodeFactory::CreateFromID(Core::instance()->GetSelectedTransition()));
}
// Set transition length
rational len = ghost_->GetAdjustedLength();
transition->set_length_and_media_out(len);
MultiUndoCommand* command = new MultiUndoCommand();
// Place transition in place
command->add_child(new NodeAddCommand(parent()->GetConnectedNode()->parent(),
transition));
command->add_child(new NodeSetPositionCommand(transition, transition, QPointF(0, 0)));
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(track.type()),
track.index(),
transition,
ghost_->GetAdjustedIn()));
if (dual_transition_) {
// Block mouse is hovering over
Block* active_block = QtUtils::ValueToPtr<Block>(ghost_->GetData(TimelineViewGhostItem::kAttachedBlock));
// Block mouse is next to
Block* friend_block = QtUtils::ValueToPtr<Block>(ghost_->GetData(TimelineViewGhostItem::kReferenceBlock));
// Use ghost mode to determine which block is which
Block* out_block = (ghost_->GetMode() == Timeline::kTrimIn) ? friend_block : active_block;
Block* in_block = (ghost_->GetMode() == Timeline::kTrimIn) ? active_block : friend_block;
// Connect block to transition
command->add_child(new NodeEdgeAddCommand(out_block,
NodeInput(transition, TransitionBlock::kOutBlockInput)));
command->add_child(new NodeEdgeAddCommand(in_block,
NodeInput(transition, TransitionBlock::kInBlockInput)));
command->add_child(new NodeSetPositionCommand(out_block, transition, QPointF(-1, -0.5)));
command->add_child(new NodeSetPositionCommand(in_block, transition, QPointF(-1, 0.5)));
} else {
Block* block_to_transition = QtUtils::ValueToPtr<Block>(ghost_->GetData(TimelineViewGhostItem::kAttachedBlock));
QString transition_input_to_connect;
if (ghost_->GetMode() == Timeline::kTrimIn) {
transition_input_to_connect = TransitionBlock::kInBlockInput;
} else {
transition_input_to_connect = TransitionBlock::kOutBlockInput;
}
// Connect block to transition
command->add_child(new NodeEdgeAddCommand(block_to_transition,
NodeInput(transition, transition_input_to_connect)));
command->add_child(new NodeSetPositionCommand(block_to_transition, transition, QPointF(-1, 0)));
}
Core::instance()->undo_stack()->push(command, qApp->translate("TransitionTool", "Created Transition"));
parent()->SetViewTransitionOverlay(nullptr, nullptr);
}
parent()->ClearGhosts();
snap_points_.clear();
ghost_ = nullptr;
}
}
bool TransitionTool::GetBlocksAtCoord(const TimelineCoordinate &coord, ClipBlock **primary, ClipBlock **secondary, Timeline::MovementMode *ptrim_mode, rational *start_point)
{
const Track::Reference& track = coord.GetTrack();
Track* t = parent()->GetTrackFromReference(track);
rational cursor_frame = coord.GetFrame();
if (!t || t->IsLocked()) {
return false;
}
Block* block_at_time = t->NearestBlockBeforeOrAt(coord.GetFrame());
if (!dynamic_cast<ClipBlock*>(block_at_time)) {
return false;
}
// Determine which side of the clip the transition belongs to
rational transition_start_point;
Timeline::MovementMode trim_mode;
rational tenth_point = block_at_time->length() / 10;
Block* other_block = nullptr;
if (cursor_frame < (block_at_time->in() + block_at_time->length() / 2)) {
if (static_cast<ClipBlock*>(block_at_time)->in_transition()) {
// This clip already has a transition here
return false;
}
ClipBlock *adjacent = dynamic_cast<ClipBlock*>(block_at_time->previous());
if (adjacent) {
tenth_point = std::min(tenth_point, adjacent->length()/10);
}
transition_start_point = block_at_time->in();
trim_mode = Timeline::kTrimIn;
if (cursor_frame < (block_at_time->in() + tenth_point) && adjacent) {
other_block = adjacent;
}
} else {
if (static_cast<ClipBlock*>(block_at_time)->out_transition()) {
// This clip already has a transition here
return false;
}
ClipBlock *adjacent = dynamic_cast<ClipBlock*>(block_at_time->next());
if (adjacent) {
tenth_point = std::min(tenth_point, adjacent->length()/10);
}
transition_start_point = block_at_time->out();
trim_mode = Timeline::kTrimOut;
if (cursor_frame > block_at_time->out() - tenth_point && adjacent) {
other_block = block_at_time->next();
}
}
*primary = static_cast<ClipBlock*>(block_at_time);
*secondary = static_cast<ClipBlock*>(other_block);
*ptrim_mode = trim_mode;
*start_point = transition_start_point;
return true;
}
}
| 8,156
|
C++
|
.cpp
| 181
| 38.502762
| 173
| 0.683373
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,852
|
slip.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/slip.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "slip.h"
#include <QToolTip>
#include "config/config.h"
#include "timeline/timelineundogeneral.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
SlipTool::SlipTool(TimelineWidget *parent) :
PointerTool(parent)
{
SetTrimmingAllowed(false);
SetTrackMovementAllowed(false);
}
void SlipTool::ProcessDrag(const TimelineCoordinate &mouse_pos)
{
// Determine frame movement
rational time_movement = drag_start_.GetFrame() - mouse_pos.GetFrame();
// Validate slip (enforce all ghosts moving in legal ways)
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
if (ghost->GetMediaIn() + time_movement < 0) {
time_movement = -ghost->GetMediaIn();
}
}
// Perform slip
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
ghost->SetMediaInAdjustment(time_movement);
}
// Generate tooltip and force it to to update (otherwise the tooltip won't move as written in the
// documentation, and could get in the way of the cursor)
rational tooltip_timebase = parent()->GetTimebaseForTrackType(drag_start_.GetTrack().type());
QToolTip::hideText();
QToolTip::showText(QCursor::pos(),
QString::fromStdString(Timecode::time_to_timecode(time_movement,
tooltip_timebase,
Core::instance()->GetTimecodeDisplay(),
true)),
parent());
}
void SlipTool::FinishDrag(TimelineViewMouseEvent *event)
{
Q_UNUSED(event)
MultiUndoCommand* command = new MultiUndoCommand();
// Find earliest point to ripple around
foreach (TimelineViewGhostItem* ghost, parent()->GetGhostItems()) {
Block* b = QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kAttachedBlock));
ClipBlock *cb = dynamic_cast<ClipBlock*>(b);
if (cb) {
command->add_child(new BlockSetMediaInCommand(cb, ghost->GetAdjustedMediaIn()));
}
}
Core::instance()->undo_stack()->push(command, qApp->translate("SlipTool", "Slipped %1 Clip(s)").arg(parent()->GetGhostItems().size()));
}
}
| 2,940
|
C++
|
.cpp
| 66
| 37.742424
| 137
| 0.685354
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,853
|
edit.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/edit.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "edit.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
EditTool::EditTool(TimelineWidget* parent) :
BeamTool(parent)
{
}
void EditTool::MousePress(TimelineViewMouseEvent *event)
{
if (!(event->GetModifiers() & Qt::ShiftModifier)) {
parent()->DeselectAll();
}
}
void EditTool::MouseMove(TimelineViewMouseEvent *event)
{
if (dragging_) {
rational end_frame = event->GetFrame(true);
if (Core::instance()->snapping()) {
rational movement;
parent()->SnapPoint({end_frame}, &movement);
if (!movement.isNull()) {
end_frame += movement;
}
}
parent()->SetSelections(start_selections_, false);
parent()->AddSelection(TimeRange(start_coord_.GetFrame(), end_frame),
start_coord_.GetTrack());
} else {
start_selections_ = parent()->GetSelections();
dragging_ = true;
start_coord_ = event->GetCoordinates(true);
// Snap if we're snapping
if (Core::instance()->snapping()) {
rational movement;
parent()->SnapPoint({start_coord_.GetFrame()}, &movement);
if (!movement.isNull()) {
start_coord_.SetFrame(start_coord_.GetFrame() + movement);
}
}
dragging_ = true;
}
}
void EditTool::MouseRelease(TimelineViewMouseEvent *event)
{
auto current_sel = parent()->GetSelections();
parent()->SetSelections(start_selections_, false);
parent()->SetSelections(current_sel, true);
dragging_ = false;
}
void EditTool::MouseDoubleClick(TimelineViewMouseEvent *event)
{
Block* item = parent()->GetItemAtScenePos(event->GetCoordinates());
if (item && !item->track()->IsLocked()) {
parent()->AddSelection(item);
}
}
}
| 2,414
|
C++
|
.cpp
| 71
| 29.929577
| 73
| 0.700258
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,854
|
zoom.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/zoom.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "zoom.h"
namespace olive {
ZoomTool::ZoomTool(TimelineWidget *parent) :
TimelineTool(parent)
{
}
void ZoomTool::MousePress(TimelineViewMouseEvent *event)
{
Q_UNUSED(event)
drag_global_start_ = QCursor::pos();
}
void ZoomTool::MouseMove(TimelineViewMouseEvent *event)
{
Q_UNUSED(event)
if (!dragging_) {
parent()->StartRubberBandSelect(drag_global_start_);
dragging_ = true;
}
parent()->MoveRubberBandSelect(false, false);
}
void ZoomTool::MouseRelease(TimelineViewMouseEvent *event)
{
int scroll_value;
if (dragging_) {
// Zoom into the rubberband selection
QRect screen_coords = parent()->GetRubberBandGeometry();
parent()->EndRubberBandSelect();
TimelineView* reference_view = parent()->GetFirstTimelineView();
QPointF scene_topleft = reference_view->mapToScene(reference_view->mapFrom(parent(), screen_coords.topLeft()));
QPointF scene_bottomright = reference_view->mapToScene(reference_view->mapFrom(parent(), screen_coords.bottomRight()));
double scene_left = scene_topleft.x();
double scene_right = scene_bottomright.x();
// Normalize scale to 1.0 scale
double scene_width = (scene_right - scene_left) / parent()->GetScale();
double new_scale = qMin(parent()->GetFirstTimelineView()->GetMaximumScale(), static_cast<double>(reference_view->viewport()->width()) / scene_width);
parent()->SetScale(new_scale);
scroll_value = qMax(0, qRound(scene_left / parent()->GetScale() * new_scale));
dragging_ = false;
} else {
// Simple zoom in/out at the cursor position
double scale = parent()->GetScale();
if (event->GetModifiers() & Qt::AltModifier) {
// Zoom out if the user clicks while holding Alt
scale *= 0.5;
} else {
// Otherwise zoom in
scale *= 2.0;
}
parent()->SetScale(scale);
// Adjust scroll location for new scale
double frame_x = event->GetFrame().toDouble() * scale;
scroll_value = qMax(0, qRound(frame_x - parent()->GetFirstTimelineView()->viewport()->width()/2));
}
parent()->QueueScroll(scroll_value);
}
}
| 2,865
|
C++
|
.cpp
| 71
| 36.507042
| 153
| 0.719971
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,855
|
slide.cpp
|
olive-editor_olive/app/widget/timelinewidget/tool/slide.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "widget/timelinewidget/timelinewidget.h"
#include "node/block/gap/gap.h"
#include "node/nodeundo.h"
#include "slide.h"
namespace olive {
SlideTool::SlideTool(TimelineWidget* parent) :
PointerTool(parent)
{
SetTrimmingAllowed(false);
SetTrackMovementAllowed(false);
SetGapTrimmingAllowed(true);
}
void SlideTool::InitiateDrag(Block *clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers)
{
InitiateDragInternal(clicked_item, trim_mode, modifiers, false, true, true);
}
}
| 1,232
|
C++
|
.cpp
| 31
| 37.290323
| 116
| 0.785714
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,856
|
timelineview.cpp
|
olive-editor_olive/app/widget/timelinewidget/view/timelineview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timelineview.h"
#include <QDebug>
#include <QMimeData>
#include <QMouseEvent>
#include <QScrollBar>
#include <QtMath>
#include <QPen>
#include "config/config.h"
#include "common/qtutils.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 {
#define super TimeBasedView
TimelineView::TimelineView(Qt::Alignment vertical_alignment, QWidget *parent) :
super(parent),
selections_(nullptr),
ghosts_(nullptr),
show_beam_cursor_(false),
connected_track_list_(nullptr),
transition_overlay_out_(nullptr),
transition_overlay_in_(nullptr)
{
Q_ASSERT(vertical_alignment == Qt::AlignTop || vertical_alignment == Qt::AlignBottom);
setAlignment(Qt::AlignLeft | vertical_alignment);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setBackgroundRole(QPalette::Window);
setContextMenuPolicy(Qt::CustomContextMenu);
viewport()->setMouseTracking(true);
SetIsTimelineAxes(true);
}
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)) {
GetViewerNode()->SetPlayhead(it.key()->time().in());
break;
}
}
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event);
if (HandPress(event)
|| (!GetItemAtScenePos(timeline_event.GetFrame(), timeline_event.GetTrack().index()) && Core::instance()->tool() != Tool::kAdd && PlayheadPress(event))) {
// Let the parent handle this
return;
}
if (dragMode() != GetDefaultDragMode()) {
// Use default behavior when hand dragging for instance
super::mousePressEvent(event);
return;
}
emit MousePressed(&timeline_event);
}
void TimelineView::mouseMoveEvent(QMouseEvent *event)
{
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event);
if (HandMove(event) || PlayheadMove(event)) {
// Let the parent handle this
return;
}
if (dragMode() != GetDefaultDragMode()) {
super::mouseMoveEvent(event);
return;
}
if (event->buttons() == Qt::NoButton) {
Block* b = GetItemAtScenePos(timeline_event.GetFrame(), timeline_event.GetTrack().index());
if (b) {
setToolTip(tr("In: %1\nOut: %2\nDuration: %3").arg(
QString::fromStdString(Timecode::time_to_timecode(b->in(), timebase(), Core::instance()->GetTimecodeDisplay())),
QString::fromStdString(Timecode::time_to_timecode(b->out(), timebase(), Core::instance()->GetTimecodeDisplay())),
QString::fromStdString(Timecode::time_to_timecode(b->length(), timebase(), Core::instance()->GetTimecodeDisplay()))
));
} else {
setToolTip(QString());
}
}
emit MouseMoved(&timeline_event);
}
void TimelineView::mouseReleaseEvent(QMouseEvent *event)
{
if (HandRelease(event) || PlayheadRelease(event)) {
// Let the parent handle this
return;
}
if (dragMode() != GetDefaultDragMode()) {
super::mouseReleaseEvent(event);
return;
}
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event);
emit MouseReleased(&timeline_event);
}
void TimelineView::mouseDoubleClickEvent(QMouseEvent *event)
{
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event);
emit MouseDoubleClicked(&timeline_event);
}
void TimelineView::dragEnterEvent(QDragEnterEvent *event)
{
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event->pos(), Qt::NoButton, event->keyboardModifiers());
timeline_event.SetMimeData(event->mimeData());
timeline_event.SetEvent(event);
emit DragEntered(&timeline_event);
}
void TimelineView::dragMoveEvent(QDragMoveEvent *event)
{
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event->pos(), Qt::NoButton, event->keyboardModifiers());
timeline_event.SetMimeData(event->mimeData());
timeline_event.SetEvent(event);
emit DragMoved(&timeline_event);
}
void TimelineView::dragLeaveEvent(QDragLeaveEvent *event)
{
emit DragLeft(event);
}
void TimelineView::dropEvent(QDropEvent *event)
{
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event->pos(), Qt::NoButton, event->keyboardModifiers());
timeline_event.SetMimeData(event->mimeData());
timeline_event.SetEvent(event);
emit DragDropped(&timeline_event);
}
void TimelineView::drawBackground(QPainter *painter, const QRectF &rect)
{
if (!connected_track_list_) {
return;
}
painter->setPen(palette().base().color());
int line_y = 0;
foreach (Track* track, connected_track_list_->GetTracks()) {
line_y += track->GetTrackHeightInPixels();
// One px gap between tracks
line_y++;
int this_line_y;
if (alignment() & Qt::AlignTop) {
this_line_y = line_y;
} else {
this_line_y = -line_y;
}
painter->drawLine(qRound(rect.left()), this_line_y, qRound(rect.right()), this_line_y);
}
}
void TimelineView::drawForeground(QPainter *painter, const QRectF &rect)
{
if (!connected_track_list_) {
return;
}
// Draw block backgrounds
DrawBlocks(painter, false);
// Draw selections
if (selections_ && !selections_->isEmpty()) {
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(0, 0, 0, 64));
for (auto it=selections_->cbegin(); it!=selections_->cend(); it++) {
if (it.key().type() == connected_track_list_->type()) {
int track_index = it.key().index();
foreach (const TimeRange& range, it.value()) {
painter->drawRect(TimeToScene(range.in()),
GetTrackY(track_index),
TimeToScene(range.length()),
GetTrackHeight(track_index));
}
}
}
}
// Draw block foregrounds
DrawBlocks(painter, true);
// Draw ghosts
if (ghosts_ && !ghosts_->isEmpty()) {
foreach (TimelineViewGhostItem* ghost, (*ghosts_)) {
if (ghost->GetTrack().type() == connected_track_list_->type()
&& !ghost->IsInvisible()) {
int track_index = ghost->GetAdjustedTrack().index();
Block *attached = QtUtils::ValueToPtr<Block>(ghost->GetData(TimelineViewGhostItem::kAttachedBlock));
if (attached && OLIVE_CONFIG("ShowClipWhileDragging").toBool()) {
int adj_track = ghost->GetAdjustedTrack().index();
qreal track_top = GetTrackY(adj_track);
qreal track_height = GetTrackHeight(adj_track);
qreal old_opacity = painter->opacity();
painter->setOpacity(0.5);
rational in = ghost->GetAdjustedIn(), out = ghost->GetAdjustedOut(), media_in = ghost->GetAdjustedMediaIn();
DrawBlock(painter, false, attached, track_top, track_height, in, out, media_in);
DrawBlock(painter, true, attached, track_top, track_height, in, out, media_in);
painter->setOpacity(old_opacity);
}
painter->setPen(QPen(Qt::yellow, 2));
painter->setBrush(Qt::NoBrush);
painter->drawRect(TimeToScene(ghost->GetAdjustedIn()),
GetTrackY(track_index),
TimeToScene(ghost->GetAdjustedLength()),
GetTrackHeight(track_index));
}
}
}
// Draw beam cursor
if (show_beam_cursor_
&& cursor_coord_.GetTrack().type() == connected_track_list_->type()) {
painter->setPen(Qt::gray);
double cursor_x = TimeToScene(cursor_coord_.GetFrame());
int track_index = cursor_coord_.GetTrack().index();
int track_y = GetTrackY(track_index);
painter->drawLine(cursor_x,
track_y,
cursor_x,
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(GetViewerNode()->GetPlayhead()) - x, GetTrackHeight(recording_coord_.GetTrack().index()));
}
// Draw standard TimelineViewBase things (such as playhead)
super::drawForeground(painter, rect);
}
void TimelineView::ToolChangedEvent(Tool::Item tool)
{
switch (tool) {
case Tool::kRazor:
setCursor(Qt::SplitHCursor);
break;
case Tool::kEdit:
setCursor(Qt::IBeamCursor);
break;
case Tool::kAdd:
case Tool::kTransition:
case Tool::kZoom:
case Tool::kRecord :
setCursor(Qt::CrossCursor);
break;
case Tool::kTrackSelect:
setCursor(Qt::SizeHorCursor); // FIXME: Not the ideal cursor
break;
default:
unsetCursor();
}
// Hide/show cursor if necessary
if (show_beam_cursor_) {
show_beam_cursor_ = false;
viewport()->update();
}
}
void TimelineView::SceneRectUpdateEvent(QRectF &rect)
{
if (alignment() & Qt::AlignTop) {
rect.setTop(0);
rect.setBottom(GetHeightOfAllTracks() + height() / 2);
} else if (alignment() & Qt::AlignBottom) {
rect.setBottom(0);
rect.setTop(GetHeightOfAllTracks() - height() / 2);
}
}
Track::Type TimelineView::ConnectedTrackType()
{
if (connected_track_list_) {
return connected_track_list_->type();
}
return Track::kNone;
}
TimelineCoordinate TimelineView::ScreenToCoordinate(const QPoint& pt)
{
return SceneToCoordinate(mapToScene(pt));
}
TimelineCoordinate TimelineView::SceneToCoordinate(const QPointF& pt)
{
return TimelineCoordinate(SceneToTime(pt.x()), Track::Reference(ConnectedTrackType(), SceneToTrack(pt.y())));
}
TimelineViewMouseEvent TimelineView::CreateMouseEvent(QMouseEvent *event)
{
return CreateMouseEvent(event->pos(), event->button(), event->modifiers());
}
TimelineViewMouseEvent TimelineView::CreateMouseEvent(const QPoint& pos, Qt::MouseButton button, Qt::KeyboardModifiers modifiers)
{
QPointF scene_pt = mapToScene(pos);
return TimelineViewMouseEvent(scene_pt,
pos,
GetScale(),
timebase(),
Track::Reference(ConnectedTrackType(), SceneToTrack(scene_pt.y())),
button,
modifiers);
}
void TimelineView::DrawBlocks(QPainter *painter, bool foreground)
{
rational start_time = SceneToTime(GetTimelineLeftBound());
rational end_time = SceneToTime(GetTimelineRightBound());
foreach (Track* track, connected_track_list_->GetTracks()) {
// Get first visible block in this track
Block* block = track->NearestBlockBeforeOrAt(start_time);
qreal track_top = GetTrackY(track->Index());
qreal track_height = GetTrackHeight(track->Index());
while (block) {
DrawBlock(painter, foreground, block, track_top, track_height);
if (block->out() >= end_time) {
// Rest of the clips are offscreen, can break loop now
break;
}
block = block->next();
}
}
}
void TimelineView::DrawBlock(QPainter *painter, bool foreground, Block *block, qreal block_top, qreal block_height, const rational &in, const rational &out, const rational &media_in)
{
if (dynamic_cast<ClipBlock*>(block) || dynamic_cast<TransitionBlock*>(block)) {
qreal block_in = TimeToScene(in);
qreal block_left = qMax(GetTimelineLeftBound(), block_in);
qreal block_right = qMin(GetTimelineRightBound(), TimeToScene(out)) - 1;
QRectF r(block_left,
block_top,
block_right - block_left,
block_height);
QColor shadow_color = block->is_enabled() ? QtUtils::toQColor(block->color()).darker() : QColor(Qt::darkGray).darker();
const qreal MINIMUM_RECT_WIDTH = 2;
const qreal MINIMUM_DETAIL_WIDTH = 8;
if (r.width() <= MINIMUM_RECT_WIDTH) {
if (!foreground) {
// Just draw a green background
// Width is likely fractional, so we ceil it and add 1 to ensure the entire width of the
// rect is painted
r.setWidth(std::ceil(r.width())+1);
painter->fillRect(r, shadow_color);
}
} else {
QFontMetrics fm = fontMetrics();
int text_height = fm.height();
int text_padding = text_height/4; // This ties into the track minimum height being 1.5
int text_total_height = text_height + text_padding + text_padding;
if (foreground) {
painter->setBrush(Qt::NoBrush);
if (r.width() > MINIMUM_DETAIL_WIDTH) {
QString using_label = block->GetLabelOrName();
QRectF text_rect = r.adjusted(text_padding, text_padding, -text_padding, -text_padding);
painter->setPen(block->is_enabled() ? ColorCoding::GetUISelectorColor(block->color()) : Qt::lightGray);
painter->drawText(text_rect, Qt::AlignLeft | Qt::AlignTop, using_label);
if (block->HasLinks()) {
int text_width = qMin(qRound(text_rect.width()),
QtUtils::QFontMetricsWidth(fm, using_label));
int underline_y = text_rect.y() + text_height;
painter->drawLine(text_rect.x(), underline_y, text_width + text_rect.x(), underline_y);
}
}
qreal line_bottom = block_top+block_height-1;
painter->setPen(Qt::white);
painter->drawLine(block_left, block_top, block_right, block_top);
painter->drawLine(block_left, block_top, block_left, line_bottom);
painter->setPen(shadow_color);
painter->drawLine(block_left, line_bottom, block_right, line_bottom);
painter->drawLine(block_right, line_bottom, block_right, block_top);
} else {
painter->setPen(Qt::NoPen);
painter->setBrush(block->is_enabled() ? block->brush(block_top, block_top + block_height) : Qt::gray);
painter->drawRect(r);
if (r.width() > MINIMUM_DETAIL_WIDTH) {
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(block)) {
QRect preview_rect = r.toRect();
// Draw clip thumbnails
if (clip->GetTrackType() == Track::kVideo
&& OLIVE_CONFIG("TimelineThumbnailMode").toInt() != Timeline::kThumbnailOff) {
// Start thumbnails underneath clip name
preview_rect.adjust(0, text_total_height, 0, 0);
if (preview_rect.height() > r.height()/3) {
if (const FrameHashCache *thumbs = clip->thumbnails()) {
QRect thumb_rect;
painter->setRenderHint(QPainter::SmoothPixmapTransform);
painter->setClipRect(preview_rect);
if (OLIVE_CONFIG("TimelineThumbnailMode") == Timeline::kThumbnailOn) {
Sequence *s = clip->track()->sequence();
int width = s->GetVideoParams().width();
int height = s->GetVideoParams().height();
int start;
if (height > 0) { // Prevent divide by zero/invalid params
double scale = double(preview_rect.height())/double(height);
thumb_rect.setWidth(width * scale);
start = (((preview_rect.left() - int(qFloor(block_in))) / thumb_rect.width()) * thumb_rect.width()) + qFloor(block_in);
} else {
start = preview_rect.left();
}
for (int i=start; i<preview_rect.right(); i+=thumb_rect.width()+1) {
rational time_here = SceneToTime(i - block_in, GetScale(), connected_track_list_->parent()->GetVideoParams().frame_rate_as_time_base()) + media_in;
DrawThumbnail(painter, thumbs, time_here, i, preview_rect, &thumb_rect);
}
} else {
rational time = clip->media_range().in();
time = Timecode::snap_time_to_timebase(time, thumbs->GetTimebase(), Timecode::kFloor);
DrawThumbnail(painter, thumbs, time, block_left, preview_rect, &thumb_rect);
}
painter->setClipping(false);
}
}
}
// Draw waveform
if (clip->GetTrackType() == Track::kAudio
&& OLIVE_CONFIG("TimelineWaveformMode").toInt() == Timeline::kWaveformsEnabled) {
if (const AudioWaveformCache *wave = clip->waveform()) {
rational waveform_start = SceneToTime(block_left - block_in, GetScale(), connected_track_list_->parent()->GetAudioParams().sample_rate_as_time_base()) + media_in;
painter->setPen(shadow_color);
wave->Draw(painter, preview_rect, this->GetScale(), waveform_start);
}
}
// Draw zebra stripes and markers
if (clip->connected_viewer()) {
if (!clip->connected_viewer()->GetLength().isNull()) {
painter->setPen(shadow_color);
if (clip->media_in() < 0) {
qreal zebra_right = TimeToScene(clip->in() - clip->media_in());
switch (clip->loop_mode()) {
case LoopMode::kLoopModeOff:
// Draw stripes for sections of clip < 0
if (zebra_right > GetTimelineLeftBound()) {
DrawZebraStripes(painter, QRectF(block_left, block_top, zebra_right - block_left, block_height));
}
break;
case LoopMode::kLoopModeLoop:
for (qreal i=zebra_right; i>block_left; i-=TimeToScene(clip->connected_viewer()->GetLength())) {
painter->drawLine(i, block_top, i, block_top + block_height);
}
break;
case LoopMode::kLoopModeClamp:
painter->drawLine(zebra_right, block_top, zebra_right, block_top + block_height);
break;
}
}
if (clip->length() + clip->media_in() > clip->connected_viewer()->GetLength()) {
qreal zebra_left = TimeToScene(clip->out() - (clip->media_in() + clip->length() - clip->connected_viewer()->GetLength()));
switch (clip->loop_mode()) {
case LoopMode::kLoopModeOff:
// Draw stripes for sections for clip > clip length
if (zebra_left < GetTimelineRightBound()) {
DrawZebraStripes(painter, QRectF(zebra_left, block_top, block_right - zebra_left, block_height));
}
break;
case LoopMode::kLoopModeLoop:
for (qreal i=zebra_left; i<block_right; i+=TimeToScene(clip->connected_viewer()->GetLength())) {
painter->drawLine(i, block_top, i, block_top + block_height);
}
break;
case LoopMode::kLoopModeClamp:
painter->drawLine(zebra_left, block_top, zebra_left, block_top + block_height);
break;
}
}
}
TimelineMarkerList *marker_list = clip->connected_viewer()->GetMarkers();
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().in() >= clip->media_in() && marker->time().out() <= clip->media_in() + clip->length()) {
QPoint marker_pt(TimeToScene(clip->in() - clip->media_in() + marker->time().in()), block_top + block_height);
painter->setClipRect(r);
QRect marker_rect = marker->Draw(painter, marker_pt, -1, GetScale(), false);
clip_marker_rects_.insert(marker, marker_rect);
painter->setClipping(false);
}
}
}
}
if (const FrameHashCache *cache = clip->connected_video_cache()) {
if (cache->HasValidatedRanges()) {
QRect cache_rect = r.adjusted(0, r.height() - PlaybackCache::GetCacheIndicatorHeight(), 0, 0).toRect();
cache->Draw(painter, clip->media_in(), GetScale(), cache_rect);
}
}
}
// For transitions, show lines representing a transition
if (TransitionBlock* transition = dynamic_cast<TransitionBlock*>(block)) {
QVector<QLineF> lines;
if (transition->connected_in_block()) {
lines.append(QLineF(r.bottomLeft(), r.topRight()));
}
if (transition->connected_out_block()) {
lines.append(QLineF(r.topLeft(), r.bottomRight()));
}
painter->setPen(shadow_color);
painter->drawLines(lines);
}
if (transition_overlay_out_ == block || transition_overlay_in_ == block) {
QRectF transition_overlay_rect = r;
qreal transition_overlay_width = TimeToScene(block->length()) * 0.5;
if (transition_overlay_out_ && transition_overlay_in_) {
// This is a dual transition, use the smallest width
Block *other_block = (transition_overlay_out_ == block) ? transition_overlay_in_ : transition_overlay_out_;
qreal other_width = TimeToScene(other_block->length()) * 0.5;
transition_overlay_width = qMin(transition_overlay_width, other_width);
}
if (transition_overlay_out_ == block) {
transition_overlay_rect.setLeft(transition_overlay_rect.right() - transition_overlay_width);
} else {
transition_overlay_rect.setRight(transition_overlay_rect.left() + transition_overlay_width);
}
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(0, 0, 0, 64));
painter->drawRect(transition_overlay_rect);
}
}
}
}
}
}
void TimelineView::DrawZebraStripes(QPainter *painter, const QRectF &r)
{
int zebra_interval = fontMetrics().height();
painter->setPen(QPen(QColor(0, 0, 0, 128), zebra_interval/4));
painter->setBrush(Qt::NoBrush);
QVector<QLineF> lines;
lines.reserve(qCeil(r.width() / zebra_interval));
qreal left = r.left() - r.height();
qreal right = r.right() + r.height();
for (qreal i=left; i<right; i+=zebra_interval) {
lines.append(QLineF(i, r.top(), i - r.height(), r.bottom()));
}
painter->setClipRect(r);
painter->drawLines(lines);
painter->setClipping(false);
}
int TimelineView::GetHeightOfAllTracks() const
{
if (connected_track_list_) {
if (alignment() & Qt::AlignTop) {
return GetTrackY(connected_track_list_->GetTrackCount());
} else {
return GetTrackY(connected_track_list_->GetTrackCount() - 1);
}
} else {
return 0;
}
}
qreal TimelineView::GetTimelineLeftBound() const
{
return horizontalScrollBar()->value();
}
qreal TimelineView::GetTimelineRightBound() const
{
return GetTimelineLeftBound() + viewport()->width();
}
void TimelineView::DrawThumbnail(QPainter *painter, const FrameHashCache *thumbs, const rational &time, int x, const QRect &preview_rect, QRect *thumb_rect) const
{
QString thumbnail = thumbs->GetValidCacheFilename(time);
if (!thumbnail.isEmpty()) {
QImage img;
if (img.load(thumbnail, "jpg")) {
double scale = double(preview_rect.height())/double(img.height());
*thumb_rect = QRect(x, preview_rect.top(), img.width() * scale, preview_rect.height());
painter->drawImage(*thumb_rect, img);
}
}
}
int TimelineView::GetTrackY(int track_index) const
{
if (!connected_track_list_ || !connected_track_list_->GetTrackCount()) {
return 0;
}
int y = 0;
if (alignment() & Qt::AlignBottom) {
track_index++;
}
for (int i=0;i<track_index;i++) {
y += GetTrackHeight(i);
// One px line between each track
y++;
}
if (alignment() & Qt::AlignBottom) {
y = -y + 1;
}
return y;
}
int TimelineView::GetTrackHeight(int track_index) const
{
if (!connected_track_list_ || connected_track_list_->GetTrackCount() == 0) {
// Handle null or empty track list
return Track::GetDefaultTrackHeightInPixels();
}
if (track_index >= connected_track_list_->GetTrackCount()) {
// Handle new track at the end of the list
return connected_track_list_->GetTrackAt(connected_track_list_->GetTrackCount()-1)->GetTrackHeightInPixels();
}
if (track_index < 0) {
// Handle new track at the beginning of the list
return connected_track_list_->GetTrackAt(0)->GetTrackHeightInPixels();
}
// Track definitely exists, return its actual height
return connected_track_list_->GetTrackAt(track_index)->GetTrackHeightInPixels();
}
QPoint TimelineView::GetScrollCoordinates() const
{
return QPoint(horizontalScrollBar()->value(), verticalScrollBar()->value());
}
void TimelineView::SetScrollCoordinates(const QPoint &pt)
{
horizontalScrollBar()->setValue(pt.x());
verticalScrollBar()->setValue(pt.y());
}
void TimelineView::ConnectTrackList(TrackList *list)
{
if (connected_track_list_) {
disconnect(connected_track_list_, &TrackList::TrackListChanged, this, &TimelineView::TrackListChanged);
disconnect(connected_track_list_, &TrackList::TrackHeightChanged, this, &TimelineView::TrackListChanged);
}
connected_track_list_ = list;
if (connected_track_list_) {
connect(connected_track_list_, &TrackList::TrackListChanged, this, &TimelineView::TrackListChanged);
connect(connected_track_list_, &TrackList::TrackHeightChanged, this, &TimelineView::TrackListChanged);
}
}
void TimelineView::SetBeamCursor(const TimelineCoordinate &coord)
{
if (!connected_track_list_) {
return;
}
bool update_required = coord.GetTrack().type() == connected_track_list_->type()
|| cursor_coord_.GetTrack().type() == connected_track_list_->type();
show_beam_cursor_ = true;
cursor_coord_ = coord;
if (update_required) {
viewport()->update();
}
}
void TimelineView::SetTransitionOverlay(ClipBlock *out, ClipBlock *in)
{
if (transition_overlay_out_ != out || transition_overlay_in_ != in) {
Track::Type type = Track::kNone;
if (out) {
type = out->track()->type();
} else if (in) {
type = in->track()->type();
}
if (type == this->connected_track_list_->type()) {
transition_overlay_out_ = out;
transition_overlay_in_ = in;
} else {
transition_overlay_out_ = nullptr;
transition_overlay_in_ = nullptr;
}
viewport()->update();
}
}
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;
int heights = 0;
if (alignment() & Qt::AlignBottom) {
y = -y;
}
do {
track++;
heights += GetTrackHeight(track);
} while (y > heights);
return track;
}
Block *TimelineView::GetItemAtScenePos(const rational &time, int track_index) const
{
if (connected_track_list_) {
Track* track = connected_track_list_->GetTrackAt(track_index);
if (track) {
foreach (Block* b, track->Blocks()) {
if (b->in() <= time && b->out() > time) {
return b;
}
}
}
}
return nullptr;
}
QVector<Block *> TimelineView::GetItemsAtSceneRect(const QRectF &rect) const
{
QVector<Block *> list;
if (connected_track_list_) {
rational start = this->SceneToTime(rect.left());
rational end = this->SceneToTime(rect.right());
for (int i = 0; i < connected_track_list_->GetTrackCount(); i++) {
Track *track = connected_track_list_->GetTrackAt(i);
int track_top = GetTrackY(i);
int track_bottom = track_top + GetTrackHeight(i);
if (track) {
if (!(track_bottom < rect.top() || track_top > rect.bottom())) {
Block *b = track->NearestBlockBeforeOrAt(start);
while (b && b->in() < end) {
list.append(b);
b = b->next();
}
}
}
}
}
return list;
}
void TimelineView::TrackListChanged()
{
UpdateSceneRect();
viewport()->update();
}
}
| 29,425
|
C++
|
.cpp
| 722
| 33.142659
| 182
| 0.630798
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,857
|
historywidget.cpp
|
olive-editor_olive/app/widget/history/historywidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 Olive Studios LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "historywidget.h"
#include "core.h"
namespace olive {
HistoryWidget::HistoryWidget(QWidget *parent) :
QTreeView(parent)
{
stack_ = Core::instance()->undo_stack();
this->setModel(stack_);
this->setRootIsDecorated(false);
connect(stack_, &UndoStack::indexChanged, this, &HistoryWidget::indexChanged);
connect(this->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &HistoryWidget::currentRowChanged);
}
void HistoryWidget::indexChanged(int i)
{
this->selectionModel()->select(this->model()->index(i-1, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void HistoryWidget::currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
size_t jump_to = (current.row() + 1);
stack_->jump(jump_to);
}
}
| 1,502
|
C++
|
.cpp
| 36
| 39.194444
| 128
| 0.768066
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,858
|
nodewidget.cpp
|
olive-editor_olive/app/widget/nodeview/nodewidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodewidget.h"
#include <QVBoxLayout>
namespace olive {
NodeWidget::NodeWidget(QWidget *parent) :
QWidget(parent)
{
QVBoxLayout *outer_layout = new QVBoxLayout(this);
outer_layout->setContentsMargins(0, 0, 0, 0);
toolbar_ = new NodeViewToolBar();
outer_layout->addWidget(toolbar_);
// Create NodeView widget
node_view_ = new NodeView(this);
outer_layout->addWidget(node_view_);
// Connect toolbar to NodeView
connect(toolbar_, &NodeViewToolBar::MiniMapEnabledToggled, node_view_, &NodeView::SetMiniMapEnabled);
connect(toolbar_, &NodeViewToolBar::AddNodeClicked, node_view_, &NodeView::ShowAddMenu);
// Set defaults
toolbar_->SetMiniMapEnabled(true);
node_view_->SetMiniMapEnabled(true);
setSizePolicy(node_view_->sizePolicy());
}
}
| 1,493
|
C++
|
.cpp
| 36
| 38.555556
| 103
| 0.764216
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,859
|
nodeviewcontext.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewcontext.cpp
|
#include "nodeviewcontext.h"
#include <QBrush>
#include <QCoreApplication>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPen>
#include <QStyleOptionGraphicsItem>
#include "core.h"
#include "node/block/block.h"
#include "node/group/group.h"
#include "node/output/track/track.h"
#include "node/project.h"
#include "node/project/sequence/sequence.h"
#include "nodeviewitem.h"
#include "ui/colorcoding.h"
namespace olive {
#define super QGraphicsRectItem
NodeViewContext::NodeViewContext(Node *context, QGraphicsItem *item) :
super(item),
context_(context)
{
Block *block = dynamic_cast<Block*>(context_);
if (block && block->track() && block->track()->sequence()) {
rational timebase = block->track()->sequence()->GetVideoParams().frame_rate_as_time_base();
lbl_ = QCoreApplication::translate("NodeViewContext",
"%1 [%2] :: %3 - %4").arg(block->GetLabelAndName(),
Track::Reference::TypeToTranslatedString(block->track()->type()),
QString::fromStdString(Timecode::time_to_timecode(block->in(), timebase, Core::instance()->GetTimecodeDisplay())),
QString::fromStdString(Timecode::time_to_timecode(block->out(), timebase, Core::instance()->GetTimecodeDisplay())));
} else {
lbl_ = context_->GetLabelAndName();
}
const Node::PositionMap &map = context_->GetContextPositions();
for (auto it=map.cbegin(); it!=map.cend(); it++) {
AddChild(it.key());
}
connect(context_, &Node::NodeAddedToContext, this, &NodeViewContext::AddChild, Qt::DirectConnection);
connect(context_, &Node::NodePositionInContextChanged, this, &NodeViewContext::SetChildPosition, Qt::DirectConnection);
connect(context_, &Node::NodeRemovedFromContext, this, &NodeViewContext::RemoveChild, Qt::DirectConnection);
}
NodeViewContext::~NodeViewContext()
{
// Delete edges before items, because the edge constructor references the items
qDeleteAll(edges_);
edges_.clear();
}
void NodeViewContext::AddChild(Node *node)
{
if (!context_) {
return;
}
NodeViewItem *item = new NodeViewItem(node, context_, this);
item->SetFlowDirection(flow_dir_);
AddNodeInternal(node, item);
if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
for (auto it=group->GetContextPositions().cbegin(); it!=group->GetContextPositions().cend(); it++) {
// Use this item as the representative for all of these nodes too
AddNodeInternal(it.key(), item);
}
connect(group, &NodeGroup::NodeAddedToContext, this, &NodeViewContext::GroupAddedNode);
connect(group, &NodeGroup::NodeRemovedFromContext, this, &NodeViewContext::GroupRemovedNode);
}
UpdateRect();
}
void NodeViewContext::SetChildPosition(Node *node, const QPointF &pos)
{
item_map_.value(node)->SetNodePosition(pos);
}
void NodeViewContext::RemoveChild(Node *node)
{
disconnect(node, &Node::InputConnected, this, &NodeViewContext::ChildInputConnected);
disconnect(node, &Node::InputDisconnected, this, &NodeViewContext::ChildInputDisconnected);
if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
disconnect(group, &NodeGroup::NodeAddedToContext, this, &NodeViewContext::GroupAddedNode);
disconnect(group, &NodeGroup::NodeRemovedFromContext, this, &NodeViewContext::GroupRemovedNode);
}
NodeViewItem *item = item_map_.take(node);
// Remove from scene before emitting signal so that any drag functions that might be happening
// now can be handled before the item is destroyed
scene()->removeItem(item);
emit ItemAboutToBeDeleted(item);
// Delete edges first because the edge destructor will try to reference item (maybe that should
// be changed...)
QVector<NodeViewEdge*> edges_to_remove = item->GetAllEdgesRecursively();
foreach (NodeViewEdge *edge, edges_to_remove) {
if (node == item->GetNode() || edge->output() == node || edge->input().node() == node) {
ChildInputDisconnected(edge->output(), edge->input());
}
}
// Check if this item is specifically for this node and the node is a group. If so, remove it for
// all other entries in the map.
if (item->GetNode() == node) {
if (dynamic_cast<NodeGroup*>(item->GetNode())) {
for (auto it=item_map_.begin(); it!=item_map_.end(); ) {
if (it.value() == item) {
it = item_map_.erase(it);
} else {
it++;
}
}
}
delete item;
}
UpdateRect();
}
void NodeViewContext::ChildInputConnected(Node *output, const NodeInput &input)
{
// Add edge
if (!input.IsHidden()) {
if (NodeViewItem* output_item = item_map_.value(output)) {
AddEdgeInternal(output, input, output_item, item_map_.value(input.node())->GetItemForInput(input));
}
}
}
bool NodeViewContext::ChildInputDisconnected(Node *output, const NodeInput &input)
{
// Remove edge
for (int i=0; i<edges_.size(); i++) {
NodeViewEdge *e = edges_.at(i);
if (e->output() == output && e->input() == input) {
delete e;
edges_.removeAt(i);
return true;
}
}
return false;
}
qreal GetTextOffset(const QFontMetricsF &fm)
{
return fm.height()/2;
}
void NodeViewContext::UpdateRect()
{
QFont f;
QFontMetricsF fm(f);
qreal lbl_offset = GetTextOffset(fm);
QRectF cbr = childrenBoundingRect();
QRectF rect = cbr;
int pad = NodeViewItem::DefaultItemHeight();
rect.adjust(-pad, - lbl_offset*2 - fm.height() - pad, pad, pad);
setRect(rect);
last_titlebar_height_ = rect.y() + (cbr.y() - rect.y()) - pad;
}
void NodeViewContext::SetFlowDirection(NodeViewCommon::FlowDirection dir)
{
flow_dir_ = dir;
foreach (NodeViewItem *item, item_map_) {
item->SetFlowDirection(dir);
}
}
void NodeViewContext::SetCurvedEdges(bool e)
{
curved_edges_ = e;
foreach (NodeViewEdge *edge, edges_) {
edge->SetCurved(e);
}
}
int NodeViewContext::DeleteSelected(NodeViewDeleteCommand *command)
{
int count = 0;
// Delete any selected edges
foreach (NodeViewEdge *edge, edges_) {
if (edge->isSelected()) {
command->AddEdge(edge->output(), edge->input());
}
}
// Delete any selected nodes
foreach (NodeViewItem *node, item_map_) {
if (node->isSelected()) {
command->AddNode(node->GetNode(), context_);
count++;
}
}
return count;
}
void NodeViewContext::Select(const QVector<Node *> &nodes)
{
foreach (Node *n, nodes) {
if (NodeViewItem *item = item_map_.value(n)) {
item->setSelected(true);
}
}
}
QVector<NodeViewItem *> NodeViewContext::GetSelectedItems() const
{
QVector<NodeViewItem *> items;
for (auto it=item_map_.cbegin(); it!=item_map_.cend(); it++) {
if (it.value()->isSelected()) {
if (!items.contains(it.value())) {
items.append(it.value());
}
}
}
return items;
}
QPointF NodeViewContext::MapScenePosToNodePosInContext(const QPointF &pos) const
{
for (auto it=item_map_.cbegin(); it!=item_map_.cend(); it++) {
QPointF pos_inside_parent = it.value()->mapToParent(it.value()->mapFromScene(pos));
return NodeViewItem::ScreenToNodePoint(pos_inside_parent, flow_dir_);
}
return QPointF(0, 0);
}
void NodeViewContext::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
// Set pen and brush
Color color = context_->color();
QColor c = QtUtils::toQColor(color);
QPen pen(c, 2);
if (option->state & QStyle::State_Selected) {
pen.setStyle(Qt::DotLine);
}
painter->setPen(pen);
QColor bg = c;
bg.setAlpha(128);
painter->setBrush(bg);
// Draw semi-transparent rect for whole item
int rounded = painter->fontMetrics().height();
painter->drawRoundedRect(rect(), rounded, rounded);
// Draw solid background for titlebar
QRectF titlebar_rect = rect();
titlebar_rect.setHeight(last_titlebar_height_ - rect().top());
painter->setClipRect(titlebar_rect);
painter->setBrush(c);
painter->drawRoundedRect(rect(), rounded, rounded);
painter->setClipping(false);
// Draw titlebar text
painter->setPen(ColorCoding::GetUISelectorColor(color));
int offset = GetTextOffset(painter->fontMetrics());
QRectF text_rect = rect();
text_rect.adjust(offset, offset, -offset, -offset);
painter->drawText(text_rect, lbl_);
}
QVariant NodeViewContext::itemChange(GraphicsItemChange change, const QVariant &value)
{
return super::itemChange(change, value);
}
void NodeViewContext::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
bool clicked_inside_titlebar = (event->pos().y() < last_titlebar_height_);
setFlag(ItemIsMovable, clicked_inside_titlebar);
setFlag(ItemIsSelectable, clicked_inside_titlebar);
super::mousePressEvent(event);
}
void NodeViewContext::AddNodeInternal(Node *node, NodeViewItem *item)
{
connect(node, &Node::InputConnected, this, &NodeViewContext::ChildInputConnected);
connect(node, &Node::InputDisconnected, this, &NodeViewContext::ChildInputDisconnected);
item_map_.insert(node, item);
if (node == context_) {
item->SetLabelAsOutput(true);
}
for (auto it=node->output_connections().cbegin(); it!=node->output_connections().cend(); it++) {
if (!it->second.IsHidden()) {
if (NodeViewItem *other_item = item_map_.value(it->second.node())) {
AddEdgeInternal(node, it->second, item, other_item->GetItemForInput(it->second));
}
}
}
for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) {
if (!it->first.IsHidden()) {
if (NodeViewItem *other_item = item_map_.value(it->second)) {
AddEdgeInternal(it->second, it->first, other_item, item->GetItemForInput(it->first));
}
}
}
}
void NodeViewContext::AddEdgeInternal(Node *output, const NodeInput& input, NodeViewItem *from, NodeViewItem *to)
{
if (from == to) {
return;
}
NodeViewEdge* edge_ui = new NodeViewEdge(output, input, from, to, this);
edge_ui->Adjust();
edge_ui->SetCurved(curved_edges_);
edges_.append(edge_ui);
}
void NodeViewContext::GroupAddedNode(Node *node)
{
NodeGroup *group = static_cast<NodeGroup*>(sender());
AddNodeInternal(node, item_map_.value(group));
}
void NodeViewContext::GroupRemovedNode(Node *node)
{
NodeGroup *group = static_cast<NodeGroup*>(sender());
if (item_map_.value(node) == item_map_.value(group)) {
item_map_.remove(node);
}
}
}
| 10,470
|
C++
|
.cpp
| 290
| 31.941379
| 181
| 0.691623
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,860
|
nodeview.cpp
|
olive-editor_olive/app/widget/nodeview/nodeview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeview.h"
#include <QInputDialog>
#include <QMessageBox>
#include <QMimeData>
#include <QMouseEvent>
#include <QPushButton>
#include <QScrollBar>
#include <QToolTip>
#include "node/audio/volume/volume.h"
#include "node/distort/transform/transformdistortnode.h"
#include "node/factory.h"
#include "node/group/group.h"
#include "node/nodeundo.h"
#include "node/project/serializer/serializer.h"
#include "node/traverser.h"
#include "ui/icons/icons.h"
#include "widget/menu/menushared.h"
#include "widget/timebased/timebasedview.h"
#define super HandMovableView
namespace olive {
const double NodeView::kMinimumScale = 0.1;
const int NodeView::kMaximumContexts = 10;
NodeView::NodeView(QWidget *parent) :
HandMovableView(parent),
drop_edge_(nullptr),
create_edge_(nullptr),
create_edge_output_item_(nullptr),
create_edge_input_item_(nullptr),
overlay_view_(nullptr),
scale_(1.0),
dont_emit_selection_signals_(false)
{
setScene(&scene_);
SetDefaultDragMode(RubberBandDrag);
setContextMenuPolicy(Qt::CustomContextMenu);
setMouseTracking(true);
setRenderHint(QPainter::Antialiasing);
setViewportUpdateMode(FullViewportUpdate);
connect(this, &NodeView::customContextMenuRequested, this, &NodeView::ShowContextMenu);
ConnectSelectionChangedSignal();
SetFlowDirection(NodeViewCommon::kLeftToRight);
UpdateSceneBoundingRect();
connect(&scene_, &QGraphicsScene::changed, this, &NodeView::UpdateSceneBoundingRect);
minimap_ = new NodeViewMiniMap(&scene_, this);
minimap_->show();
connect(minimap_, &NodeViewMiniMap::Resized, this, &NodeView::RepositionMiniMap);
connect(minimap_, &NodeViewMiniMap::MoveToScenePoint, this, &NodeView::MoveToScenePoint);
connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, &NodeView::UpdateViewportOnMiniMap);
connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &NodeView::UpdateViewportOnMiniMap);
viewport()->installEventFilter(this);
}
NodeView::~NodeView()
{
// Unset the current graph
ClearGraph();
}
void NodeView::SetContexts(const QVector<Node*> &nodes)
{
if (overlay_view_) {
CloseOverlay();
}
// Remove contexts that are no longer in the list
foreach (Node *n, contexts_) {
if (!nodes.contains(n)) {
RemoveContext(n);
}
}
// Add contexts that are now in the list
foreach (Node *n, nodes) {
if (scene_.context_map().size() >= kMaximumContexts) {
break;
}
if (!contexts_.contains(n)) {
AddContext(n);
}
}
contexts_ = nodes;
CenterOnItemsBoundingRect();
}
void NodeView::CloseContextsBelongingToProject(Project *project)
{
QVector<Node*> new_contexts = contexts_;
for (auto it = new_contexts.begin(); it != new_contexts.end(); ) {
if ((*it)->project() == project) {
it = new_contexts.erase(it);
} else {
it++;
}
}
SetContexts(new_contexts);
}
void NodeView::ClearGraph()
{
SetContexts(QVector<Node*>());
}
void NodeView::DeleteSelected()
{
NodeViewDeleteCommand* command = new NodeViewDeleteCommand();
int count = 0;
foreach (NodeViewContext *ctx, scene_.context_map()) {
count += ctx->DeleteSelected(command);
}
Core::instance()->undo_stack()->push(command, tr("Deleted %1 Node(s)").arg(count));
}
void NodeView::SelectAll()
{
// Optimization: rather than respond to every single item being selected, ignore the signal and
// then handle them all at the end.
DisconnectSelectionChangedSignal();
scene_.SelectAll();
ConnectSelectionChangedSignal();
UpdateSelectionCache();
}
void NodeView::DeselectAll()
{
if (selected_nodes_.isEmpty()) {
return;
}
// Optimization: rather than respond to every single item being selected, ignore the signal and
// then handle them all at the end.
DisconnectSelectionChangedSignal();
scene_.DeselectAll();
ConnectSelectionChangedSignal();
// Just emit all the nodes that are currently selected as no longer selected
emit NodesDeselected(selected_nodes_);
selected_nodes_.clear();
emit NodeSelectionChanged(selected_nodes_);
emit NodeSelectionChangedWithContexts(QVector<Node::ContextPair>());
}
void NodeView::Select(const QVector<Node::ContextPair> &nodes, bool center_view_on_item)
{
// Optimization: rather than respond to every single item being selected, ignore the signal and
// then handle them all at the end.
DisconnectSelectionChangedSignal();
QVector<Node*> deselections = selected_nodes_;
QVector<Node*> new_selections;
scene_.DeselectAll();
foreach (const Node::ContextPair &p, nodes) {
NodeViewContext *ctx = scene_.context_map().value(p.context);
if (ctx) {
NodeViewItem *item = ctx->GetItemFromMap(p.node);
if (item) {
item->setSelected(true);
}
}
}
// Center on something
if (center_view_on_item && !nodes.isEmpty()) {
QMetaObject::invokeMethod(this, "CenterOnNode", Qt::QueuedConnection, OLIVE_NS_ARG(Node*, nodes.first().node));
}
ConnectSelectionChangedSignal();
// Don't signal when this function was likely triggered from another widget's signal anyway
dont_emit_selection_signals_ = true;
UpdateSelectionCache();
dont_emit_selection_signals_ = false;
}
void NodeView::CopySelected(bool cut)
{
if (selected_nodes_.isEmpty()) {
return;
}
QString copy_str;
QXmlStreamWriter writer(©_str);
ProjectSerializer::SaveData sdata(ProjectSerializer::kOnlyNodes);
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);
Core::CopyStringToClipboard(copy_str);
if (cut) {
DeleteSelected();
}
}
void NodeView::Paste()
{
if (contexts_.isEmpty()) {
return;
}
ProjectSerializer::Result res = ProjectSerializer::Paste(ProjectSerializer::kOnlyNodes);
if (res.GetLoadData().nodes.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();
map.insert(it.key(), pos);
}
PostPaste(res.GetLoadData().nodes, map);
}
void NodeView::Duplicate()
{
if (!selected_nodes_.isEmpty()) {
QVector<Node*> selected = selected_nodes_;
QVector<Node*> new_nodes;
Node::PositionMap map;
new_nodes.resize(selected.size());
// Create copies of each selected node, checking for groups and adding children if necessary
for (int i=0; i<selected.size(); i++) {
new_nodes[i] = selected.at(i)->copy();
if (NodeGroup *g = dynamic_cast<NodeGroup*>(selected.at(i))) {
for (auto it=g->GetContextPositions().cbegin(); it!=g->GetContextPositions().cend(); it++) {
if (!selected.contains(it.key())) {
// This should automatically recurse if this is a group inside a group
selected.append(it.key());
}
}
new_nodes.resize(selected.size());
}
}
// Get positions in contexts, add input passthroughs, and copy input values/keyframes
for (int i=0; i<new_nodes.size(); i++) {
Node *og = selected.at(i);
Node *copy = new_nodes.at(i);
Node::Position pos;
if (GetAssumedPositionForSelectedNode(og, &pos)) {
map.insert(copy, pos);
}
for (auto it=og->GetContextPositions().cbegin(); it!=og->GetContextPositions().cend(); it++) {
Node *child_og = it.key();
int child_index = selected.indexOf(child_og);
if (child_index != -1) {
Node *child_copy = new_nodes.at(child_index);
copy->SetNodePositionInContext(child_copy, it.value());
}
}
if (NodeGroup *src_group = dynamic_cast<NodeGroup*>(og)) {
NodeGroup *dst_group = static_cast<NodeGroup*>(copy);
for (auto it=src_group->GetInputPassthroughs().cbegin(); it!=src_group->GetInputPassthroughs().cend(); it++) {
NodeInput input = it->second;
input.set_node(new_nodes.at(selected.indexOf(input.node())));
dst_group->AddInputPassthrough(input, it->first);
}
dst_group->SetOutputPassthrough(new_nodes.at(selected.indexOf(src_group->GetOutputPassthrough())));
}
Node::CopyInputs(selected.at(i), new_nodes.at(i), false);
}
// Copy connections
Node::CopyDependencyGraph(selected, new_nodes, nullptr);
// Set root level context positions and attach to
PostPaste(new_nodes, map);
}
}
void NodeView::SetColorLabel(int index)
{
MultiUndoCommand *command = new MultiUndoCommand();
for (Node* node : qAsConst(selected_nodes_)) {
command->add_child(new NodeOverrideColorCommand(node, index));
}
Core::instance()->undo_stack()->push(command, tr("Set Color of %1 Node(s)").arg(selected_nodes_.size()));
}
void NodeView::ZoomIn()
{
ZoomFromKeyboard(1.25);
}
void NodeView::ZoomOut()
{
ZoomFromKeyboard(0.8);
}
void NodeView::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Up:
case Qt::Key_Down:
{
MultiUndoCommand *pos_command = new MultiUndoCommand();
for (Node *n : qAsConst(selected_nodes_)) {
for (Node *context : qAsConst(contexts_)) {
if (context->ContextContainsNode(n)) {
Node::Position old_pos = context->GetNodePositionInContext(n);
// Determine one pixel in scene units
double movement_amt = 1.0 / scale_;
// Translate to 2D movement
QPointF node_movement;
switch (event->key()) {
case Qt::Key_Left:
node_movement.setX(-movement_amt);
break;
case Qt::Key_Right:
node_movement.setX(movement_amt);
break;
case Qt::Key_Up:
node_movement.setY(-movement_amt);
break;
case Qt::Key_Down:
node_movement.setY(movement_amt);
break;
}
// Translate from screen units into node units
node_movement = NodeViewItem::ScreenToNodePoint(node_movement, scene_.GetFlowDirection());
// Move command
pos_command->add_child(new NodeSetPositionCommand(n, context, old_pos + node_movement));
}
}
}
Core::instance()->undo_stack()->push(pos_command, tr("Moved %1 Node(s)").arg(selected_nodes_.size()));
break;
}
case Qt::Key_Escape:
if (!attached_items_.isEmpty()) {
DetachItemsFromCursor();
break;
}
emit EscPressed();
/* fall through */
default:
super::keyPressEvent(event);
break;
}
}
void NodeView::mousePressEvent(QMouseEvent *event)
{
// Handle mouse press event
if (HandPress(event)) return;
// Get the item that the user clicked on, if any
QGraphicsItem* item = itemAt(event->pos());
if (event->button() == Qt::LeftButton) {
// Sane defaults
create_edge_already_exists_ = false;
create_edge_from_output_ = true;
create_edge_input_.Reset();
if (event->modifiers() & Qt::ControlModifier) {
NodeViewItem *mouse_item = dynamic_cast<NodeViewItem*>(item);
if (mouse_item) {
if (mouse_item->IsOutputItem()) {
create_edge_output_item_ = mouse_item;
} else {
create_edge_input_item_ = mouse_item;
create_edge_input_ = mouse_item->GetInput();
create_edge_from_output_ = false;
}
// Highlight start item for better user experience
mouse_item->SetHighlighted(true);
}
}
if (!create_edge_output_item_ && !create_edge_input_item_) {
// Determine if user clicked on a connector
if (NodeViewItemConnector *connector = dynamic_cast<NodeViewItemConnector *>(item)) {
NodeViewItem *attached = static_cast<NodeViewItem*>(connector->parentItem());
if (connector->IsOutput()) {
create_edge_output_item_ = attached;
} else {
create_edge_input_item_ = attached;
if (!create_edge_input_item_->edges().isEmpty()) {
// Drag existing edge instead
create_edge_ = create_edge_input_item_->edges().first();
create_edge_input_item_ = nullptr;
create_edge_output_item_ = create_edge_->from_item();
create_edge_already_exists_ = true;
} else {
create_edge_from_output_ = false;
create_edge_input_ = create_edge_input_item_->GetInput();
}
}
}
}
if ((create_edge_output_item_ || create_edge_input_item_) && !create_edge_already_exists_) {
// Create a new edge from this output
create_edge_ = new NodeViewEdge();
create_edge_->SetCurved(scene_.GetEdgesAreCurved());
// Add edge to scene
scene_.addItem(create_edge_);
// Position edge to mouse cursor
PositionNewEdge(event->pos());
return;
}
}
// Handle selections with the right mouse button
if (event->button() == Qt::RightButton) {
if (!item || !item->isSelected()) {
// Qt doesn't do this by default for some reason
if (!(event->modifiers() & Qt::ShiftModifier)) {
scene_.clearSelection();
}
// If there's an item here, select it
if (item) {
item->setSelected(true);
}
}
}
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();
foreach (NodeViewItem *i, selected_items) {
// Ignore items attached to the cursor
if (!IsItemAttachedToCursor(i)) {
dragging_items_.insert(i, i->GetNodePosition());
}
}
}
void NodeView::mouseMoveEvent(QMouseEvent *event)
{
if (HandMove(event)) return;
if (create_edge_) {
PositionNewEdge(event->pos());
return;
}
if (attached_items_.isEmpty()) {
super::mouseMoveEvent(event);
}
// See if there are any items attached
if (!attached_items_.isEmpty()) {
ProcessMovingAttachedNodes(event->pos());
}
}
void NodeView::mouseReleaseEvent(QMouseEvent *event)
{
if (HandRelease(event)) return;
if (create_edge_) {
EndEdgeDrag();
}
MultiUndoCommand* command = new MultiUndoCommand();
Node *select_context = nullptr;
QVector<Node*> select_nodes;
bool had_attached_items = !attached_items_.isEmpty();
if (!attached_items_.isEmpty()) {
select_context = GetContextAtMousePos(event->pos());
if (select_context) {
select_nodes = ProcessDroppingAttachedNodes(command, select_context, event->pos());
} else {
QToolTip::showText(QCursor::pos(), tr("Nodes must be placed inside a context."));
}
}
for (auto it=dragging_items_.cbegin(); it!=dragging_items_.cend(); it++) {
NodeViewItem *i = it.key();
QPointF current_pos = i->GetNodePosition();
if (it.value() != current_pos) {
command->add_child(new NodeSetPositionCommand(i->GetNode(), i->GetContext(), current_pos));
}
}
Core::instance()->undo_stack()->push(command, tr("Moved %1 Node(s)").arg(dragging_items_.size()));
dragging_items_.clear();
if (!had_attached_items) {
super::mouseReleaseEvent(event);
}
if (select_context) {
DeselectAll();
scene_.context_map().value(select_context)->Select(select_nodes);
}
}
void NodeView::mouseDoubleClickEvent(QMouseEvent *event)
{
super::mouseDoubleClickEvent(event);
if (!(event->modifiers() & Qt::ControlModifier)) {
NodeViewItem *item_at_cursor = dynamic_cast<NodeViewItem*>(itemAt(event->pos()));
if (item_at_cursor) {
item_at_cursor->ToggleExpanded();
}
}
}
void NodeView::dragEnterEvent(QDragEnterEvent *event)
{
if (contexts_.empty()) {
event->ignore();
return;
}
QStringList mime_fmts = event->mimeData()->formats();
if (mime_fmts.contains(Project::kItemMimeType)) {
QByteArray model_data = event->mimeData()->data(Project::kItemMimeType);
QDataStream stream(&model_data, QIODevice::ReadOnly);
// Variables to deserialize into
quintptr item_ptr;
QVector<Track::Reference> enabled_streams;
QVector<AttachedItem> new_attached;
int y = 0;
while (!stream.atEnd()) {
stream >> enabled_streams >> item_ptr;
// Get Item object
Node* item = reinterpret_cast<Node*>(item_ptr);
if (ViewerOutput* f = dynamic_cast<ViewerOutput*>(item)) {
NodeViewItem *new_item;
new_item = new NodeViewItem(f, nullptr);
new_item->SetFlowDirection(scene_.GetFlowDirection());
new_item->SetNodePosition(QPointF(0, y));
y++;
scene_.addItem(new_item);
new_attached.append({new_item, f, new_item->pos()});
}
}
if (new_attached.empty()) {
event->ignore();
} else {
SetAttachedItems(new_attached);
event->accept();
}
}
}
void NodeView::dragMoveEvent(QDragMoveEvent *event)
{
if (attached_items_.empty()) {
event->ignore();
} else {
ProcessMovingAttachedNodes(event->pos());
if (GetContextAtMousePos(event->pos())) {
event->accept();
} else {
event->ignore();
}
}
}
void NodeView::dropEvent(QDropEvent *event)
{
if (Node *drop_ctx = GetContextAtMousePos(event->pos())) {
MultiUndoCommand *command = new MultiUndoCommand();
QVector<Node*> select_nodes = ProcessDroppingAttachedNodes(command, drop_ctx, event->pos());
Core::instance()->undo_stack()->push(command, tr("Dropped %1 Node(s)").arg(select_nodes.size()));
DeselectAll();
scene_.context_map().value(drop_ctx)->Select(select_nodes);
event->accept();
} else {
DetachItemsFromCursor(false);
event->ignore();
}
}
void NodeView::dragLeaveEvent(QDragLeaveEvent *event)
{
if (attached_items_.empty()) {
event->ignore();
} else {
DetachItemsFromCursor(false);
event->accept();
}
}
void NodeView::resizeEvent(QResizeEvent *event)
{
super::resizeEvent(event);
RepositionMiniMap();
if (overlay_view_) {
ResizeOverlay();
}
}
void NodeView::UpdateSelectionCache()
{
QVector<NodeViewItem*> current_selection = scene_.GetSelectedItems();
QVector<Node*> selected;
QVector<Node*> deselected;
QVector<Node::ContextPair> sel_with_ctx(current_selection.size());
// Determine which nodes are newly selected
for (int j=0; j<current_selection.size(); j++) {
NodeViewItem *i = current_selection.at(j);
Node *n = i->GetNode();
if (!selected_nodes_.contains(n)) {
selected.append(n);
selected_nodes_.append(n);
}
sel_with_ctx[j] = {n, i->GetContext()};
}
// Determine which nodes are newly deselected
if (current_selection.isEmpty()) {
// All nodes that were selected have been deselected, so we'll just set them all to `deselected`
deselected = selected_nodes_;
selected_nodes_.clear();
} else {
foreach (Node* n, selected_nodes_) {
bool still_selected = false;
foreach (NodeViewItem *i, current_selection) {
if (i->GetNode() == n) {
still_selected = true;
break;
}
}
if (!still_selected) {
deselected.append(n);
selected_nodes_.removeOne(n);
}
}
}
if (!deselected.isEmpty()) {
emit NodesDeselected(deselected);
}
if (!selected.isEmpty()) {
emit NodesSelected(selected);
}
if (!dont_emit_selection_signals_) {
emit NodeSelectionChanged(selected_nodes_);
emit NodeSelectionChangedWithContexts(sel_with_ctx);
}
}
void NodeView::ShowContextMenu(const QPoint &pos)
{
if (contexts_.isEmpty()) {
return;
}
Menu m;
MenuShared::instance()->AddItemsForEditMenu(&m, false);
m.addSeparator();
QVector<NodeViewItem*> selected = scene_.GetSelectedItems();
if (itemAt(pos) && !selected.isEmpty()) {
// Grouping
if (selected.size() == 1 && dynamic_cast<NodeGroup*>(selected.first()->GetNode())) {
QAction *ungroup_action = m.addAction(tr("Ungroup"));
connect(ungroup_action, &QAction::triggered, this, &NodeView::UngroupNodes);
} else {
QAction *group_action = m.addAction(tr("Group"));
connect(group_action, &QAction::triggered, this, &NodeView::GroupNodes);
}
// Color menu
MenuShared::instance()->AddColorCodingMenu(&m);
// Show in Viewer option for nodes based on Viewer
if (ViewerOutput* viewer = dynamic_cast<ViewerOutput*>(selected.first()->GetNode())) {
Q_UNUSED(viewer)
m.addSeparator();
QAction* open_in_viewer_action = m.addAction(tr("Open in Viewer"));
connect(open_in_viewer_action, &QAction::triggered, this, &NodeView::OpenSelectedNodeInViewer);
}
m.addSeparator();
// Properties
QAction *properties_action = m.addAction(tr("P&roperties"));
connect(properties_action, &QAction::triggered, this, &NodeView::ShowNodeProperties);
} else {
QAction* curved_action = m.addAction(tr("Smooth Edges"));
curved_action->setCheckable(true);
curved_action->setChecked(scene_.GetEdgesAreCurved());
connect(curved_action, &QAction::triggered, &scene_, &NodeViewScene::SetEdgesAreCurved);
m.addSeparator();
Menu* direction_menu = new Menu(tr("Direction"), &m);
m.addMenu(direction_menu);
direction_menu->AddActionWithData(tr("Top to Bottom"),
NodeViewCommon::kTopToBottom,
scene_.GetFlowDirection());
direction_menu->AddActionWithData(tr("Bottom to Top"),
NodeViewCommon::kBottomToTop,
scene_.GetFlowDirection());
direction_menu->AddActionWithData(tr("Left to Right"),
NodeViewCommon::kLeftToRight,
scene_.GetFlowDirection());
direction_menu->AddActionWithData(tr("Right to Left"),
NodeViewCommon::kRightToLeft,
scene_.GetFlowDirection());
connect(direction_menu, &Menu::triggered, this, &NodeView::ContextMenuSetDirection);
m.addSeparator();
Menu* add_menu = CreateAddMenu(&m);
m.addMenu(add_menu);
}
m.exec(mapToGlobal(pos));
}
void NodeView::CreateNodeSlot(QAction *action)
{
Node* new_node = NodeFactory::CreateFromMenuAction(action);
if (new_node) {
NodeViewItem *new_item = new NodeViewItem(new_node, nullptr);
new_item->SetFlowDirection(scene_.GetFlowDirection());
scene_.addItem(new_item);
QVector<AttachedItem> new_attached;
new_attached.append({new_item, new_node, QPointF(0, 0)});
if (NodeGroup *new_group = dynamic_cast<NodeGroup*>(new_node)) {
for (auto it=new_group->GetContextPositions().cbegin(); it!=new_group->GetContextPositions().cend(); it++) {
new_attached.append({nullptr, it.key(), QPointF(0, 0)});
}
}
SetAttachedItems(new_attached);
}
}
void NodeView::ContextMenuSetDirection(QAction *action)
{
SetFlowDirection(static_cast<NodeViewCommon::FlowDirection>(action->data().toInt()));
}
void NodeView::OpenSelectedNodeInViewer()
{
// Find first viewer in list of selected nodes and open it
foreach (Node *n, selected_nodes_) {
if (ViewerOutput* viewer = dynamic_cast<ViewerOutput*>(n)) {
Core::instance()->OpenNodeInViewer(viewer);
break;
}
}
}
void NodeView::UpdateSceneBoundingRect()
{
// Get current items bounding rect
QRectF r = scene_.itemsBoundingRect();
// Adjust so that it fills the view
r.adjust(-width(), -height(), width(), height());
// Set it
scene_.setSceneRect(r);
}
void NodeView::CenterOnItemsBoundingRect()
{
centerOn(scene_.itemsBoundingRect().center());
}
void NodeView::CenterOnNode(Node *n)
{
foreach (NodeViewContext *ctx, scene_.context_map()) {
if (NodeViewItem* item = ctx->GetItemFromMap(n)) {
centerOn(item);
break;
}
}
}
void NodeView::RepositionMiniMap()
{
if (minimap_->isVisible()) {
int margin = fontMetrics().height();
int w = width() - minimap_->width() - margin;
int h = height() - minimap_->height() - margin;
if (verticalScrollBar()->isVisible()) {
w -= verticalScrollBar()->width();
}
if (horizontalScrollBar()->isVisible()) {
h -= horizontalScrollBar()->height();
}
minimap_->move(w, h);
UpdateViewportOnMiniMap();
}
}
void NodeView::UpdateViewportOnMiniMap()
{
if (minimap_->isVisible()) {
minimap_->SetViewportRect(mapToScene(viewport()->rect()));
}
}
void NodeView::MoveToScenePoint(const QPointF &pos)
{
centerOn(pos);
}
void NodeView::NodeRemovedFromGraph()
{
Node *context = static_cast<Node*>(sender());
RemoveContext(context);
contexts_.removeOne(context);
}
void NodeView::DetachItemsFromCursor(bool delete_nodes_too)
{
foreach (const AttachedItem &ai, attached_items_) {
delete ai.item;
if (delete_nodes_too) {
qDebug() << "deleting" << ai.node;
delete ai.node;
}
}
attached_items_.clear();
}
void NodeView::SetFlowDirection(NodeViewCommon::FlowDirection dir)
{
scene_.SetFlowDirection(dir);
}
void NodeView::MoveAttachedNodesToCursor(const QPoint& p)
{
QPointF item_pos = mapToScene(p);
for (const AttachedItem& i : qAsConst(attached_items_)) {
if (i.item) {
i.item->setPos(item_pos + i.original_pos);
}
}
}
void NodeView::ProcessMovingAttachedNodes(const QPoint &pos)
{
// Move those items to the cursor
MoveAttachedNodesToCursor(pos);
// See if the user clicked on an edge (only when dropping single nodes)
if (attached_items_.size() == 1) {
Node* attached_node = attached_items_.first().item->GetNode();
QRect edge_detect_rect(pos, pos);
int edge_detect_radius = fontMetrics().height();
edge_detect_rect.adjust(-edge_detect_radius, -edge_detect_radius, edge_detect_radius, edge_detect_radius);
QList<QGraphicsItem*> items = this->items(edge_detect_rect);
NodeViewEdge* new_drop_edge = nullptr;
// See if there is an edge here
for (QGraphicsItem* item : qAsConst(items)) {
new_drop_edge = dynamic_cast<NodeViewEdge*>(item);
if (new_drop_edge) {
drop_input_.Reset();
NodeValue::Type drop_edge_data_type = new_drop_edge->input().GetDataType();
// 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()) {
if (input == Node::kEnabledInput) {
// Ignore enabled input
continue;
}
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->InputsFrom(new_drop_edge->input().node(), true)) {
drop_input_.Reset();
}
if (drop_input_.IsValid()) {
break;
} else {
new_drop_edge = nullptr;
}
}
}
if (drop_edge_ != new_drop_edge) {
if (drop_edge_) {
drop_edge_->SetHighlighted(false);
}
drop_edge_ = new_drop_edge;
if (drop_edge_) {
drop_edge_->SetHighlighted(true);
}
}
}
}
QVector<Node*> NodeView::ProcessDroppingAttachedNodes(MultiUndoCommand *command, Node *select_context, const QPoint &pos)
{
QVector<Node*> select_nodes;
// Make a copy
QVector<AttachedItem> attached = attached_items_;
for (int i=0; i<attached.size(); i++) {
const AttachedItem &ai = attached.at(i);
if (ai.node->InputsFrom(select_context, true)) {
attached.removeAt(i);
} else if (select_context->ContextContainsNode(ai.node)) {
select_nodes.append(ai.node);
attached.removeAt(i);
}
}
{
MultiUndoCommand *add_command = new MultiUndoCommand();
foreach (const AttachedItem &ai, attached) {
// Add node to the same graph that the context is in
if (ai.node->parent() != select_context->parent()) {
add_command->add_child(new NodeAddCommand(select_context->parent(), ai.node));
if (ai.node->IsItem() && !ai.node->folder()) {
add_command->add_child(new FolderAddChild(select_context->parent()->root(), ai.node));
}
}
// Add node to the context
if (ai.item) {
select_nodes.append(ai.node);
add_command->add_child(new NodeSetPositionCommand(ai.node, select_context, scene_.context_map().value(select_context)->MapScenePosToNodePosInContext(ai.item->pos())));
}
}
if (add_command->child_count()) {
add_command->redo_now();
command->add_child(add_command);
} else {
delete add_command;
}
}
{
// Dropped attached item onto an edge, connect it between them
MultiUndoCommand *drop_edge_command = new MultiUndoCommand();
if (attached.size() == 1) {
Node* dropping_node = nullptr;
foreach (const AttachedItem &ai, attached) {
if (ai.item && !ai.node->InputsFrom(select_context, true)) {
dropping_node = ai.node;
break;
}
}
if (dropping_node && drop_edge_) {
// Remove old edge
drop_edge_command->add_child(new NodeEdgeRemoveCommand(drop_edge_->output(), drop_edge_->input()));
// Place new edges
drop_edge_command->add_child(new NodeEdgeAddCommand(drop_edge_->output(), drop_input_));
drop_edge_command->add_child(new NodeEdgeAddCommand(dropping_node, drop_edge_->input()));
}
drop_edge_ = nullptr;
}
if (drop_edge_command->child_count()) {
drop_edge_command->redo_now();
command->add_child(drop_edge_command);
} else {
delete drop_edge_command;
}
}
DetachItemsFromCursor(false);
return select_nodes;
}
Node *NodeView::GetContextAtMousePos(const QPoint &p)
{
QList<QGraphicsItem*> items_at_cursor = this->items(p);
foreach (QGraphicsItem *i, items_at_cursor) {
if (NodeViewContext *context_item = dynamic_cast<NodeViewContext*>(i)) {
return context_item->GetContext();
}
}
return nullptr;
}
void NodeView::ConnectSelectionChangedSignal()
{
connect(&scene_, &QGraphicsScene::selectionChanged, this, &NodeView::UpdateSelectionCache);
}
void NodeView::DisconnectSelectionChangedSignal()
{
disconnect(&scene_, &QGraphicsScene::selectionChanged, this, &NodeView::UpdateSelectionCache);
}
void NodeView::ZoomIntoCursorPosition(QWheelEvent *event, double multiplier, const QPointF& cursor_pos)
{
Q_UNUSED(event)
double test_scale = scale_ * multiplier;
if (test_scale > kMinimumScale) {
int anchor_x = qRound(double(cursor_pos.x() + horizontalScrollBar()->value()) / scale_ * test_scale - cursor_pos.x());
int anchor_y = qRound(double(cursor_pos.y() + verticalScrollBar()->value()) / scale_ * test_scale - cursor_pos.y());
scale(multiplier, multiplier);
this->horizontalScrollBar()->setValue(anchor_x);
this->verticalScrollBar()->setValue(anchor_y);
scale_ = test_scale;
}
}
bool NodeView::event(QEvent *event)
{
if (event->type() == QEvent::ShortcutOverride) {
QKeyEvent *se = static_cast<QKeyEvent *>(event);
if (se->key() == Qt::Key_Left
|| se->key() == Qt::Key_Right
|| se->key() == Qt::Key_Up
|| se->key() == Qt::Key_Down) {
se->accept();
return true;
}
}
return super::event(event);
}
bool NodeView::eventFilter(QObject *object, QEvent *event)
{
return super::eventFilter(object, event);
}
void NodeView::changeEvent(QEvent *e)
{
// Add translation code
super::changeEvent(e);
}
void NodeView::ZoomFromKeyboard(double multiplier)
{
QPoint cursor_pos = mapFromGlobal(QCursor::pos());
// If the cursor is not currently within the widget, zoom into the center
if (!rect().contains(cursor_pos)) {
cursor_pos = QPoint(width()/2, height()/2);
}
ZoomIntoCursorPosition(nullptr, multiplier, cursor_pos);
}
void NodeView::ClearCreateEdgeInputIfNecessary()
{
if (create_edge_from_output_ && create_edge_input_.IsValid()) {
create_edge_input_.Reset();
}
}
QPointF NodeView::GetEstimatedPositionForContext(NodeViewItem *item, Node *context) const
{
return item->GetNodePosition() - context_offsets_.value(context);
}
NodeViewItem *NodeView::GetAssumedItemForSelectedNode(Node *node)
{
// Try to find corresponding selected item
foreach (NodeViewContext *ctx, scene_.context_map()) {
NodeViewItem *item = ctx->GetItemFromMap(node);
if (item && item->GetNode() == node && item->isSelected()) {
// Good enough
return item;
}
}
return nullptr;
}
bool NodeView::GetAssumedPositionForSelectedNode(Node *node, Node::Position *pos)
{
if (NodeViewItem *item = GetAssumedItemForSelectedNode(node)) {
*pos = item->GetNodePositionData();
return true;
} else {
return false;
}
}
Menu *NodeView::CreateAddMenu(Menu *parent)
{
Menu* add_menu = NodeFactory::CreateMenu(parent);
add_menu->setTitle(tr("Add"));
connect(add_menu, &Menu::triggered, this, &NodeView::CreateNodeSlot);
return add_menu;
}
void NodeView::PositionNewEdge(const QPoint &pos)
{
// Determine scene coordinate
QPointF scene_pt = mapToScene(pos);
// Find if the cursor is currently inside an item
NodeViewItem* item_at_cursor = dynamic_cast<NodeViewItem*>(itemAt(pos));
NodeViewItem *source_item = create_edge_from_output_ ? create_edge_output_item_ : create_edge_input_item_;
NodeViewItem *&opposing_item = create_edge_from_output_ ? create_edge_input_item_ : create_edge_output_item_;
// Filter out connecting to self
if (item_at_cursor && item_at_cursor->GetNode() == source_item->GetNode()) {
item_at_cursor = nullptr;
}
// Collapse any items that the cursor is no longer inside
int i=create_edge_expanded_items_.size() - 1;
for ( ; i>=0; i--) {
NodeViewItem* nvi = create_edge_expanded_items_.at(i);
QPointF local_pt = nvi->mapFromScene(scene_pt);
if (nvi->scene() == &scene_ && (nvi->contains(local_pt) || (!nvi->IsOutputItem() && nvi->parentItem()->contains(nvi->parentItem()->mapFromScene(scene_pt)) && local_pt.y() > nvi->rect().bottom()))) {
break;
} else {
// Collapsing an item will destroy its children, so if the cursor item happens to be a child
// of the item we're about to collapse, set it to null
if (item_at_cursor && item_at_cursor->parentItem() == nvi) {
item_at_cursor = nullptr;
}
if (opposing_item && opposing_item->parentItem() == nvi) {
opposing_item = nullptr;
ClearCreateEdgeInputIfNecessary();
}
CollapseItem(nvi);
}
}
create_edge_expanded_items_.resize(i + 1);
// Expand item if possible
if (item_at_cursor
&& item_at_cursor->CanBeExpanded()
&& !item_at_cursor->IsExpanded()
&& create_edge_from_output_) {
ExpandItem(item_at_cursor);
create_edge_expanded_items_.append(item_at_cursor);
}
// Filter out connecting to a node that connects to us or an item of the same type
if (item_at_cursor
&& ((create_edge_from_output_ && source_item->GetNode()->InputsFrom(item_at_cursor->GetNode(), true))
|| (!create_edge_from_output_ && item_at_cursor->GetNode()->InputsFrom(source_item->GetNode(), true))
|| (create_edge_from_output_ == item_at_cursor->IsOutputItem()))) {
item_at_cursor = nullptr;
}
// Filter out "output node" of the context, we assume users won't want to fetch the output of this
if (item_at_cursor && !create_edge_from_output_ && item_at_cursor->IsLabelledAsOutputOfContext()) {
item_at_cursor = nullptr;
}
// If the item has changed
if (item_at_cursor != opposing_item) {
// If we had a destination active, disconnect from it since the item has changed
if (opposing_item) {
opposing_item->SetHighlighted(false);
opposing_item = nullptr;
}
// Clear cached input
ClearCreateEdgeInputIfNecessary();
// If this is an input and we're
opposing_item = item_at_cursor;
if (opposing_item) {
opposing_item->SetHighlighted(true);
if (!opposing_item->IsOutputItem()) {
create_edge_input_ = opposing_item->GetInput();
}
}
}
QPointF output_point = create_edge_output_item_ ? create_edge_output_item_->GetOutputPoint() : scene_pt;
QPointF input_point = create_edge_input_.IsValid() ? create_edge_input_item_->GetInputPoint() : scene_pt;
create_edge_->SetPoints(output_point, input_point);
create_edge_->SetConnected(create_edge_output_item_ && create_edge_input_.IsValid());
}
void NodeView::GroupNodes()
{
// Get items
QVector<NodeViewItem*> items = scene_.GetSelectedItems();
if (items.isEmpty()) {
return;
}
// Get node context
Node *context = items.first()->GetContext();
QPointF avg_pos = items.first()->GetNodePosition();
for (int i=1; i<items.size(); i++) {
if (items.at(i)->GetContext() != context) {
QMessageBox::critical(this, tr("Failed to group nodes"), tr("Nodes can only be grouped if they're in the same context."));
return;
}
avg_pos += items.at(i)->GetNodePosition();
}
avg_pos /= items.size();
// Create group
NodeGroup *group = new NodeGroup();
// Add group to graph and context
MultiUndoCommand *command = new MultiUndoCommand();
// Add nodes to group
Node *output_passthrough = nullptr;
QVector<Node*> nodes_to_group = selected_nodes_;
DeselectAll();
foreach (Node *n, nodes_to_group) {
command->add_child(new NodeRemovePositionFromContextCommand(n, context));
command->add_child(new NodeSetPositionCommand(n, group, context->GetNodePositionDataInContext(n)));
for (auto it=n->inputs().cbegin(); it!=n->inputs().cend(); it++) {
NodeInput input(n, *it, -1);
if (!input.IsConnected() || !nodes_to_group.contains(input.GetConnectedOutput())) {
command->add_child(new NodeGroupAddInputPassthrough(group, input));
}
}
if (!output_passthrough) {
// Default to the first node we find that doesn't output to a node inside the group
output_passthrough = nodes_to_group.first();
foreach (Node *potential_in, nodes_to_group) {
if (potential_in != n && !potential_in->InputsFrom(n, false)) {
output_passthrough = n;
break;
}
}
}
}
// Set output passthrough
command->add_child(new NodeGroupSetOutputPassthrough(group, output_passthrough));
// Add group to graph
command->add_child(new NodeAddCommand(context->parent(), group));
command->add_child(new NodeSetPositionCommand(group, context, avg_pos));
// Do command
Core::instance()->LabelNodes({group}, command);
Core::instance()->undo_stack()->push(command, tr("Grouped Nodes"));
}
void NodeView::UngroupNodes()
{
NodeViewItem *group_item = nullptr;
QVector<NodeViewItem*> items = scene_.GetSelectedItems();
if (items.isEmpty()) {
return;
}
NodeGroup *group = nullptr;
foreach (NodeViewItem *i, items) {
if ((group = dynamic_cast<NodeGroup*>(i->GetNode()))) {
group_item = i;
break;
}
}
if (!group_item) {
return;
}
MultiUndoCommand *command = new MultiUndoCommand();
Node *context = group_item->GetContext();
command->add_child(new NodeRemovePositionFromContextCommand(group, context));
command->add_child(new NodeRemoveAndDisconnectCommand(group));
for (auto it=group->GetContextPositions().cbegin(); it!=group->GetContextPositions().cend(); it++) {
command->add_child(new NodeRemovePositionFromContextCommand(it.key(), group));
command->add_child(new NodeSetPositionCommand(it.key(), context, group->GetNodePositionDataInContext(it.key())));
}
Core::instance()->undo_stack()->push(command, tr("Ungrouped Nodes"));
}
void NodeView::ShowNodeProperties()
{
Node *first_node = selected_nodes_.first();
if (NodeGroup *group = dynamic_cast<NodeGroup*>(first_node)) {
if (!overlay_view_) {
overlay_view_ = new NodeView(this);
overlay_view_->show();
QPushButton *overlay_close_btn = new QPushButton(overlay_view_);
overlay_close_btn->setIcon(icon::Error);
int offset = overlay_close_btn->sizeHint().width()/2;
overlay_close_btn->move(offset, offset);
overlay_close_btn->show();
connect(overlay_view_, &NodeView::NodesSelected, this, &NodeView::NodesSelected);
connect(overlay_view_, &NodeView::NodesDeselected, this, &NodeView::NodesDeselected);
connect(overlay_view_, &NodeView::NodeGroupOpened, this, &NodeView::NodeGroupOpened);
connect(overlay_view_, &NodeView::NodeGroupClosed, this, &NodeView::NodeGroupClosed);
connect(overlay_view_, &NodeView::EscPressed, this, &NodeView::CloseOverlay);
connect(overlay_close_btn, &QPushButton::clicked, this, &NodeView::CloseOverlay);
const QColor &bgcol = overlay_view_->palette().base().color();
overlay_view_->setStyleSheet(QStringLiteral("QGraphicsView { background: rgba(%1, %2, %3, 0.8); }").arg(QString::number(bgcol.red()), QString::number(bgcol.green()), QString::number(bgcol.blue())));
overlay_close_btn->setStyleSheet(QStringLiteral("background: transparent; border: none;"));
}
overlay_view_->SetContexts({group});
ResizeOverlay();
QMetaObject::invokeMethod(overlay_view_, &NodeView::CenterOnItemsBoundingRect, Qt::QueuedConnection);
overlay_view_->setFocus();
emit NodesDeselected(selected_nodes_);
emit NodeSelectionChanged(QVector<Node*>());
emit NodeSelectionChangedWithContexts(QVector<Node::ContextPair>());
overlay_view_->SelectAll();
emit NodeGroupOpened(group);
} else {
LabelSelectedNodes();
}
}
void NodeView::LabelSelectedNodes()
{
Core::instance()->LabelNodes(selected_nodes_);
}
void NodeView::ItemAboutToBeDeleted(NodeViewItem *item)
{
dragging_items_.remove(item);
if (create_edge_) {
// Item should be removed from scene, but not yet deleted, allowing a safe PositionNewEdge call
// to disconnect
PositionNewEdge(mapFromGlobal(QCursor::pos()));
QGraphicsItem *test = item;
do {
if (test == item) {
break;
}
test = test->parentItem();
} while (test);
if (test == item) {
// Cancel edge function
EndEdgeDrag(true);
}
}
}
void NodeView::CloseOverlay()
{
if (overlay_view_->overlay_view_) {
overlay_view_->CloseOverlay();
}
overlay_view_->deleteLater();
overlay_view_ = nullptr;
emit NodeGroupClosed();
}
void NodeView::AddContext(Node *n)
{
NodeViewContext *ctx = scene_.AddContext(n);
connect(ctx, &NodeViewContext::ItemAboutToBeDeleted, this, &NodeView::ItemAboutToBeDeleted);
connect(n, &Node::RemovedFromGraph, this, &NodeView::NodeRemovedFromGraph);
}
void NodeView::RemoveContext(Node *n)
{
scene_.RemoveContext(n);
disconnect(n, &Node::RemovedFromGraph, this, &NodeView::NodeRemovedFromGraph);
}
bool NodeView::IsItemAttachedToCursor(NodeViewItem *item) const
{
foreach (const AttachedItem &ai, attached_items_) {
if (ai.item == item) {
return true;
}
}
return false;
}
void NodeView::ExpandItem(NodeViewItem *item)
{
item->SetExpanded(true);
item->setZValue(100);
}
void NodeView::CollapseItem(NodeViewItem *item)
{
item->SetExpanded(false);
item->setZValue(0);
}
void NodeView::EndEdgeDrag(bool cancel)
{
// Check if the edge was reconnected to the same place as before
MultiUndoCommand* command = new MultiUndoCommand();
bool reconnected_to_itself = false;
if (create_edge_already_exists_) {
if (!cancel) {
if (create_edge_output_item_ == create_edge_->from_item() && create_edge_->input() == create_edge_input_) {
reconnected_to_itself = true;
} else {
// We are moving (or removing) an existing edge
command->add_child(new NodeEdgeRemoveCommand(create_edge_->output(), create_edge_->input()));
}
}
} else {
// We're creating a new edge, which means this UI object is only temporary
delete create_edge_;
}
create_edge_ = nullptr;
// Clear highlight if we set one
if (create_edge_output_item_) {
create_edge_output_item_->SetHighlighted(false);
}
if (create_edge_input_item_) {
create_edge_input_item_->SetHighlighted(false);
}
QString command_name;
NodeInput &creating_input = create_edge_input_;
if (create_edge_output_item_ && create_edge_input_item_ && !cancel) {
if (creating_input.IsValid()) {
// Make connection
if (!reconnected_to_itself) {
Node *creating_output = create_edge_output_item_->GetNode();
while (NodeGroup *output_group = dynamic_cast<NodeGroup*>(creating_output)) {
creating_output = output_group->GetOutputPassthrough();
}
while (NodeGroup *input_group = dynamic_cast<NodeGroup*>(creating_input.node())) {
creating_input = input_group->GetInputFromID(creating_input.input());
}
if (creating_input.IsConnected()) {
Node::OutputConnection existing_edge_to_remove = {creating_input.GetConnectedOutput(), creating_input};
Node *already_connected_output = creating_input.GetConnectedOutput();
NodeViewContext *ctx = GetContextItemFromNodeItem(create_edge_input_item_);
if (ctx && !ctx->GetItemFromMap(already_connected_output)) {
if (QMessageBox::warning(this, QString(), tr("Input \"%1\" is currently connected to node \"%2\", which is not visible in this context. "
"By connecting this, that connection will be removed. Do you wish to continue?").arg(creating_input.name(), already_connected_output->GetLabelAndName()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
cancel = true;
}
}
if (!cancel) {
command->add_child(new NodeEdgeRemoveCommand(existing_edge_to_remove.first, existing_edge_to_remove.second));
}
}
if (!cancel) {
command->add_child(new NodeEdgeAddCommand(creating_output, creating_input));
command_name = Node::GetConnectCommandString(creating_output, creating_input);
// If the output is not in the input's context, add it now. We check the item rather than
// the node itself, because sometimes a node may not be in the context but another node
// representing it will be (e.g. groups)
if (!scene_.context_map().value(create_edge_input_item_->GetContext())->GetItemFromMap(creating_output)) {
command->add_child(new NodeSetPositionCommand(creating_output, create_edge_input_item_->GetContext(), scene_.context_map().value(create_edge_input_item_->GetContext())->MapScenePosToNodePosInContext(create_edge_output_item_->scenePos())));
}
}
}
}
}
creating_input.Reset();
create_edge_output_item_ = nullptr;
create_edge_input_item_ = nullptr;
// Collapse any items we expanded
for (auto it=create_edge_expanded_items_.crbegin(); it!=create_edge_expanded_items_.crend(); it++) {
CollapseItem(*it);
}
create_edge_expanded_items_.clear();
Core::instance()->undo_stack()->push(command, command_name);
}
void NodeView::PostPaste(const QVector<Node *> &new_nodes, const Node::PositionMap &map)
{
QVector<AttachedItem> new_attached;
NodeViewItem *first_item = nullptr;
for (int i=0; i<new_nodes.size(); i++) {
Node *node = new_nodes.at(i);
// Determine if item had a position, if not don't create an item for it
NodeViewItem *new_item;
if (map.contains(node)) {
new_item = new NodeViewItem(node, nullptr);
new_item->SetFlowDirection(scene_.GetFlowDirection());
new_item->SetNodePosition(map.value(node));
scene_.addItem(new_item);
if (!first_item) {
first_item = new_item;
}
} else {
new_item = nullptr;
}
new_attached.append({new_item, node, QPointF(0, 0)});
}
// Correct positions
if (first_item) {
for (int i=0; i<new_attached.size(); i++) {
AttachedItem &ai = new_attached[i];
if (ai.item) {
ai.original_pos = ai.item->pos() - first_item->pos();
}
}
}
SetAttachedItems(new_attached);
}
void NodeView::ResizeOverlay()
{
overlay_view_->resize(this->size());
}
NodeViewContext *NodeView::GetContextItemFromNodeItem(NodeViewItem *item)
{
QGraphicsItem *i = item;
while ((i = i->parentItem())) {
if (NodeViewContext *nvc = dynamic_cast<NodeViewContext*>(i)) {
return nvc;
}
}
return nullptr;
}
void NodeView::SetAttachedItems(const QVector<AttachedItem> &items)
{
// Detach anything currently attached
DetachItemsFromCursor();
attached_items_ = items;
// Move to cursor
MoveAttachedNodesToCursor(mapFromGlobal(QCursor::pos()));
}
}
| 50,819
|
C++
|
.cpp
| 1,394
| 31.228838
| 251
| 0.670424
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,861
|
nodeviewitem.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewitem.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeviewitem.h"
#include <QDebug>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include "common/qtutils.h"
#include "config/config.h"
#include "core.h"
#include "node/nodeundo.h"
#include "nodeview.h"
#include "nodeviewscene.h"
#include "ui/colorcoding.h"
#include "ui/icons/icons.h"
#include "window/mainwindow/mainwindow.h"
namespace olive {
NodeViewItem::NodeViewItem(Node *node, const QString &input, int element, Node *context, QGraphicsItem *parent) :
QGraphicsRectItem(parent),
node_(node),
input_(input),
element_(element),
context_(context),
expanded_(false),
highlighted_(false),
flow_dir_(NodeViewCommon::kInvalidDirection),
arrow_click_(false),
label_as_output_(false)
{
//
// We use font metrics to set all the UI measurements for DPI-awareness
//
// Set border width
node_border_width_ = DefaultItemBorder();
// Set rect size to default
SetRectSize();
// Create connector
input_connector_ = new NodeViewItemConnector(false, this);
output_connector_ = new NodeViewItemConnector(true, this);
connect(node_, &Node::LabelChanged, this, &NodeViewItem::NodeAppearanceChanged);
connect(node_, &Node::ColorChanged, this, &NodeViewItem::NodeAppearanceChanged);
if (IsOutputItem()) {
connect(node_, &Node::InputAdded, this, &NodeViewItem::RepopulateInputs);
connect(node_, &Node::InputRemoved, this, &NodeViewItem::RepopulateInputs);
RepopulateInputs();
// Set flags for this widget
setFlag(QGraphicsItem::ItemSendsGeometryChanges);
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
if (context_) {
SetNodePosition(context_->GetNodePositionDataInContext(node_));
}
} else {
output_connector_->setVisible(false);
connect(node_, &Node::InputArraySizeChanged, this, &NodeViewItem::InputArraySizeChanged);
connect(node_, &Node::InputArraySizeChanged, this, &NodeViewItem::InputArraySizeChanged);
}
// This should be set during runtime, but just in case here's a default fallback
SetFlowDirection(NodeViewCommon::kLeftToRight);
}
NodeViewItem::~NodeViewItem()
{
Q_ASSERT(edges_.isEmpty());
}
Node::Position NodeViewItem::GetNodePositionData() const
{
return Node::Position(GetNodePosition(), IsExpanded());
}
QPointF NodeViewItem::GetNodePosition() const
{
return ScreenToNodePoint(pos(), flow_dir_);
}
void NodeViewItem::SetNodePosition(const QPointF &pos)
{
cached_node_pos_ = pos;
UpdateNodePosition();
}
void NodeViewItem::SetNodePosition(const Node::Position &pos)
{
SetNodePosition(pos.position);
SetExpanded(pos.expanded);
}
QVector<NodeViewEdge *> NodeViewItem::GetAllEdgesRecursively() const
{
QVector<NodeViewEdge *> list = edges_;
foreach (NodeViewItem *item, children_) {
list.append(item->GetAllEdgesRecursively());
}
return list;
}
int NodeViewItem::DefaultTextPadding()
{
return QFontMetrics(QFont()).height() / 4;
}
int NodeViewItem::DefaultItemHeight()
{
return QFontMetrics(QFont()).height() + DefaultTextPadding() * 2;
}
int NodeViewItem::DefaultItemWidth()
{
return QtUtils::QFontMetricsWidth(QFontMetrics(QFont()), "HHHHHHHHHHHHHHHH");;
}
int NodeViewItem::DefaultItemBorder()
{
return QFontMetrics(QFont()).height() / 12;
}
QPointF NodeViewItem::NodeToScreenPoint(QPointF p, NodeViewCommon::FlowDirection direction)
{
switch (direction) {
case NodeViewCommon::kLeftToRight:
// NodeGraphs are always left-to-right internally, no need to translate
break;
case NodeViewCommon::kRightToLeft:
// Invert X value
p.setX(-p.x());
break;
case NodeViewCommon::kTopToBottom:
// Swap X/Y
p = QPointF(p.y(), p.x());
break;
case NodeViewCommon::kBottomToTop:
// Swap X/Y and invert Y
p = QPointF(p.y(), -p.x());
break;
case NodeViewCommon::kInvalidDirection:
break;
}
// Multiply by item sizes for this direction
p.setX(p.x() * DefaultItemHorizontalPadding(direction));
p.setY(p.y() * DefaultItemVerticalPadding(direction));
return p;
}
QPointF NodeViewItem::ScreenToNodePoint(QPointF p, NodeViewCommon::FlowDirection direction)
{
// Divide by item sizes for this direction
p.setX(p.x() / DefaultItemHorizontalPadding(direction));
p.setY(p.y() / DefaultItemVerticalPadding(direction));
switch (direction) {
case NodeViewCommon::kLeftToRight:
// NodeGraphs are always left-to-right internally, no need to translate
break;
case NodeViewCommon::kRightToLeft:
// Invert X value
p.setX(-p.x());
break;
case NodeViewCommon::kTopToBottom:
// Swap X/Y
p = QPointF(p.y(), p.x());
break;
case NodeViewCommon::kBottomToTop:
// Swap X/Y and invert Y
p = QPointF(-p.y(), p.x());
break;
case NodeViewCommon::kInvalidDirection:
break;
}
return p;
}
qreal NodeViewItem::DefaultItemHorizontalPadding(NodeViewCommon::FlowDirection dir)
{
if (NodeViewCommon::GetFlowOrientation(dir) == Qt::Horizontal) {
return DefaultItemWidth() * 1.5;
} else {
return DefaultItemWidth() * 1.25;
}
}
qreal NodeViewItem::DefaultItemVerticalPadding(NodeViewCommon::FlowDirection dir)
{
if (NodeViewCommon::GetFlowOrientation(dir) == Qt::Horizontal) {
return DefaultItemHeight() * 1.5;
} else {
return DefaultItemHeight() * 2.0;
}
}
qreal NodeViewItem::DefaultItemHorizontalPadding() const
{
return DefaultItemHorizontalPadding(flow_dir_);
}
qreal NodeViewItem::DefaultItemVerticalPadding() const
{
return DefaultItemVerticalPadding(flow_dir_);
}
void NodeViewItem::AddEdge(NodeViewEdge *edge)
{
edges_.append(edge);
}
void NodeViewItem::RemoveEdge(NodeViewEdge *edge)
{
edges_.removeOne(edge);
}
void NodeViewItem::SetExpanded(bool e, bool hide_titlebar)
{
if (!CanBeExpanded() || (expanded_ == e)) {
return;
}
expanded_ = e;
if (context_) {
context_->SetNodeExpandedInContext(node_, e);
}
if (IsOutputItem()) {
// We don't have to check has_connectable_inputs_ here because we did it at the top
input_connector_->setVisible(!expanded_);
}
if (expanded_) {
node_->Retranslate();
if (IsOutputItem()) {
// Create items for each input of the node
int i = 1;
foreach (const QString &input, node_->inputs()) {
if (IsInputValid(input)) {
NodeViewItem *item = new NodeViewItem(node_, input, -1, context_, this);
children_.append(item);
i++;
}
}
QVector<NodeViewEdge*> edges = edges_;
for (auto it=edges.cbegin(); it!=edges.cend(); it++) {
if ((*it)->to_item() == this) {
(*it)->set_to_item(GetItemForInput((*it)->input()));
}
}
} else {
// Create items for each element of the input array
int arr_sz = node_->InputArraySize(input_);
children_.resize(arr_sz);
for (int i=0; i<arr_sz; i++) {
NodeViewItem *item = new NodeViewItem(node_, input_, i, context_, this);
children_[i] = item;
}
QVector<NodeViewEdge*> edges = edges_;
for (auto it=edges.cbegin(); it!=edges.cend(); it++) {
if ((*it)->to_item() == this) {
(*it)->set_to_item(GetItemForInput((*it)->input()));
}
}
}
} else {
foreach (NodeViewItem *child, children_) {
QVector<NodeViewEdge*> child_edges = child->edges();
foreach (NodeViewEdge *edge, child_edges) {
edge->set_to_item(this);
}
delete child;
}
children_.clear();
}
UpdateChildrenPositions();
if (flow_dir_ == NodeViewCommon::kTopToBottom) {
UpdateOutputConnectorPosition();
}
ReadjustAllEdges();
UpdateContextRect();
update();
}
void NodeViewItem::ToggleExpanded()
{
SetExpanded(!IsExpanded());
}
void NodeViewItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
// Use main window palette since the palette passed in `widget` is the NodeView palette which
// has been slightly modified
QPalette app_pal = Core::instance()->main_window()->palette();
// We only draw a single unit's worth
QRectF single_unit_rect = rect();
single_unit_rect.setHeight(DefaultItemHeight());
if (IsOutputItem()) {
// Set output item colors
painter->setPen(Qt::black);
painter->setBrush(node_->brush(single_unit_rect.top(), single_unit_rect.bottom()));
} else {
// Set input item colors
painter->setPen(Qt::NoPen);
painter->setBrush(element_ == -1 ? app_pal.color(QPalette::Window) : app_pal.color(QPalette::Base));
}
painter->drawRect(single_unit_rect);
// Draw highlight if applicable
if (highlighted_) {
QColor highlight_col = app_pal.color(QPalette::Text);
highlight_col.setAlpha(64);
painter->setBrush(highlight_col);
painter->drawRect(rect());
}
// Determine what text to draw and whether to draw an arrow
QString node_label, node_name;
if (IsOutputItem()) {
if (label_as_output_) {
node_name = QCoreApplication::translate("NodeViewItem", "Output");
} else {
node_label = node_->GetLabel();
node_name = node_->ShortName();
}
} else {
if (element_ == -1) {
node_name = node_->GetInputName(input_);
} else {
node_name = QString::number(element_ + node_->GetInputProperty(input_, QStringLiteral("arraystart")).toInt());
}
}
// Draw arrow if necessary
int arrow_size = CanBeExpanded() ? DrawExpandArrow(painter) : 0;
if (IsOutputItem()) {
// Determine the text color (automatically calculate from node background color)
painter->setPen(ColorCoding::GetUISelectorColor(node_->color()));
} else {
// Just use text item
painter->setPen(app_pal.text().color());
}
if (node_label.isEmpty()) {
// Draw name only
DrawNodeTitle(painter, node_name, single_unit_rect, Qt::AlignVCenter, arrow_size);
} else {
int text_pad = DefaultTextPadding()/2;
QRectF safe_label_bounds = single_unit_rect.adjusted(text_pad, text_pad, -text_pad, -text_pad);
QFont f;
qreal font_sz = f.pointSizeF();
// Draw label as larger/upper text
f.setPointSizeF(font_sz * 0.8);
painter->setFont(f);
DrawNodeTitle(painter, node_label, safe_label_bounds, Qt::AlignTop, arrow_size);
// Draw node name as smaller/lower text
f.setPointSizeF(font_sz * 0.6);
painter->setFont(f);
DrawNodeTitle(painter, node_name, safe_label_bounds, Qt::AlignBottom, arrow_size);
}
// Draw final border (output only)
if (IsOutputItem()) {
QPen border_pen;
border_pen.setWidth(node_border_width_);
if (option->state & QStyle::State_Selected) {
border_pen.setColor(app_pal.color(QPalette::Highlight));
} else {
border_pen.setColor(Qt::black);
}
painter->setPen(border_pen);
painter->setBrush(Qt::NoBrush);
painter->drawRect(rect());
}
}
void NodeViewItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (last_arrow_rect_.contains(event->pos().toPoint())) {
arrow_click_ = true;
ToggleExpanded();
return;
}
event->setModifiers(QtUtils::FlipControlAndShiftModifiers(event->modifiers()));
QGraphicsRectItem::mousePressEvent(event);
}
void NodeViewItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (arrow_click_) {
return;
}
event->setModifiers(QtUtils::FlipControlAndShiftModifiers(event->modifiers()));
QGraphicsRectItem::mouseMoveEvent(event);
}
void NodeViewItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (arrow_click_) {
arrow_click_ = false;
return;
}
event->setModifiers(QtUtils::FlipControlAndShiftModifiers(event->modifiers()));
QGraphicsRectItem::mouseReleaseEvent(event);
}
QVariant NodeViewItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (node_) {
if (change == ItemPositionHasChanged) {
ReadjustAllEdges();
UpdateContextRect();
} else if (change == ItemSelectedHasChanged) {
if (value.toBool()) {
qDebug() << "Selected node:" << node_;
}
}
}
return QGraphicsItem::itemChange(change, value);
}
void NodeViewItem::ReadjustAllEdges()
{
foreach (NodeViewEdge* edge, edges_) {
if (NodeViewItem *to_item = edge->to_item()) {
static_cast<NodeViewItem*>(to_item->parentItem())->UpdateFlowDirectionOfInputItem(to_item);
}
edge->Adjust();
}
foreach (NodeViewItem *child, children_) {
child->ReadjustAllEdges();
}
}
void NodeViewItem::UpdateContextRect()
{
QGraphicsItem *item = parentItem();
while (item) {
if (NodeViewContext *ctx = dynamic_cast<NodeViewContext*>(item)) {
ctx->UpdateRect();
break;
}
item = item->parentItem();
}
}
void NodeViewItem::DrawNodeTitle(QPainter* painter, QString text, const QRectF& rect, Qt::Alignment vertical_align, int icon_full_size)
{
QFontMetrics fm = painter->fontMetrics();
// Calculate how much space we have for text
int item_width = this->rect().width();
int max_text_width = item_width - DefaultTextPadding() * 2 - icon_full_size;
int label_width = QtUtils::QFontMetricsWidth(fm, text);
// Concatenate text if necessary (adds a "..." to the end and removes characters until the
// string fits in the bounds)
if (label_width > max_text_width) {
QString concatenated;
do {
text.chop(1);
concatenated = QCoreApplication::translate("NodeViewItem", "%1...").arg(text);
} while ((label_width = QtUtils::QFontMetricsWidth(fm, concatenated)) > max_text_width);
text = concatenated;
}
// Determine X position (favors horizontal centering unless it'll overrun the arrow)
QRectF text_rect = rect;
Qt::Alignment text_align = Qt::AlignHCenter | vertical_align;
int likely_x = item_width / 2 - label_width / 2;
if (likely_x < icon_full_size) {
text_rect.adjust(icon_full_size, 0, 0, 0);
text_align = Qt::AlignLeft | vertical_align;
}
// Draw the text in a rect (the rect is sized around text already in the constructor)
painter->drawText(text_rect,
text_align,
text);
}
int NodeViewItem::DrawExpandArrow(QPainter *painter)
{
// Draw right or down arrow based on expanded state
int icon_size = painter->fontMetrics().height()/2;
int icon_padding = DefaultItemHeight() / 2 - icon_size / 2;
int icon_full_size = icon_size + icon_padding * 2;
painter->setRenderHint(QPainter::SmoothPixmapTransform);
const QIcon& expand_icon = IsExpanded() ? icon::TriDown : icon::TriRight;
int icon_size_scaled = icon_size * painter->transform().m11();
last_arrow_rect_ = QRect(this->rect().x() + icon_padding,
this->rect().y() + icon_padding,
icon_size,
icon_size);
painter->drawPixmap(last_arrow_rect_, expand_icon.pixmap(QSize(icon_size_scaled, icon_size_scaled)));
return icon_full_size;
}
void NodeViewItem::SetLabelAsOutput(bool e)
{
label_as_output_ = e;
output_connector_->setVisible(!e);
update();
}
QPointF NodeViewItem::GetInputPoint() const
{
return input_connector_->scenePos();
}
QPointF NodeViewItem::GetOutputPoint() const
{
QPointF p = output_connector_->scenePos();
QRectF r = output_connector_->polygon().boundingRect();
switch (flow_dir_) {
case NodeViewCommon::kLeftToRight:
default:
p.setX(p.x() + r.width());
break;
case NodeViewCommon::kRightToLeft:
p.setX(p.x() - r.width());
break;
case NodeViewCommon::kTopToBottom:
p.setY(p.y() + r.height());
break;
case NodeViewCommon::kBottomToTop:
p.setY(p.y() - r.height());
break;
}
return p;
}
void NodeViewItem::SetFlowDirection(NodeViewCommon::FlowDirection dir)
{
if (flow_dir_ != dir) {
flow_dir_ = dir;
input_connector_->SetFlowDirection(dir);
output_connector_->SetFlowDirection(dir);
UpdateInputConnectorPosition();
UpdateOutputConnectorPosition();
if (IsOutputItem()) {
UpdateNodePosition();
}
ReadjustAllEdges();
}
}
void NodeViewItem::UpdateNodePosition()
{
setPos(NodeToScreenPoint(cached_node_pos_, flow_dir_));
}
void NodeViewItem::UpdateInputConnectorPosition()
{
QRectF output_rect = input_connector_->polygon().boundingRect();
NodeViewCommon::FlowDirection using_flow_dir = flow_dir_;
if (IsExpanded() && !NodeViewCommon::IsFlowHorizontal(flow_dir_)) {
if (edges_.isEmpty() || edges_.first()->from_item()->x() < this->x()) {
using_flow_dir = NodeViewCommon::kLeftToRight;
} else {
using_flow_dir = NodeViewCommon::kRightToLeft;
}
}
// Input connector flow directions change conditionally
switch (using_flow_dir) {
case NodeViewCommon::kLeftToRight:
input_connector_->setPos(rect().left() - output_rect.width(), 0);
break;
case NodeViewCommon::kRightToLeft:
input_connector_->setPos(rect().right() + output_rect.width(), 0);
break;
case NodeViewCommon::kTopToBottom:
input_connector_->setPos(rect().center().x(), rect().top() - output_rect.height());
break;
case NodeViewCommon::kBottomToTop:
input_connector_->setPos(rect().center().x(), rect().bottom() + output_rect.height());
break;
case NodeViewCommon::kInvalidDirection:
break;
}
}
void NodeViewItem::UpdateOutputConnectorPosition()
{
switch (flow_dir_) {
case NodeViewCommon::kLeftToRight:
output_connector_->setPos(rect().right(), 0);
break;
case NodeViewCommon::kRightToLeft:
output_connector_->setPos(rect().left(), 0);
break;
case NodeViewCommon::kTopToBottom:
output_connector_->setPos(rect().center().x(), rect().bottom());
break;
case NodeViewCommon::kBottomToTop:
output_connector_->setPos(rect().center().x(), rect().top());
break;
case NodeViewCommon::kInvalidDirection:
break;
}
}
bool NodeViewItem::IsInputValid(const QString &input)
{
return node_->IsInputConnectable(input) && !node_->IsInputHidden(input);
}
void NodeViewItem::SetRectSize(int height_units)
{
// Set rect
int widget_width = DefaultItemWidth();
int widget_height = DefaultItemHeight();
setRect(QRectF(-widget_width/2, -widget_height/2, widget_width, widget_height * height_units));
}
bool NodeViewItem::CanBeExpanded() const
{
if (IsOutputItem()) {
return has_connectable_inputs_;
} else {
return node_->GetInputFlags(input_) & kInputFlagArray && element_ == -1 && !node_->IsInputConnected(input_);
}
}
void NodeViewItem::UpdateChildrenPositions()
{
int y = 1;
int h = DefaultItemHeight();
foreach (NodeViewItem *c, children_) {
c->setPos(QPointF(0, y * h));
y += c->GetLogicalHeightWithChildren();
}
SetRectSize(y);
if (NodeViewItem *p = dynamic_cast<NodeViewItem*>(parentItem())) {
p->UpdateChildrenPositions();
}
}
int NodeViewItem::GetLogicalHeightWithChildren() const
{
int h = 1;
foreach (NodeViewItem *c, children_) {
h += c->GetLogicalHeightWithChildren();
}
return h;
}
void NodeViewItem::UpdateFlowDirectionOfInputItem(NodeViewItem *child)
{
if (!child->IsOutputItem()) {
if (NodeViewCommon::IsFlowVertical(flow_dir_)) {
if (!child->edges().isEmpty() && child->edges().first()->from_item()->scenePos().x() > child->scenePos().x()) {
child->SetFlowDirection(NodeViewCommon::kRightToLeft);
} else {
child->SetFlowDirection(NodeViewCommon::kLeftToRight);
}
} else {
child->SetFlowDirection(flow_dir_);
}
}
}
void NodeViewItem::RepopulateInputs()
{
if (IsOutputItem()) {
has_connectable_inputs_ = false;
foreach (const QString& input, node_->inputs()) {
if (IsInputValid(input)) {
has_connectable_inputs_ = true;
break;
}
}
input_connector_->setVisible(has_connectable_inputs_);
}
if (IsExpanded() && (IsOutputItem() || element_ == -1)) {
// Create or remove inputs when necessary
// NOTE: This is not the most efficient thing in the world, but it does work
SetExpanded(false);
SetExpanded(true);
}
}
void NodeViewItem::InputArraySizeChanged(const QString &input)
{
if (input == input_) {
RepopulateInputs();
}
}
void NodeViewItem::NodeAppearanceChanged()
{
update();
}
void NodeViewItem::SetHighlighted(bool e)
{
highlighted_ = e;
update();
}
NodeViewItem *NodeViewItem::GetItemForInput(NodeInput input)
{
if (NodeGroup *group = dynamic_cast<NodeGroup*>(node_)) {
if (input.node() != group) {
// Translate input to group input
QString id = group->GetIDOfPassthrough(input);
input.set_node(group);
input.set_input(id);
}
}
if (IsExpanded()) {
if (input_.isEmpty()) {
// Look for the input in our children
foreach (NodeViewItem *i, children_) {
if (i->input_ == input.input()) {
return i->GetItemForInput(input);
}
}
} else {
// Look for element in our children
if (input.element() >= 0 && input.element() < children_.size()) {
return children_.at(input.element())->GetItemForInput(input);
}
}
}
// Fallback to this object
return this;
}
}
| 21,774
|
C++
|
.cpp
| 676
| 28.244083
| 135
| 0.695905
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,862
|
nodeviewitemconnector.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewitemconnector.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeviewitemconnector.h"
#include <QApplication>
#include <QFontMetrics>
#include <QPalette>
#include <QPen>
#include "nodeviewitem.h"
namespace olive {
NodeViewItemConnector::NodeViewItemConnector(bool is_output, QGraphicsItem *parent) :
QGraphicsPolygonItem(parent),
output_(is_output)
{
QColor c = qApp->palette().text().color();
setPen(QPen(c, NodeViewItem::DefaultItemBorder()));
setBrush(c);
}
void NodeViewItemConnector::SetFlowDirection(NodeViewCommon::FlowDirection dir)
{
QFont f;
QFontMetricsF fm(f);
int triangle_sz = fm.height()/2;
int triangle_sz_half = triangle_sz / 2;
QPolygonF p;
p.resize(3);
switch (dir) {
case NodeViewCommon::kLeftToRight:
// Triangle pointing right
p[0] = QPointF(0, -triangle_sz_half);
p[1] = QPointF(triangle_sz_half, 0);
p[2] = QPointF(0, triangle_sz_half);
break;
case NodeViewCommon::kTopToBottom:
// Triangle pointing down
p[0] = QPointF(-triangle_sz_half, 0);
p[1] = QPointF(0, triangle_sz_half);
p[2] = QPointF(triangle_sz_half, 0);
break;
case NodeViewCommon::kBottomToTop:
// Triangle pointing up
p[0] = QPointF(-triangle_sz_half, 0);
p[1] = QPointF(0, -triangle_sz_half);
p[2] = QPointF(triangle_sz_half, 0);
break;
case NodeViewCommon::kRightToLeft:
// Triangle pointing left
p[0] = QPointF(0, -triangle_sz_half);
p[1] = QPointF(-triangle_sz_half, 0);
p[2] = QPointF(0, triangle_sz_half);
break;
case NodeViewCommon::kInvalidDirection:
break;
}
setPolygon(p);
}
QPainterPath NodeViewItemConnector::shape() const
{
// Yes, we skip QGraphicsPolygonItem because it adds the polygon. QGraphicsItem adds the
// boundingRect which we modify below
return QGraphicsItem::shape(); // clazy:exclude=skipped-base-method
}
QRectF NodeViewItemConnector::boundingRect() const
{
QRectF b = this->polygon().boundingRect();
const int radius = QFontMetrics(QFont()).height()/2;
b.adjust(-radius, -radius, radius, radius);
return b;
}
}
| 2,739
|
C++
|
.cpp
| 81
| 30.617284
| 90
| 0.729545
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,863
|
nodeviewtoolbar.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewtoolbar.cpp
|
#include "nodeviewtoolbar.h"
#include <QEvent>
#include <QHBoxLayout>
#include "ui/icons/icons.h"
namespace olive {
#define super QWidget
NodeViewToolBar::NodeViewToolBar(QWidget *parent) :
QWidget(parent)
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
add_node_btn_ = new QPushButton();
connect(add_node_btn_, &QPushButton::clicked, this, &NodeViewToolBar::AddNodeClicked);
layout->addWidget(add_node_btn_);
minimap_btn_ = new QPushButton();
minimap_btn_->setCheckable(true);
connect(minimap_btn_, &QPushButton::clicked, this, &NodeViewToolBar::MiniMapEnabledToggled);
layout->addWidget(minimap_btn_);
layout->addStretch();
Retranslate();
UpdateIcons();
}
void NodeViewToolBar::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
Retranslate();
} else if (e->type() == QEvent::StyleChange) {
UpdateIcons();
}
super::changeEvent(e);
}
void NodeViewToolBar::Retranslate()
{
add_node_btn_->setToolTip(tr("Add Node"));
minimap_btn_->setToolTip(tr("Toggle Mini-Map"));
}
void NodeViewToolBar::UpdateIcons()
{
add_node_btn_->setIcon(icon::Add);
minimap_btn_->setIcon(icon::MiniMap);
}
}
| 1,201
|
C++
|
.cpp
| 42
| 26.095238
| 94
| 0.730366
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,864
|
nodeviewedge.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewedge.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeviewedge.h"
#include <QApplication>
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QStyleOptionGraphicsItem>
#include "common/lerp.h"
#include "nodeview.h"
#include "nodeviewitem.h"
#include "nodeviewscene.h"
namespace olive {
#define super QGraphicsPathItem
NodeViewEdge::NodeViewEdge(Node *output, const NodeInput &input,
NodeViewItem* from_item, NodeViewItem* to_item,
QGraphicsItem* parent) :
super(parent),
output_(output),
input_(input),
from_item_(from_item),
to_item_(to_item)
{
Init();
SetConnected(true);
from_item_->AddEdge(this);
to_item_->AddEdge(this);
}
NodeViewEdge::NodeViewEdge(QGraphicsItem *parent) :
QGraphicsPathItem(parent),
from_item_(nullptr),
to_item_(nullptr)
{
Init();
}
NodeViewEdge::~NodeViewEdge()
{
if (from_item_) {
from_item_->RemoveEdge(this);
}
if (to_item_) {
to_item_->RemoveEdge(this);
}
}
void NodeViewEdge::set_from_item(NodeViewItem *i)
{
if (from_item_) {
from_item_->RemoveEdge(this);
}
from_item_ = i;
if (from_item_) {
from_item_->AddEdge(this);
}
Adjust();
}
void NodeViewEdge::set_to_item(NodeViewItem *i)
{
if (to_item_) {
to_item_->RemoveEdge(this);
}
to_item_ = i;
if (to_item_) {
to_item_->AddEdge(this);
}
Adjust();
}
void NodeViewEdge::Adjust()
{
// Draw a line between the two
SetPoints(from_item()->GetOutputPoint(), to_item()->GetInputPoint());
}
void NodeViewEdge::SetConnected(bool c)
{
connected_ = c;
update();
}
void NodeViewEdge::SetHighlighted(bool e)
{
highlighted_ = e;
update();
}
void NodeViewEdge::SetPoints(const QPointF &start, const QPointF &end)
{
cached_start_ = start;
cached_end_ = end;
UpdateCurve();
}
void NodeViewEdge::SetCurved(bool e)
{
curved_ = e;
UpdateCurve();
}
void NodeViewEdge::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
QPalette::ColorGroup group;
QPalette::ColorRole role;
if (connected_) {
group = QPalette::Active;
} else {
group = QPalette::Disabled;
}
if (highlighted_ != bool(option->state & QStyle::State_Selected)) {
role = QPalette::Highlight;
} else {
role = QPalette::Text;
}
// Draw main path
QColor edge_color = qApp->palette().color(group, role);
painter->setPen(QPen(edge_color, edge_width_));
painter->setBrush(Qt::NoBrush);
painter->drawPath(path());
}
void NodeViewEdge::Init()
{
connected_ = false;
highlighted_ = false;
curved_ = true;
setFlag(QGraphicsItem::ItemIsSelectable);
// Ensures this UI object is drawn behind other objects
setZValue(-1);
// Use font metrics to set edge width for basic high DPI support
edge_width_ = QFontMetrics(QFont()).height() / 12;
}
void NodeViewEdge::UpdateCurve()
{
const QPointF &start = cached_start_;
const QPointF &end = cached_end_;
QPainterPath path;
path.moveTo(start);
double angle = std::atan2(end.y() - start.y(), end.x() - start.x());
if (curved_) {
double half_x = lerp(start.x(), end.x(), 0.5);
double half_y = lerp(start.y(), end.y(), 0.5);
QPointF cp1, cp2;
NodeViewCommon::FlowDirection from_flow = from_item_ ? from_item_->GetFlowDirection() : NodeViewCommon::kInvalidDirection;
NodeViewCommon::FlowDirection to_flow = to_item_ ? to_item_->GetFlowDirection() : NodeViewCommon::kInvalidDirection;
if (from_flow == NodeViewCommon::kInvalidDirection && to_flow == NodeViewCommon::kInvalidDirection) {
// This is a technically unsupported scenario, but to avoid issues, we'll use a fallback
from_flow = NodeViewCommon::kLeftToRight;
to_flow = NodeViewCommon::kLeftToRight;
} else if (from_flow == NodeViewCommon::kInvalidDirection) {
from_flow = to_flow;
} else if (to_flow == NodeViewCommon::kInvalidDirection) {
to_flow = from_flow;
}
if (NodeViewCommon::GetFlowOrientation(from_flow) == Qt::Horizontal) {
cp1 = QPointF(half_x, start.y());
} else {
cp1 = QPointF(start.x(), half_y);
}
if (NodeViewCommon::GetFlowOrientation(to_flow) == Qt::Horizontal) {
cp2 = QPointF(half_x, end.y());
} else {
cp2 = QPointF(end.x(), half_y);
}
path.cubicTo(cp1, cp2, end);
if (!qFuzzyCompare(start.x(), end.x())) {
double continue_x = end.x() - std::cos(angle);
double x1 = start.x();
double x2 = cp1.x();
double x3 = cp2.x();
double x4 = end.x();
double y1 = start.y();
double y2 = cp1.y();
double y3 = cp2.y();
double y4 = end.y();
if (start.x() >= end.x()) {
std::swap(x1, x4);
std::swap(x2, x3);
std::swap(y1, y4);
std::swap(y2, y3);
}
double t = Bezier::CubicXtoT(continue_x, x1, x2, x3, x4);
double y = Bezier::CubicTtoY(y1, y2, y3, y4, t);
angle = std::atan2(end.y() - y, end.x() - continue_x);
}
} else {
path.lineTo(end);
}
setPath(mapFromScene(path));
}
}
| 5,727
|
C++
|
.cpp
| 193
| 25.740933
| 126
| 0.671053
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,865
|
nodeviewscene.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewscene.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeviewscene.h"
#include "core.h"
#include "node/project/sequence/sequence.h"
#include "nodeviewedge.h"
#include "nodeviewitem.h"
namespace olive {
NodeViewScene::NodeViewScene(QObject *parent) :
QGraphicsScene(parent),
direction_(NodeViewCommon::kLeftToRight),
curved_edges_(true)
{
}
void NodeViewScene::SetFlowDirection(NodeViewCommon::FlowDirection direction)
{
direction_ = direction;
foreach (NodeViewContext *ctx, context_map_) {
ctx->SetFlowDirection(direction_);
}
}
void NodeViewScene::SelectAll()
{
foreach (QGraphicsItem* i, items()) {
i->setSelected(true);
}
}
void NodeViewScene::DeselectAll()
{
foreach (QGraphicsItem* i, items()) {
i->setSelected(false);
}
}
QVector<NodeViewItem *> NodeViewScene::GetSelectedItems() const
{
QVector<NodeViewItem *> items;
foreach (NodeViewContext *ctx, context_map_) {
items.append(ctx->GetSelectedItems());
}
return items;
}
NodeViewContext *NodeViewScene::AddContext(Node *node)
{
NodeViewContext *context_item = context_map_.value(node);
if (!context_item) {
context_item = new NodeViewContext(node);
context_item->SetFlowDirection(GetFlowDirection());
context_item->SetCurvedEdges(GetEdgesAreCurved());
QPointF pos(0, 0);
QRectF item_rect = context_item->rect();
while (!items(item_rect).isEmpty()) {
pos.setY(pos.y() + item_rect.height());
item_rect = context_item->rect().translated(pos);
}
context_item->setPos(pos);
addItem(context_item);
context_map_.insert(node, context_item);
}
return context_item;
}
void NodeViewScene::RemoveContext(Node *node)
{
delete context_map_.take(node);
}
Qt::Orientation NodeViewScene::GetFlowOrientation() const
{
return NodeViewCommon::GetFlowOrientation(direction_);
}
void NodeViewScene::SetEdgesAreCurved(bool curved)
{
if (curved_edges_ != curved) {
curved_edges_ = curved;
foreach (NodeViewContext *ctx, context_map_) {
ctx->SetCurvedEdges(curved_edges_);
}
}
}
}
| 2,736
|
C++
|
.cpp
| 90
| 27.377778
| 77
| 0.74217
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,866
|
nodeviewminimap.cpp
|
olive-editor_olive/app/widget/nodeview/nodeviewminimap.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodeviewminimap.h"
#include <QMouseEvent>
namespace olive {
#define super QGraphicsView
NodeViewMiniMap::NodeViewMiniMap(NodeViewScene *scene, QWidget *parent) :
super(parent),
resizing_(false)
{
connect(scene, &QGraphicsScene::sceneRectChanged, this, &NodeViewMiniMap::SceneChanged);
setScene(scene);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setViewportUpdateMode(FullViewportUpdate);
setFrameShape(QFrame::Panel);
setFrameShadow(QFrame::Plain);
setMouseTracking(true);
QMetaObject::invokeMethod(this, &NodeViewMiniMap::SetDefaultSize, Qt::QueuedConnection);
resize_triangle_sz_ = fontMetrics().height() / 2;
}
void NodeViewMiniMap::SetViewportRect(const QPolygonF &rect)
{
viewport_rect_ = rect;
viewport()->update();
}
void NodeViewMiniMap::drawForeground(QPainter *painter, const QRectF &rect)
{
super::drawForeground(painter, rect);
QColor viewport_color = palette().text().color();
// Draw resize triangle
painter->save();
painter->resetTransform();
QPointF triangle[3] = {QPointF(0, 0), QPointF(resize_triangle_sz_, 0), QPointF(0, resize_triangle_sz_)};
painter->setBrush(viewport_color);
painter->setPen(viewport_color);
painter->drawPolygon(triangle, 3);
painter->restore();
// Draw viewport rectangle
viewport_color.setAlphaF(0.25);
painter->setBrush(viewport_color);
painter->drawPolygon(viewport_rect_);
}
void NodeViewMiniMap::resizeEvent(QResizeEvent *event)
{
super::resizeEvent(event);
emit Resized();
SceneChanged(sceneRect());
}
void NodeViewMiniMap::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if (MouseInsideResizeTriangle(event)) {
// Resizing!
resizing_ = true;
resize_anchor_ = QCursor::pos();
} else {
EmitMoveSignal(event);
}
}
}
void NodeViewMiniMap::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
if (resizing_) {
QPointF movement = QCursor::pos() - resize_anchor_;
resize(QSize(width() - movement.x(), height() - movement.y()));
resize_anchor_ = QCursor::pos();
} else {
EmitMoveSignal(event);
}
} else {
if (MouseInsideResizeTriangle(event)) {
setCursor(Qt::SizeFDiagCursor);
} else {
unsetCursor();
}
}
}
void NodeViewMiniMap::mouseReleaseEvent(QMouseEvent *event)
{
resizing_ = false;
}
void NodeViewMiniMap::SceneChanged(const QRectF &bounding)
{
double x_scale = double(this->width()) / bounding.width();
double y_scale = double(this->height()) / bounding.height();
double min_scale = qMin(x_scale, y_scale);
QTransform transform;
transform.scale(min_scale, min_scale);
setTransform(transform);
}
void NodeViewMiniMap::SetDefaultSize()
{
if (parentWidget()) {
resize(parentWidget()->width()/4, parentWidget()->height()/4);
}
}
bool NodeViewMiniMap::MouseInsideResizeTriangle(QMouseEvent *event)
{
return event->pos().x() <= resize_triangle_sz_ && event->pos().y() <= resize_triangle_sz_;
}
void NodeViewMiniMap::EmitMoveSignal(QMouseEvent *event)
{
emit MoveToScenePoint(mapToScene(event->pos()));
}
}
| 3,912
|
C++
|
.cpp
| 119
| 29.739496
| 106
| 0.737823
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,867
|
nodetreeview.cpp
|
olive-editor_olive/app/widget/nodetreeview/nodetreeview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodetreeview.h"
#include <QEvent>
namespace olive {
NodeTreeView::NodeTreeView(QWidget *parent) :
QTreeWidget(parent),
only_show_keyframable_(false),
show_keyframe_tracks_as_rows_(false),
checkboxes_enabled_(false)
{
connect(this, &NodeTreeView::itemChanged, this, &NodeTreeView::ItemCheckStateChanged);
connect(this, &NodeTreeView::itemSelectionChanged, this, &NodeTreeView::SelectionChanged);
Retranslate();
}
bool NodeTreeView::IsNodeEnabled(Node *n) const
{
return !disabled_nodes_.contains(n);
}
bool NodeTreeView::IsInputEnabled(const NodeKeyframeTrackReference &ref) const
{
return !disabled_inputs_.contains(ref);
}
void NodeTreeView::SetKeyframeTrackColor(const NodeKeyframeTrackReference &ref, const QColor &color)
{
// Insert into hashmap
keyframe_colors_.insert(ref, color);
// If we currently have an item for this, set it
QTreeWidgetItem* item = item_map_.value(ref);
if (item) {
item->setForeground(0, color);
}
}
void NodeTreeView::SetNodes(const QVector<Node *> &nodes)
{
nodes_ = nodes;
this->clear();
item_map_.clear();
foreach (Node* n, nodes_) {
QTreeWidgetItem* node_item = new QTreeWidgetItem();
node_item->setText(0, n->Name());
if (checkboxes_enabled_) {
node_item->setCheckState(0, disabled_nodes_.contains(n) ? Qt::Unchecked : Qt::Checked);
}
node_item->setData(0, kItemType, kItemTypeNode);
node_item->setData(0, kItemNodePointer, QtUtils::PtrToValue(n));
foreach (const QString& input, n->inputs()) {
if (n->IsInputHidden(input) || (only_show_keyframable_ && !n->IsInputKeyframable(input))) {
continue;
}
QTreeWidgetItem* input_item = nullptr;
int arr_sz = n->InputArraySize(input);
for (int i=-1; i<arr_sz; i++) {
NodeInput input_ref(n, input, i);
const QVector<NodeKeyframeTrack>& key_tracks = n->GetKeyframeTracks(input_ref);
int this_element_track;
if (show_keyframe_tracks_as_rows_
&& (key_tracks.size() == 1 || (i == -1 && n->InputIsArray(input)))) {
this_element_track = 0;
} else {
this_element_track = -1;
}
QTreeWidgetItem* element_item;
if (input_item) {
element_item = CreateItem(input_item, NodeKeyframeTrackReference(input_ref, this_element_track));
} else {
input_item = CreateItem(node_item, NodeKeyframeTrackReference(input_ref, this_element_track));
element_item = input_item;
}
if (show_keyframe_tracks_as_rows_ && key_tracks.size() > 1 && (!n->InputIsArray(input) || i >= 0)) {
CreateItemsForTracks(element_item, input_ref, key_tracks.size());
}
}
}
// Add at the end to prevent unnecessary signalling while we're setting these objects up
if (node_item->childCount() > 0) {
this->addTopLevelItem(node_item);
} else {
delete node_item;
}
}
expandAll();
}
void NodeTreeView::changeEvent(QEvent *e)
{
QTreeWidget::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
Retranslate();
}
}
void NodeTreeView::mouseDoubleClickEvent(QMouseEvent *e)
{
QTreeWidget::mouseDoubleClickEvent(e);
NodeKeyframeTrackReference ref = GetSelectedInput();
if (ref.input().IsValid()) {
emit InputDoubleClicked(ref);
}
}
void NodeTreeView::Retranslate()
{
setHeaderLabel(tr("Nodes"));
}
NodeKeyframeTrackReference NodeTreeView::GetSelectedInput()
{
QList<QTreeWidgetItem*> sel = selectedItems();
NodeKeyframeTrackReference selected_ref;
if (!sel.isEmpty()) {
QTreeWidgetItem* item = sel.first();
if (item->data(0, kItemType).toInt() == kItemTypeInput) {
selected_ref = item->data(0, kItemInputReference).value<NodeKeyframeTrackReference>();
} else {
selected_ref = NodeKeyframeTrackReference(NodeInput(QtUtils::ValueToPtr<Node>(item->data(0, kItemNodePointer)), QString()));
}
}
return selected_ref;
}
QTreeWidgetItem* NodeTreeView::CreateItem(QTreeWidgetItem *parent, const NodeKeyframeTrackReference& ref)
{
QTreeWidgetItem* input_item = new QTreeWidgetItem(parent);
QString item_name;
if (ref.track() == -1
|| NodeValue::get_number_of_keyframe_tracks(ref.input().GetDataType()) == 1
|| (ref.input().IsArray() && ref.input().element() == -1)) {
if (ref.input().element() == -1) {
item_name = ref.input().name();
} else {
item_name = QString::number(ref.input().element());
}
} else {
switch (ref.track()) {
case 0:
item_name = UseRGBAOverXYZW(ref) ? tr("R") : tr("X");
break;
case 1:
item_name = UseRGBAOverXYZW(ref) ? tr("G") : tr("Y");
break;
case 2:
item_name = UseRGBAOverXYZW(ref) ? tr("B") : tr("Z");
break;
case 3:
item_name = UseRGBAOverXYZW(ref) ? tr("A") : tr("W");
break;
default:
item_name = QString::number(ref.track());
}
}
input_item->setText(0, item_name);
if (checkboxes_enabled_) {
input_item->setCheckState(0, disabled_inputs_.contains(ref) ? Qt::Unchecked : Qt::Checked);
}
input_item->setData(0, kItemType, kItemTypeInput);
input_item->setData(0, kItemInputReference, QVariant::fromValue(ref));
if (keyframe_colors_.contains(ref)) {
input_item->setForeground(0, keyframe_colors_.value(ref));
}
item_map_.insert(ref, input_item);
return input_item;
}
void NodeTreeView::CreateItemsForTracks(QTreeWidgetItem *parent, const NodeInput& input, int track_count)
{
for (int j=0; j<track_count; j++) {
CreateItem(parent, NodeKeyframeTrackReference(input, j));
}
}
bool NodeTreeView::UseRGBAOverXYZW(const NodeKeyframeTrackReference &ref)
{
return ref.input().GetDataType() == NodeValue::kColor;
}
void NodeTreeView::ItemCheckStateChanged(QTreeWidgetItem *item, int column)
{
Q_UNUSED(column)
switch (item->data(0, kItemType).toInt()) {
case kItemTypeNode:
{
Node* n = QtUtils::ValueToPtr<Node>(item->data(0, kItemNodePointer));
if (item->checkState(0) == Qt::Checked) {
if (disabled_nodes_.contains(n)) {
disabled_nodes_.removeOne(n);
emit NodeEnableChanged(n, true);
}
} else if (!disabled_nodes_.contains(n)) {
disabled_nodes_.append(n);
emit NodeEnableChanged(n, false);
}
break;
}
case kItemTypeInput:
{
NodeKeyframeTrackReference i = item->data(0, kItemInputReference).value<NodeKeyframeTrackReference>();
if (item->checkState(0) == Qt::Checked) {
if (disabled_inputs_.contains(i)) {
disabled_inputs_.removeOne(i);
emit InputEnableChanged(i, true);
}
} else if (!disabled_inputs_.contains(i)) {
disabled_inputs_.append(i);
emit InputEnableChanged(i, false);
}
break;
}
}
}
void NodeTreeView::SelectionChanged()
{
emit InputSelectionChanged(GetSelectedInput());
}
}
| 7,574
|
C++
|
.cpp
| 219
| 30.086758
| 130
| 0.685198
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,868
|
rationalslider.cpp
|
olive-editor_olive/app/widget/slider/rationalslider.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "rationalslider.h"
#include "core.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
namespace olive {
#define super DecimalSliderBase
RationalSlider::RationalSlider(QWidget *parent) :
super(parent),
lock_display_type_(false)
{
connect(Core::instance(), &Core::TimecodeDisplayChanged, this, &RationalSlider::UpdateLabel);
connect(SliderBase::label(), &SliderLabel::customContextMenuRequested, this, &RationalSlider::ShowDisplayTypeMenu);
SetDisplayType(kFloat);
SetValue(rational(0, 0));
}
rational RationalSlider::GetValue()
{
return GetValueInternal().value<rational>();
}
void RationalSlider::SetValue(const rational &d)
{
SetValueInternal(QVariant::fromValue(d));
}
void RationalSlider::SetDefaultValue(const rational &r)
{
super::SetDefaultValue(QVariant::fromValue(r));
}
void RationalSlider::SetMinimum(const rational &d)
{
SetMinimumInternal(QVariant::fromValue(d));
}
void RationalSlider::SetMaximum(const rational &d)
{
SetMaximumInternal(QVariant::fromValue(d));
}
void RationalSlider::SetTimebase(const rational &timebase)
{
timebase_ = timebase;
// Refresh label since we have a new timebase to generate a timecode with
UpdateLabel();
}
void RationalSlider::SetDisplayType(const RationalSlider::DisplayType &type)
{
display_type_ = type;
UpdateLabel();
}
void RationalSlider::SetLockDisplayType(bool e)
{
lock_display_type_ = e;
}
bool RationalSlider::GetLockDisplayType()
{
return lock_display_type_;
}
void RationalSlider::DisableDisplayType(RationalSlider::DisplayType type)
{
disabled_.append(type);
}
QString RationalSlider::ValueToString(const QVariant &v) const
{
rational r = v.value<rational>();
if (r.isNaN()) {
return tr("NaN");
} else {
double val = r.toDouble() + GetOffset().value<rational>().toDouble();
switch (display_type_) {
case kTime:
return QString::fromStdString(Timecode::time_to_timecode(r, timebase_, Core::instance()->GetTimecodeDisplay()));
case kFloat:
return FloatToString(val, GetDecimalPlaces(), GetAutoTrimDecimalPlaces());
case kRational:
return QString::fromStdString(v.value<rational>().toString());
}
return v.toString();
}
}
QVariant RationalSlider::StringToValue(const QString &s, bool *ok) const
{
rational r;
*ok = false;
switch (display_type_) {
case kTime:
{
r = Timecode::timecode_to_time(s.toStdString(), timebase_, Core::instance()->GetTimecodeDisplay(), ok);
break;
}
case kFloat:
{
// First, convert to a double
double d = s.toDouble(ok);
if (!(*ok)) {
break;
}
// If double conversion succeeded, convert to a rational
r = rational::fromDouble(d, ok);
break;
}
case kRational:
r = rational::fromString(s.toStdString(), ok);
break;
}
//return QVariant::fromValue(r - GetOffset().value<rational>());
return QVariant::fromValue(r);
}
QVariant RationalSlider::AdjustDragDistanceInternal(const QVariant &start, const double &drag) const
{
// Assume we want smallest increment to be timebase or 1 frame
return QVariant::fromValue(start.value<rational>() + rational::fromDouble(drag)*timebase_);
}
void RationalSlider::ValueSignalEvent(const QVariant &v)
{
emit ValueChanged(v.value<rational>());
}
bool RationalSlider::ValueGreaterThan(const QVariant &lhs, const QVariant &rhs) const
{
return lhs.value<rational>() > rhs.value<rational>();
}
bool RationalSlider::ValueLessThan(const QVariant &lhs, const QVariant &rhs) const
{
return lhs.value<rational>() < rhs.value<rational>();
}
void RationalSlider::ShowDisplayTypeMenu()
{
Menu m(this);
if (!GetLockDisplayType()) {
if (!disabled_.contains(kFloat)) {
QAction* float_action = m.addAction(tr("Float"));
float_action->setData(kFloat);
connect(float_action, &QAction::triggered, this, &RationalSlider::SetDisplayTypeFromMenu);
}
if (!disabled_.contains(kRational)) {
QAction* rational_action = m.addAction(tr("Rational"));
rational_action->setData(kRational);
connect(rational_action, &QAction::triggered, this, &RationalSlider::SetDisplayTypeFromMenu);
}
if (!disabled_.contains(kTime)) {
QAction* time_action = m.addAction(tr("Time"));
time_action->setData(kTime);
connect(time_action, &QAction::triggered, this, &RationalSlider::SetDisplayTypeFromMenu);
}
}
if (display_type_ == kTime) {
if (!m.actions().isEmpty()) {
m.addSeparator();
}
MenuShared::instance()->AddItemsForTimeRulerMenu(&m);
MenuShared::instance()->AboutToShowTimeRulerActions(timebase_);
}
if (!m.actions().isEmpty()) {
m.exec(QCursor::pos());
UpdateLabel();
}
}
void RationalSlider::SetDisplayTypeFromMenu()
{
QAction* action = static_cast<QAction*>(sender());
DisplayType type = static_cast<DisplayType>(action->data().toInt());
SetDisplayType(type);
}
}
| 5,623
|
C++
|
.cpp
| 174
| 29.132184
| 118
| 0.733666
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,869
|
stringslider.cpp
|
olive-editor_olive/app/widget/slider/stringslider.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "stringslider.h"
namespace olive {
#define super SliderBase
StringSlider::StringSlider(QWidget* parent) :
super(parent)
{
SetValue(QString());
connect(label(), &SliderLabel::LabelReleased, this, &SliderBase::ShowEditor);
}
QString StringSlider::GetValue() const
{
return GetValueInternal().toString();
}
void StringSlider::SetValue(const QString &v)
{
SetValueInternal(v);
}
void StringSlider::SetDefaultValue(const QString &v)
{
super::SetDefaultValue(v);
}
QString StringSlider::ValueToString(const QVariant &v) const
{
QString vstr = v.toString();
return (vstr.isEmpty()) ? tr("(none)") : vstr;
}
QVariant StringSlider::StringToValue(const QString &s, bool *ok) const
{
*ok = true;
return s;
}
void StringSlider::ValueSignalEvent(const QVariant &value)
{
emit ValueChanged(value.toString());
}
}
| 1,553
|
C++
|
.cpp
| 50
| 28.8
| 79
| 0.76716
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,870
|
floatslider.cpp
|
olive-editor_olive/app/widget/slider/floatslider.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "floatslider.h"
#include <cmath>
#include <QDebug>
#include "common/decibel.h"
namespace olive {
#define super DecimalSliderBase
FloatSlider::FloatSlider(QWidget *parent) :
super(parent),
display_type_(kNormal)
{
SetValue(0.0);
}
double FloatSlider::GetValue() const
{
return GetValueInternal().toDouble();
}
void FloatSlider::SetValue(const double &d)
{
SetValueInternal(d);
}
void FloatSlider::SetDefaultValue(const double &d)
{
super::SetDefaultValue(d);
}
void FloatSlider::SetMinimum(const double &d)
{
SetMinimumInternal(d);
}
void FloatSlider::SetMaximum(const double &d)
{
SetMaximumInternal(d);
}
void FloatSlider::SetDisplayType(const FloatSlider::DisplayType &type)
{
display_type_ = type;
switch (display_type_) {
case kNormal:
ClearFormat();
break;
case kDecibel:
SetFormat(tr("%1 dB"));
break;
case kPercentage:
SetFormat(tr("%1%"));
break;
}
}
double FloatSlider::TransformValueToDisplay(double val, DisplayType display)
{
switch (display) {
case kNormal:
break;
case kDecibel:
val = Decibel::fromLinear(val);
break;
case kPercentage:
val *= 100.0;
break;
}
return val;
}
double FloatSlider::TransformDisplayToValue(double val, DisplayType display)
{
switch (display) {
case kNormal:
break;
case kDecibel:
val = Decibel::toLinear(val);
break;
case kPercentage:
val *= 0.01;
break;
}
return val;
}
QString FloatSlider::ValueToString(double val, FloatSlider::DisplayType display, int decimal_places, bool autotrim_decimal_places)
{
// Return negative infinity for zero volume
if (display == kDecibel && qIsNull(val)) {
return tr("\xE2\x88\x9E");
}
return FloatToString(TransformValueToDisplay(val, display), decimal_places, autotrim_decimal_places);
}
QString FloatSlider::ValueToString(const QVariant &v) const
{
return ValueToString(v.toDouble() + GetOffset().toDouble(), display_type_, GetDecimalPlaces(), GetAutoTrimDecimalPlaces());
}
QVariant FloatSlider::StringToValue(const QString &s, bool *ok) const
{
bool valid;
double val = s.toDouble(&valid);
// If we were given an `ok` pointer, set it to `valid`
if (ok) {
*ok = valid;
}
// If valid, transform it from display
if (valid) {
val = TransformDisplayToValue(val, display_type_);
}
// Return un-offset value
return val - GetOffset().toDouble();
}
QVariant FloatSlider::AdjustDragDistanceInternal(const QVariant &start, const double &drag) const
{
switch (display_type_) {
case kNormal:
// No change here
break;
case kDecibel:
{
double current_db = Decibel::fromLinear(start.toDouble());
current_db += drag;
double adjusted_linear = Decibel::toLinear(current_db);
return adjusted_linear;
}
case kPercentage:
return super::AdjustDragDistanceInternal(start, drag * 0.01);
}
return super::AdjustDragDistanceInternal(start, drag);
}
void FloatSlider::ValueSignalEvent(const QVariant &value)
{
emit ValueChanged(value.toDouble());
}
}
| 3,755
|
C++
|
.cpp
| 139
| 24.129496
| 130
| 0.740369
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,871
|
integerslider.cpp
|
olive-editor_olive/app/widget/slider/integerslider.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "integerslider.h"
namespace olive {
#define super NumericSliderBase
IntegerSlider::IntegerSlider(QWidget* parent) :
super(parent)
{
SetValue(0);
}
int64_t IntegerSlider::GetValue()
{
return GetValueInternal().toLongLong();
}
void IntegerSlider::SetValue(const int64_t &v)
{
SetValueInternal(QVariant::fromValue(v));
}
void IntegerSlider::SetMinimum(const int64_t &d)
{
SetMinimumInternal(QVariant::fromValue(d));
}
void IntegerSlider::SetMaximum(const int64_t &d)
{
SetMaximumInternal(QVariant::fromValue(d));
}
void IntegerSlider::SetDefaultValue(const int64_t &d)
{
super::SetDefaultValue(QVariant::fromValue(d));
}
QString IntegerSlider::ValueToString(const QVariant &v) const
{
return QString::number(v.toLongLong() + GetOffset().toLongLong());
}
QVariant IntegerSlider::StringToValue(const QString &s, bool *ok) const
{
bool valid;
// Allow both floats and integers for either modes
double decimal_val = s.toDouble(&valid);
if (ok) {
*ok = valid;
}
decimal_val -= GetOffset().toLongLong();
if (valid) {
// But for an integer, we round it
return qRound(decimal_val);
}
return QVariant();
}
void IntegerSlider::ValueSignalEvent(const QVariant &value)
{
emit ValueChanged(value.toInt());
}
QVariant IntegerSlider::AdjustDragDistanceInternal(const QVariant &start, const double &drag) const
{
return qRound64(super::AdjustDragDistanceInternal(start, drag).toDouble());
}
}
| 2,163
|
C++
|
.cpp
| 70
| 28.5
| 99
| 0.767037
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,872
|
sliderladder.cpp
|
olive-editor_olive/app/widget/slider/base/sliderladder.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "sliderladder.h"
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QScreen>
#include <QtMath>
#include <QVBoxLayout>
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "common/lerp.h"
#include "common/qtutils.h"
#include "config/config.h"
namespace olive {
SliderLadder::SliderLadder(double drag_multiplier, int nb_outer_values, QString width_hint, QWidget* parent) :
QFrame(parent, Qt::Popup)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
setFrameShape(QFrame::Box);
setLineWidth(1);
if (!OLIVE_CONFIG("UseSliderLadders").toBool()) {
nb_outer_values = 0;
}
for (int i=nb_outer_values-1;i>=0;i--) {
elements_.append(new SliderLadderElement(qPow(10, i + 1) * drag_multiplier, width_hint));
}
// Create center entry
SliderLadderElement* start_element = new SliderLadderElement(drag_multiplier, width_hint);
active_element_ = elements_.size();
start_element->SetHighlighted(true);
elements_.append(start_element);
for (int i=0;i<nb_outer_values;i++) {
elements_.append(new SliderLadderElement(qPow(10, -i - 1) * drag_multiplier, width_hint));
}
foreach (SliderLadderElement* e, elements_) {
layout->addWidget(e);
}
if (elements_.size() == 1) {
elements_.first()->SetMultiplierVisible(false);
}
drag_timer_.setInterval(10);
connect(&drag_timer_, &QTimer::timeout, this, &SliderLadder::TimerUpdate);
screen_ = nullptr;
foreach (QScreen *screen, qApp->screens()) {
if (screen->geometry().contains(QCursor::pos())) {
screen_ = screen;
break;
}
}
if (UsingLadders()) {
drag_start_x_ = -1;
wrap_count_ = 0;
} else {
#if defined(Q_OS_MAC)
CGAssociateMouseAndMouseCursorPosition(false);
CGDisplayHideCursor(kCGDirectMainDisplay);
CGGetLastMouseDelta(nullptr, nullptr);
#else
drag_start_x_ = QCursor::pos().x();
drag_start_y_ = QCursor::pos().y();
static_cast<QGuiApplication*>(QApplication::instance())->setOverrideCursor(Qt::BlankCursor);
#endif
}
}
SliderLadder::~SliderLadder()
{
if (UsingLadders()) {
if (wrap_count_ != 0) {
// If wrapped, restore cursor to ladder
QCursor::setPos(pos() + rect().center());
}
} else {
#if defined(Q_OS_MAC)
CGAssociateMouseAndMouseCursorPosition(true);
CGDisplayShowCursor(kCGDirectMainDisplay);
#else
static_cast<QGuiApplication*>(QApplication::instance())->restoreOverrideCursor();
#endif
}
}
void SliderLadder::SetValue(const QString &s)
{
foreach (SliderLadderElement* e, elements_) {
e->SetValue(s);
}
}
void SliderLadder::StartListeningToMouseInput()
{
QMetaObject::invokeMethod(&drag_timer_, "start", Qt::QueuedConnection);
}
void SliderLadder::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event)
this->close();
}
void SliderLadder::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event)
drag_timer_.stop();
emit Released();
QFrame::closeEvent(event);
}
void SliderLadder::TimerUpdate()
{
int ladder_left = this->x();
int ladder_right = this->x() + this->width() - 1;
int now_pos = QCursor::pos().x();
if (UsingLadders()) {
bool is_under_mouse = (now_pos >= ladder_left && now_pos <= ladder_right && wrap_count_ == 0);
if (drag_start_x_ != -1 && (is_under_mouse
|| (drag_start_x_ < ladder_left && now_pos > ladder_right)
|| (drag_start_x_ > ladder_right && now_pos < ladder_left))) {
// We're ending a drag, try to return the value back to its beginning
int anchor;
if (drag_start_x_ < ladder_left) {
anchor = ladder_left;
} else {
anchor = ladder_right;
}
int makeup_value = anchor - drag_start_x_;
emit DraggedByValue(makeup_value, elements_.at(active_element_)->GetMultiplier());
drag_start_x_ = -1;
}
if (is_under_mouse) {
// Determine which element is currently active
for (int i=0; i<elements_.size(); i++) {
if (elements_.at(i)->underMouse()) {
if (i != active_element_) {
elements_.at(active_element_)->SetHighlighted(false);
active_element_ = i;
elements_.at(active_element_)->SetHighlighted(true);
}
break;
}
}
} else {
if (drag_start_x_ == -1) {
// Drag is a new leave from the ladder, calculate origin
if (now_pos < ladder_left) {
drag_start_x_ = ladder_left;
} else {
drag_start_x_ = ladder_right;
}
}
emit DraggedByValue(now_pos - drag_start_x_, elements_.at(active_element_)->GetMultiplier());
// Determine if cursor is at desktop edge, if so wrap around to other side
if (screen_) {
int left = screen_->geometry().left();
int right = screen_->geometry().right();
int width = right - left;
if (now_pos <= left || now_pos >= right) {
int orig_now_pos = now_pos;
int orig_wrap = wrap_count_;
if (now_pos <= left) {
wrap_count_--;
now_pos += width;
} else {
wrap_count_++;
now_pos -= width;
}
QPoint p(now_pos, QCursor::pos().y());
QCursor::setPos(p);
if (QCursor::pos() != p) {
wrap_count_ = orig_wrap;
now_pos = orig_now_pos;
}
}
}
drag_start_x_ = now_pos;
}
} else {
int32_t x_mvmt, y_mvmt;
// Keep cursor in the same position
#if defined(Q_OS_MAC)
CGGetLastMouseDelta(&x_mvmt, &y_mvmt);
#else
QPoint current_pos = QCursor::pos();
x_mvmt = current_pos.x() - drag_start_x_;
y_mvmt = current_pos.y() - drag_start_y_;
QCursor::setPos(QPoint(drag_start_x_, drag_start_y_));
#endif
if (x_mvmt || y_mvmt) {
double multiplier = 1.0;
if (qApp->keyboardModifiers() & Qt::ControlModifier) {
multiplier *= 0.01;
}
if (qApp->keyboardModifiers() & Qt::ShiftModifier) {
multiplier *= 100.0;
}
emit DraggedByValue(x_mvmt + y_mvmt, multiplier);
}
}
}
bool SliderLadder::UsingLadders() const
{
return elements_.size() > 1;
}
SliderLadderElement::SliderLadderElement(const double &multiplier, QString width_hint, QWidget *parent) :
QWidget(parent),
multiplier_(multiplier),
highlighted_(false),
multiplier_visible_(true)
{
QVBoxLayout* layout = new QVBoxLayout(this);
label_ = new QLabel();
label_->setAlignment(Qt::AlignCenter);
label_->setFixedWidth(QtUtils::QFontMetricsWidth(label_->fontMetrics(), width_hint));
layout->addWidget(label_);
QPalette p = palette();
QColor highlight_color = palette().text().color();
highlight_color.setAlpha(64);
p.setColor(QPalette::Highlight, highlight_color);
setPalette(p);
setAutoFillBackground(true);
UpdateLabel();
}
void SliderLadderElement::SetHighlighted(bool e)
{
highlighted_ = e;
if (highlighted_) {
setBackgroundRole(QPalette::Highlight);
} else {
setBackgroundRole(QPalette::Window);
}
UpdateLabel();
}
void SliderLadderElement::SetValue(const QString &value)
{
value_ = value;
UpdateLabel();
}
void SliderLadderElement::SetMultiplierVisible(bool e)
{
multiplier_visible_ = e;
UpdateLabel();
}
void SliderLadderElement::UpdateLabel()
{
if (multiplier_visible_) {
QString val_text;
if (highlighted_) {
val_text = value_;
}
label_->setText(QStringLiteral("%1\n%2").arg(QString::number(multiplier_),
val_text));
} else {
label_->setText(value_);
}
}
}
| 8,368
|
C++
|
.cpp
| 266
| 26.590226
| 110
| 0.655207
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,873
|
numericsliderbase.cpp
|
olive-editor_olive/app/widget/slider/base/numericsliderbase.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "numericsliderbase.h"
#include "common/qtutils.h"
#include "config/config.h"
#include "core.h"
namespace olive {
bool NumericSliderBase::effects_slider_is_being_dragged_ = false;
NumericSliderBase::NumericSliderBase(QWidget *parent) :
SliderBase(parent),
drag_ladder_(nullptr),
ladder_element_count_(0),
dragged_(false),
has_min_(false),
has_max_(false),
dragged_diff_(0),
drag_multiplier_(1.0),
setting_drag_value_(false)
{
// Numeric sliders are draggable, so we have a cursor that indicates that
setCursor(Qt::SizeHorCursor);
connect(label(), &SliderLabel::LabelPressed, this, &NumericSliderBase::LabelPressed);
}
void NumericSliderBase::SetDragMultiplier(const double &d)
{
drag_multiplier_ = d;
}
void NumericSliderBase::LabelPressed()
{
drag_ladder_ = new SliderLadder(drag_multiplier_, ladder_element_count_, GetFormattedValueToString(99999999));
connect(drag_ladder_, &SliderLadder::DraggedByValue, this, &NumericSliderBase::LadderDragged);
connect(drag_ladder_, &SliderLadder::Released, this, &NumericSliderBase::LadderReleased);
drag_ladder_->SetValue(GetFormattedValueToString());
drag_ladder_->resize(drag_ladder_->sizeHint());
RepositionLadder();
drag_ladder_->show();
drag_start_value_ = GetValueInternal();
}
void NumericSliderBase::LadderDragged(int value, double multiplier)
{
dragged_ = true;
dragged_diff_ += value * multiplier;
// Store current value to try and prevent any unnecessary signalling if the value doesn't change
QVariant pre_set_value = GetValueInternal();
setting_drag_value_ = true;
SetValueInternal(AdjustDragDistanceInternal(drag_start_value_, dragged_diff_));
setting_drag_value_ = false;
if (GetValueInternal() != pre_set_value) {
// We retrieve the value instead of storing it ourselves because SetValueInternal may do extra
// processing (such as clamping).
drag_ladder_->SetValue(GetFormattedValueToString());
if (!UsingLadders()) {
RepositionLadder();
}
ValueSignalEvent(GetValueInternal());
}
}
void NumericSliderBase::LadderReleased()
{
drag_ladder_->deleteLater();
drag_ladder_ = nullptr;
dragged_diff_ = 0;
if (dragged_) {
// This was a drag, send another value changed event
ValueSignalEvent(GetValueInternal());
dragged_ = false;
} else {
ShowEditor();
}
}
void NumericSliderBase::RepositionLadder()
{
if (drag_ladder_) {
if (UsingLadders()) {
drag_ladder_->move(QCursor::pos() - QPoint(drag_ladder_->width()/2, drag_ladder_->height()/2));
} else {
QPoint label_global_pos = label()->mapToGlobal(label()->pos());
int text_width = QtUtils::QFontMetricsWidth(label()->fontMetrics(), label()->text());
if (label()->alignment() & Qt::AlignRight) {
label_global_pos.setX(label_global_pos.x() + label()->width() - text_width);
} else if (label()->alignment() & Qt::AlignHCenter) {
label_global_pos.setX(label_global_pos.x() + label()->width()/2 - text_width/2);
}
int ladder_x = label_global_pos.x() + text_width / 2 - drag_ladder_->width() / 2;
int ladder_y = label_global_pos.y() + label()->height() / 2 - drag_ladder_->height() / 2;
drag_ladder_->move(ladder_x, ladder_y);
}
drag_ladder_->StartListeningToMouseInput();
}
}
bool NumericSliderBase::IsDragging() const
{
return drag_ladder_;
}
bool NumericSliderBase::UsingLadders() const
{
return ladder_element_count_ > 0 && OLIVE_CONFIG("UseSliderLadders").toBool();
}
QVariant NumericSliderBase::AdjustValue(const QVariant &value) const
{
// Clamps between min/max
if (has_min_ && ValueLessThan(value, min_value_)) {
return min_value_;
} else if (has_max_ && ValueGreaterThan(value, max_value_)) {
return max_value_;
}
return value;
}
void NumericSliderBase::SetOffset(const QVariant &v)
{
offset_ = v;
UpdateLabel();
}
QVariant NumericSliderBase::AdjustDragDistanceInternal(const QVariant &start, const double &drag) const
{
return start.toDouble() + drag;
}
void NumericSliderBase::SetMinimumInternal(const QVariant &v)
{
min_value_ = v;
has_min_ = true;
// Limit value by this new minimum value
if (ValueLessThan(GetValueInternal(), min_value_)) {
SetValueInternal(min_value_);
}
}
void NumericSliderBase::SetMaximumInternal(const QVariant &v)
{
max_value_ = v;
has_max_ = true;
// Limit value by this new maximum value
if (ValueGreaterThan(GetValueInternal(), max_value_)) {
SetValueInternal(max_value_);
}
}
bool NumericSliderBase::ValueGreaterThan(const QVariant &lhs, const QVariant &rhs) const
{
return lhs.toDouble() > rhs.toDouble();
}
bool NumericSliderBase::ValueLessThan(const QVariant &lhs, const QVariant &rhs) const
{
return lhs.toDouble() < rhs.toDouble();
}
bool NumericSliderBase::CanSetValue() const
{
return !IsDragging() || setting_drag_value_;
}
}
| 5,598
|
C++
|
.cpp
| 160
| 31.86875
| 112
| 0.726868
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,874
|
sliderlabel.cpp
|
olive-editor_olive/app/widget/slider/base/sliderlabel.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "sliderlabel.h"
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>
namespace olive {
SliderLabel::SliderLabel(QWidget *parent) :
QLabel(parent),
override_color_enabled_(false)
{
QPalette p = palette();
p.setColor(QPalette::Disabled,
QPalette::Highlight,
p.color(QPalette::Disabled, QPalette::ButtonText));
setPalette(p);
// Use highlight color as font color
setForegroundRole(QPalette::Link);
// Set underlined
QFont f = font();
f.setUnderline(true);
setFont(f);
// Allow users to tab to this widget
setFocusPolicy(Qt::TabFocus);
// Add custom context menu
setContextMenuPolicy(Qt::CustomContextMenu);
}
void SliderLabel::SetColor(const QColor &c)
{
// Prevent infinite loop in changeEvent when we set the stylesheet
override_color_enabled_ = false;
override_color_ = c;
// Different colors will look different depending on the theme (light/dark mode). We abstract
// that away here so that other classes can simply choose a color and we will handle making it
// more legible based on the background
QColor adjusted;
if (palette().window().color().lightness() < 128) {
adjusted = override_color_.lighter(150);
} else {
adjusted = override_color_.darker(150);
}
setStyleSheet(QStringLiteral("color: %1").arg(adjusted.name()));
override_color_enabled_ = true;
}
void SliderLabel::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
if (e->modifiers() & Qt::AltModifier) {
emit RequestReset();
} else {
emit LabelPressed();
}
}
}
void SliderLabel::mouseReleaseEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
if (!(e->modifiers() & Qt::AltModifier)) {
emit LabelReleased();
}
}
}
void SliderLabel::focusInEvent(QFocusEvent *event)
{
QWidget::focusInEvent(event);
if (event->reason() == Qt::TabFocusReason) {
emit focused();
}
}
void SliderLabel::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (override_color_enabled_ && event->type() == QEvent::StyleChange) {
SetColor(override_color_);
}
}
}
| 2,844
|
C++
|
.cpp
| 89
| 28.674157
| 96
| 0.721612
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,875
|
sliderbase.cpp
|
olive-editor_olive/app/widget/slider/base/sliderbase.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "sliderbase.h"
#include <QDebug>
#include <QEvent>
#include <QMessageBox>
#include "common/qtutils.h"
#include "core.h"
#include "window/mainwindow/mainwindow.h"
namespace olive {
#define super QStackedWidget
SliderBase::SliderBase(QWidget *parent) :
super(parent),
tristate_(false),
format_plural_(false)
{
// Standard (non-numeric) sliders are not draggable, so we indicate as such
setCursor(Qt::PointingHandCursor);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
label_ = new SliderLabel(this);
addWidget(label_);
editor_ = new FocusableLineEdit(this);
addWidget(editor_);
connect(label_, &SliderLabel::focused, this, &SliderBase::ShowEditor);
connect(label_, &SliderLabel::RequestReset, this, &SliderBase::ResetValue);
connect(editor_, &FocusableLineEdit::Confirmed, this, &SliderBase::LineEditConfirmed);
connect(editor_, &FocusableLineEdit::Cancelled, this, &SliderBase::LineEditCancelled);
}
void SliderBase::SetAlignment(Qt::Alignment alignment)
{
label_->setAlignment(alignment);
editor_->setAlignment(alignment);
}
bool SliderBase::IsTristate() const
{
return tristate_;
}
void SliderBase::SetTristate()
{
tristate_ = true;
UpdateLabel();
}
const QVariant &SliderBase::GetValueInternal() const
{
return value_;
}
void SliderBase::SetValueInternal(const QVariant &v)
{
if (!CanSetValue()) {
return;
}
value_ = AdjustValue(v);
// Disable tristate
tristate_ = false;
UpdateLabel();
}
void SliderBase::SetDefaultValue(const QVariant &v)
{
default_value_ = v;
}
void SliderBase::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
UpdateLabel();
}
super::changeEvent(e);
}
bool SliderBase::GetLabelSubstitution(const QVariant &v, QString *out) const
{
for (auto it=label_substitutions_.constBegin(); it!=label_substitutions_.constEnd(); it++) {
if (it->first == v) {
*out = it->second;
return true;
}
}
return false;
}
void SliderBase::UpdateLabel()
{
QString s;
if (tristate_) {
s = tr("---");
} else if (GetLabelSubstitution(GetValueInternal(), &s)) {
// String will already be set, just pass through
} else {
s = GetFormattedValueToString();
}
label_->setText(s);
}
QVariant SliderBase::AdjustValue(const QVariant &value) const
{
return value;
}
bool SliderBase::CanSetValue() const
{
return true;
}
void SliderBase::ValueSignalEvent(const QVariant &value)
{
Q_UNUSED(value)
}
void SliderBase::ShowEditor()
{
// This was a simple click
// Load label's text into editor
editor_->setText(ValueToString(value_));
// Show editor
setCurrentWidget(editor_);
// Select all text in the editor
editor_->setFocus();
editor_->selectAll();
}
void SliderBase::LineEditConfirmed()
{
bool is_valid = true;
QVariant test_val = StringToValue(editor_->text(), &is_valid);
// Ensure editor doesn't signal that the focus is lost
editor_->blockSignals(true);
label_->blockSignals(true);
if (is_valid) {
SetValueInternal(test_val);
setCurrentWidget(label_);
ValueSignalEvent(value_);
} else {
QMessageBox::critical(this,
tr("Invalid Value"),
tr("The entered value is not valid for this field."),
QMessageBox::Ok);
// Refocus editor
editor_->setFocus();
}
editor_->blockSignals(false);
label_->blockSignals(false);
}
void SliderBase::LineEditCancelled()
{
// Ensure editor doesn't signal that the focus is lost
editor_->blockSignals(true);
label_->blockSignals(true);
// Set widget back to label
setCurrentWidget(label_);
editor_->blockSignals(false);
label_->blockSignals(false);
}
void SliderBase::ResetValue()
{
if (default_value_.isValid()) {
SetValueInternal(default_value_);
ValueSignalEvent(value_);
}
}
void SliderBase::SetFormat(const QString &s, const bool plural)
{
custom_format_ = s;
format_plural_ = plural;
UpdateLabel();
}
void SliderBase::ClearFormat()
{
custom_format_.clear();
UpdateLabel();
}
bool SliderBase::IsFormatPlural() const
{
return format_plural_;
}
QString SliderBase::GetFormat() const
{
if (custom_format_.isEmpty()) {
return QStringLiteral("%1");
} else {
return custom_format_;
}
}
QString SliderBase::GetFormattedValueToString() const
{
return GetFormattedValueToString(GetValueInternal());
}
QString SliderBase::GetFormattedValueToString(const QVariant &v) const
{
if (format_plural_) {
return tr(GetFormat().toUtf8().constData(), nullptr, v.toInt());
} else {
return GetFormat().arg(ValueToString(v));
}
}
}
| 5,360
|
C++
|
.cpp
| 199
| 23.884422
| 94
| 0.723713
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,876
|
decimalsliderbase.cpp
|
olive-editor_olive/app/widget/slider/base/decimalsliderbase.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "decimalsliderbase.h"
namespace olive {
#define super NumericSliderBase
DecimalSliderBase::DecimalSliderBase(QWidget *parent) :
super(parent),
decimal_places_(2),
autotrim_decimal_places_(false)
{
}
void DecimalSliderBase::SetAutoTrimDecimalPlaces(bool e)
{
autotrim_decimal_places_ = e;
UpdateLabel();
}
QString DecimalSliderBase::FloatToString(double val, int decimal_places, bool autotrim_decimal_places)
{
QString s = QString::number(val, 'f', decimal_places);
if (autotrim_decimal_places) {
while (s.endsWith('0')
&& s.at(s.size() - 2).isDigit()) {
s = s.left(s.size() - 1);
}
}
return s;
}
void DecimalSliderBase::SetDecimalPlaces(int i)
{
decimal_places_ = i;
UpdateLabel();
}
}
| 1,466
|
C++
|
.cpp
| 45
| 29.6
| 102
| 0.745545
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,877
|
clickablelabel.cpp
|
olive-editor_olive/app/widget/clickablelabel/clickablelabel.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "clickablelabel.h"
#include <QMouseEvent>
namespace olive {
ClickableLabel::ClickableLabel(const QString &text, QWidget *parent) :
QLabel(text, parent)
{
}
ClickableLabel::ClickableLabel(QWidget *parent) :
QLabel(parent)
{
}
void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && underMouse()) {
emit MouseClicked();
}
}
void ClickableLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
emit MouseDoubleClicked();
}
}
}
| 1,255
|
C++
|
.cpp
| 38
| 30.526316
| 71
| 0.762458
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,878
|
collapsebutton.cpp
|
olive-editor_olive/app/widget/collapsebutton/collapsebutton.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "collapsebutton.h"
#include "ui/icons/icons.h"
namespace olive {
CollapseButton::CollapseButton(QWidget *parent) :
QPushButton(parent)
{
setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
setStyleSheet("border: none; background: none;");
setCheckable(true);
setChecked(true);
setIconSize(QSize(fontMetrics().height()/2, fontMetrics().height()/2));
connect(this, &CollapseButton::toggled, this, &CollapseButton::UpdateIcon);
UpdateIcon(isChecked());
}
void CollapseButton::UpdateIcon(bool e)
{
if (e) {
setIcon(icon::TriDown);
} else {
setIcon(icon::TriRight);
}
}
}
| 1,332
|
C++
|
.cpp
| 37
| 33.189189
| 77
| 0.75819
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,879
|
timeruler.cpp
|
olive-editor_olive/app/widget/timeruler/timeruler.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timeruler.h"
#include <QDebug>
#include <QPainter>
#include "common/qtutils.h"
#include "config/config.h"
#include "core.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
namespace olive {
#define super SeekableWidget
TimeRuler::TimeRuler(bool text_visible, bool cache_status_visible, QWidget* parent) :
super(parent),
text_visible_(text_visible),
centered_text_(true),
show_cache_status_(cache_status_visible),
playback_cache_(nullptr)
{
QFontMetrics fm = fontMetrics();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// Text height is used to calculate widget height
// Get the "minimum" space allowed between two line markers on the ruler (in screen pixels)
// Mediocre but reliable way of scaling UI objects by font/DPI size
minimum_gap_between_lines_ = QtUtils::QFontMetricsWidth(fm, "H");
// Text visibility affects height, so we set that here
UpdateHeight();
// Force update if the default timecode display mode changes
connect(Core::instance(), &Core::TimecodeDisplayChanged, this, static_cast<void (TimeRuler::*)()>(&TimeRuler::update));
// 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)
{
if (!show_cache_status_) {
return;
}
if (playback_cache_) {
disconnect(playback_cache_, &PlaybackCache::Invalidated, viewport(), static_cast<void(QWidget::*)()>(&QWidget::update));
disconnect(playback_cache_, &PlaybackCache::Validated, viewport(), static_cast<void(QWidget::*)()>(&QWidget::update));
}
playback_cache_ = cache;
if (playback_cache_) {
connect(playback_cache_, &PlaybackCache::Invalidated, viewport(), static_cast<void(QWidget::*)()>(&QWidget::update));
connect(playback_cache_, &PlaybackCache::Validated, viewport(), static_cast<void(QWidget::*)()>(&QWidget::update));
}
update();
}
void TimeRuler::drawForeground(QPainter *p, const QRectF &rect)
{
// Nothing to paint if the timebase is invalid
if (timebase().isNull()) {
return;
}
// Draw timeline points if connected
int marker_height = TimelineMarker::GetMarkerHeight(p->fontMetrics());
DrawWorkArea(p);
DrawMarkers(p, marker_height);
double width_of_frame = timebase_dbl() * GetScale();
double width_of_second = 0;
do {
width_of_second += timebase_dbl();
} while (width_of_second < 1.0);
width_of_second *= GetScale();
double width_of_minute = width_of_second * 60;
double width_of_hour = width_of_minute * 60;
double width_of_day = width_of_hour * 24;
double long_interval, short_interval;
int long_rate = 0;
// Used for comparison, even if one unit can technically fit, we have to fit at least two for it to matter
int doubled_gap = minimum_gap_between_lines_ * 2;
if (width_of_day < doubled_gap) {
long_interval = -1;
short_interval = width_of_day;
} else if (width_of_hour < doubled_gap) {
long_interval = width_of_day;
long_rate = 24;
short_interval = width_of_hour;
} else if (width_of_minute < doubled_gap) {
long_interval = width_of_hour;
long_rate = 60;
short_interval = width_of_minute;
} else if (width_of_second < doubled_gap) {
long_interval = width_of_minute;
long_rate = 60;
short_interval = width_of_second;
} else if (width_of_frame < doubled_gap) {
long_interval = width_of_second;
long_rate = qRound(timebase_flipped_dbl_);
short_interval = width_of_frame;
} else {
// FIXME: Implement this...
long_interval = width_of_second;
short_interval = width_of_frame;
}
if (short_interval < minimum_gap_between_lines_) {
if (long_interval <= 0) {
do {
short_interval *= 2;
} while (short_interval < minimum_gap_between_lines_);
} else {
int div;
short_interval = long_interval;
for (div=long_rate;div>0;div--) {
if (long_rate%div == 0) {
// This division produces a whole number
double test_frame_width = long_interval / static_cast<double>(div);
if (test_frame_width >= minimum_gap_between_lines_) {
short_interval = test_frame_width;
break;
}
}
}
}
}
// Set line color to main text color
p->setBrush(Qt::NoBrush);
p->setPen(palette().text().color());
// Calculate line dimensions
QFontMetrics fm = p->fontMetrics();
int line_bottom = height();
if (show_cache_status_) {
line_bottom -= PlaybackCache::GetCacheIndicatorHeight();
}
int long_height = fm.height();
int short_height = long_height/2;
int long_y = line_bottom - long_height;
int short_y = line_bottom - short_height;
// Draw long lines
int last_long_unit = -1;
int last_short_unit = -1;
int last_text_draw = INT_MIN;
// FIXME: Hardcoded number
const int kAverageTextWidth = 200;
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 = std::floor(screen_pt/long_interval);
if (this_long_unit != last_long_unit) {
int line_y = long_y;
if (text_visible_) {
QRect text_rect;
Qt::Alignment text_align;
QString timecode_str = QString::fromStdString(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, marker_height, kAverageTextWidth, fm.height());
text_align = Qt::AlignCenter;
timecode_left = i - timecode_width/2;
} else {
text_rect = QRect(i, marker_height, kAverageTextWidth, fm.height());
text_align = Qt::AlignLeft | Qt::AlignVCenter;
timecode_left = i;
// Add gap to left between line and text
timecode_str.prepend(' ');
}
if (timecode_left > last_text_draw) {
p->drawText(text_rect,
static_cast<int>(text_align),
timecode_str);
last_text_draw = timecode_left + timecode_width;
if (!centered_text_) {
line_y = 0;
}
}
}
p->drawLine(i, line_y, i, line_bottom);
last_long_unit = this_long_unit;
}
}
if (short_interval > -1) {
int this_short_unit = std::floor(screen_pt/short_interval);
if (this_short_unit != last_short_unit) {
p->drawLine(i, short_y, i, line_bottom);
last_short_unit = this_short_unit;
}
}
}
// If cache status is enabled
if (show_cache_status_ && playback_cache_ && playback_cache_->HasValidatedRanges()) {
// FIXME: Hardcoded to get video length, if we ever need audio length, this will have to change
int h = PlaybackCache::GetCacheIndicatorHeight();
QRect cache_rect(0, height() - h, width(), h);
if (ViewerOutput *viewer = dynamic_cast<ViewerOutput*>(playback_cache_->parent())) {
int right = TimeToScene(viewer->GetVideoLength());
cache_rect.setWidth(std::max(0, right));
}
if (cache_rect.width() > 0) {
playback_cache_->Draw(p, SceneToTime(GetScroll()), GetScale(), cache_rect);
}
}
// Draw the playhead if it's on screen at the moment
int playhead_pos = TimeToScene(GetViewerNode()->GetPlayhead());
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();
}
int TimeRuler::CacheStatusHeight() const
{
return fontMetrics().height() / 4;
}
bool TimeRuler::ShowContextMenu(const QPoint &p)
{
if (super::ShowContextMenu(p)) {
return true;
} else {
Menu m(this);
MenuShared::instance()->AddItemsForTimeRulerMenu(&m);
MenuShared::instance()->AboutToShowTimeRulerActions(timebase());
m.exec(mapToGlobal(p));
return true;
}
}
void TimeRuler::UpdateHeight()
{
int height = text_height();
// Add text height
if (text_visible_) {
height += text_height();
}
// Add cache status height
if (show_cache_status_) {
height += PlaybackCache::GetCacheIndicatorHeight();
}
// Add marker height
height += TimelineMarker::GetMarkerHeight(fontMetrics());
setFixedHeight(height);
}
}
| 9,808
|
C++
|
.cpp
| 257
| 33.124514
| 152
| 0.675946
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,880
|
seekablewidget.cpp
|
olive-editor_olive/app/widget/timeruler/seekablewidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "seekablewidget.h"
#include <QInputDialog>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>
#include "common/qtutils.h"
#include "common/range.h"
#include "core.h"
#include "dialog/markerproperties/markerpropertiesdialog.h"
#include "node/project/serializer/serializer.h"
#include "timeline/timelineundoworkarea.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) :
super(parent),
markers_(nullptr),
workarea_(nullptr),
dragging_(false),
ignore_next_focus_out_(false),
selection_manager_(this),
resize_item_(nullptr),
marker_top_(0),
marker_bottom_(0),
marker_editing_enabled_(true)
{
QFontMetrics fm = fontMetrics();
text_height_ = fm.height();
// Set width of playhead marker
playhead_width_ = QtUtils::QFontMetricsWidth(fm, "H");
setContextMenuPolicy(Qt::CustomContextMenu);
setFocusPolicy(Qt::ClickFocus);
setMouseTracking(true);
selection_manager_.SetSnapMask(TimeBasedWidget::kSnapAll);
SetIsTimelineAxes(true);
}
void SeekableWidget::SetMarkers(TimelineMarkerList *markers)
{
if (markers_) {
selection_manager_.ClearSelection();
disconnect(markers_, &TimelineMarkerList::MarkerAdded, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(markers_, &TimelineMarkerList::MarkerRemoved, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(markers_, &TimelineMarkerList::MarkerModified, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
markers_ = markers;
if (markers_) {
connect(markers_, &TimelineMarkerList::MarkerAdded, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(markers_, &TimelineMarkerList::MarkerRemoved, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(markers_, &TimelineMarkerList::MarkerModified, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
viewport()->update();
}
void SeekableWidget::SetWorkArea(TimelineWorkArea *workarea)
{
if (workarea_) {
selection_manager_.ClearSelection();
disconnect(workarea_, &TimelineWorkArea::RangeChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(workarea_, &TimelineWorkArea::EnabledChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
workarea_ = workarea;
if (workarea_) {
connect(workarea_, &TimelineWorkArea::RangeChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(workarea_, &TimelineWorkArea::EnabledChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
viewport()->update();
}
void SeekableWidget::DeleteSelected()
{
if (!selection_manager_.IsDragging()) {
MultiUndoCommand* command = new MultiUndoCommand();
foreach (TimelineMarker *marker, selection_manager_.GetSelectedObjects()) {
command->add_child(new MarkerRemoveCommand(marker));
}
Core::instance()->undo_stack()->push(command, tr("Deleted %1 Marker(s)").arg(selection_manager_.GetSelectedObjects().size()));
}
}
bool SeekableWidget::CopySelected(bool cut)
{
if (!selection_manager_.GetSelectedObjects().empty()) {
ProjectSerializer::SaveData sdata(ProjectSerializer::kOnlyMarkers);
sdata.SetOnlySerializeMarkers(selection_manager_.GetSelectedObjects());
ProjectSerializer::Copy(sdata);
if (cut) {
DeleteSelected();
}
return true;
} else {
return false;
}
}
bool SeekableWidget::PasteMarkers()
{
ProjectSerializer::Result res = ProjectSerializer::Paste(ProjectSerializer::kOnlyMarkers);
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 = std::min(min, (*it)->time().in());
}
min -= GetViewerNode()->GetPlayhead();
for (auto it=markers.cbegin(); it!=markers.cend(); it++) {
TimelineMarker *m = *it;
m->set_time(m->time().in() - min);
if (TimelineMarker *existing = markers_->GetMarkerAtTime(m->time().in())) {
command->add_child(new MarkerRemoveCommand(existing));
}
command->add_child(new MarkerAddCommand(markers_, m));
}
Core::instance()->undo_stack()->push(command, tr("Pasted %1 Marker(s)").arg(markers.size()));
return true;
}
}
return false;
}
void SeekableWidget::mousePressEvent(QMouseEvent *event)
{
TimelineMarker *initial;
if (HandPress(event)) {
return;
} else if (event->modifiers() & Qt::ControlModifier) {
selection_manager_.RubberBandStart(event);
} else if (marker_editing_enabled_ && (initial = selection_manager_.MousePress(event))) {
selection_manager_.DragStart(initial, event);
} else if (resize_item_) {
// Handle selection, even though we won't be using it for dragging
if (!(event->modifiers() & Qt::ShiftModifier)) {
selection_manager_.ClearSelection();
}
if (TimelineMarker *m = dynamic_cast<TimelineMarker*>(resize_item_)) {
selection_manager_.Select(m);
}
dragging_ = true;
resize_start_ = mapToScene(event->pos());
} 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 (HandMove(event)) {
return;
} else if (selection_manager_.IsRubberBanding()) {
selection_manager_.RubberBandMove(event->pos());
viewport()->update();
} else if (selection_manager_.IsDragging()) {
selection_manager_.DragMove(event->pos());
} else if (dragging_) {
QPointF scene = mapToScene(event->pos());
if (resize_item_) {
DragResizeHandle(scene);
} else {
SeekToScenePoint(scene.x());
}
} else {
// Look for resize points
if (!last_playhead_shape_.containsPoint(event->pos(), Qt::OddEvenFill)
&& !selection_manager_.GetObjectAtPoint(event->pos())
&& FindResizeHandle(event)) {
setCursor(Qt::SizeHorCursor);
} else {
unsetCursor();
ClearResizeHandle();
}
}
if (event->buttons()) {
// Signal cursor pos in case we should scroll to catch up to it
emit DragMoved(event->pos().x(), event->pos().y());
}
}
void SeekableWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (HandRelease(event)) {
return;
}
if (selection_manager_.IsRubberBanding()) {
selection_manager_.RubberBandStop();
return;
}
if (selection_manager_.IsDragging()) {
MultiUndoCommand *command = new MultiUndoCommand();
selection_manager_.DragStop(command);
Core::instance()->undo_stack()->push(command, tr("Moved %1 Marker(s)").arg(selection_manager_.GetSelectedObjects().size()));
}
if (GetSnapService()) {
GetSnapService()->HideSnaps();
}
if (resize_item_) {
CommitResizeHandle();
resize_item_ = nullptr;
}
dragging_ = false;
emit DragReleased();
}
void SeekableWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
super::mouseDoubleClickEvent(event);
if (selection_manager_.GetObjectAtPoint(event->pos()) && !selection_manager_.GetSelectedObjects().empty()) {
ShowMarkerProperties();
}
}
void SeekableWidget::focusOutEvent(QFocusEvent *event)
{
super::focusOutEvent(event);
if (ignore_next_focus_out_) {
ignore_next_focus_out_ = false;
} else {
// Deselect everything when we lose focus
DeselectAllMarkers();
}
}
void SeekableWidget::DrawMarkers(QPainter *p, int marker_bottom)
{
selection_manager_.ClearDrawnObjects();
// Draw markers
if (markers_ && !markers_->empty() && marker_bottom > 0) {
int lim_left = GetLeftLimit();
int lim_right = GetRightLimit();
for (auto it=markers_->cbegin(); it!=markers_->cend(); it++) {
TimelineMarker* marker = *it;
int marker_right = TimeToScene(marker->time().out());
if (marker_right < lim_left) {
continue;
}
int marker_left = TimeToScene(marker->time().in());
if (marker_left >= lim_right) {
break;
}
int max_marker_right = lim_right;
{
// Check if there's a marker next
auto next = it;
next++;
if (next != markers_->cend()) {
max_marker_right = std::min(max_marker_right, int(TimeToScene((*next)->time().in())));
}
}
QRect marker_rect = marker->Draw(p, QPoint(marker_left, marker_bottom), max_marker_right, GetScale(), selection_manager_.IsSelected(marker));
marker_top_ = marker_rect.top();
selection_manager_.DeclareDrawnObject(marker, marker_rect);
}
}
marker_bottom_ = marker_bottom;
}
void SeekableWidget::DrawWorkArea(QPainter *p)
{
// Draw in/out workarea
if (workarea_ && workarea_->enabled()) {
int lim_left = GetLeftLimit();
int lim_right = GetRightLimit();
int workarea_left = qMax(qreal(lim_left), TimeToScene(workarea_->in()));
int workarea_right;
if (workarea_->out() == TimelineWorkArea::kResetOut) {
workarea_right = lim_right;
} else {
workarea_right = qMin(qreal(lim_right), TimeToScene(workarea_->out()));
}
QColor translucent_highlight = palette().highlight().color();
translucent_highlight.setAlpha(96);
p->fillRect(workarea_left, 0, workarea_right - workarea_left, height(), translucent_highlight);
}
}
void SeekableWidget::DeselectAllMarkers()
{
selection_manager_.ClearSelection();
viewport()->update();
}
void SeekableWidget::SetMarkerColor(int c)
{
MultiUndoCommand *command = new MultiUndoCommand();
foreach(TimelineMarker* marker, selection_manager_.GetSelectedObjects()) {
command->add_child(new MarkerChangeColorCommand(marker, c));
}
Core::instance()->undo_stack()->push(command, tr("Changed Color of %1 Marker(s)").arg(selection_manager_.GetSelectedObjects().size()));
}
void SeekableWidget::ShowMarkerProperties()
{
MarkerPropertiesDialog mpd(selection_manager_.GetSelectedObjects(), timebase(), this);
ignore_next_focus_out_ = true;
mpd.exec();
}
void SeekableWidget::TimebaseChangedEvent(const rational &t)
{
super::TimebaseChangedEvent(t);
selection_manager_.SetTimebase(t);
}
void SeekableWidget::SeekToScenePoint(qreal scene)
{
if (timebase().isNull()) {
return;
}
rational playhead_time = qMax(rational(0), SceneToTime(scene));
if (Core::instance()->snapping() && GetSnapService()) {
rational movement;
GetSnapService()->SnapPoint({playhead_time},
&movement,
TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToPlayhead);
playhead_time += movement;
}
if (playhead_time != GetViewerNode()->GetPlayhead()) {
GetViewerNode()->SetPlayhead(playhead_time);
}
}
void SeekableWidget::SelectionManagerSelectEvent(void *obj)
{
super::SelectionManagerSelectEvent(obj);
viewport()->update();
}
void SeekableWidget::SelectionManagerDeselectEvent(void *obj)
{
super::SelectionManagerDeselectEvent(obj);
viewport()->update();
}
void SeekableWidget::CatchUpScrollEvent()
{
super::CatchUpScrollEvent();
this->selection_manager_.ForceDragUpdate();
}
void SeekableWidget::DrawPlayhead(QPainter *p, int x, int y)
{
int half_width = playhead_width_ / 2;
{
int test = x - this->GetScroll();
if (test + half_width < 0 || test - half_width > width()) {
return;
}
}
p->setRenderHint(QPainter::Antialiasing);
int half_text_height = text_height() / 3;
last_playhead_shape_ = QPolygon({
QPoint(x, y),
QPoint(x - half_width, y - half_text_height),
QPoint(x - half_width, y - text_height()),
QPoint(x + 1 + half_width, y - text_height()),
QPoint(x + 1 + half_width, y - half_text_height),
QPoint(x + 1, y),
});
p->drawPolygon(last_playhead_shape_);
p->setRenderHint(QPainter::Antialiasing, false);
}
int SeekableWidget::GetLeftLimit() const
{
return GetScroll();
}
int SeekableWidget::GetRightLimit() const
{
return GetLeftLimit() + width();
}
bool SeekableWidget::ShowContextMenu(const QPoint &p)
{
if (marker_editing_enabled_ && 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;
}
}
bool SeekableWidget::FindResizeHandle(QMouseEvent *event)
{
if (!marker_editing_enabled_) {
return false;
}
ClearResizeHandle();
QPointF scene = mapToScene(event->pos());
const int border = 10;
rational min = SceneToTimeNoGrid(scene.x() - border);
rational max = SceneToTimeNoGrid(scene.x() + border);
// Test for workarea
if (workarea_ && workarea_->enabled()) {
if (workarea_->in() >= min && workarea_->in() < max) {
resize_mode_ = kResizeIn;
} else if (workarea_->out() >= min && workarea_->out() < max) {
resize_mode_ = kResizeOut;
}
}
if (resize_mode_ != kResizeNone) {
if (workarea_) {
resize_item_ = workarea_;
resize_item_range_ = workarea_->range();
resize_snap_mask_ = TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToWorkarea;
}
} else if (event->pos().y() >= marker_top_ && event->pos().y() < marker_bottom_) {
if (markers_) {
// Check for markers
for (auto it=markers_->cbegin(); it!=markers_->cend(); it++) {
TimelineMarker *m = *it;
if (m->time().in() != m->time().out()) {
if (m->time().in() >= min && m->time().in() < max) {
resize_mode_ = kResizeIn;
} else if (m->time().out() >= min && m->time().out() < max) {
resize_mode_ = kResizeOut;
}
if (resize_mode_ != kResizeNone) {
resize_item_ = m;
resize_item_range_ = m->time();
resize_snap_mask_ = TimeBasedWidget::kSnapAll;
break;
}
}
}
}
}
return resize_item_;
}
void SeekableWidget::ClearResizeHandle()
{
resize_item_ = nullptr;
resize_mode_ = kResizeNone;
}
void SeekableWidget::DragResizeHandle(const QPointF &scene)
{
qreal diff = scene.x() - resize_start_.x();
rational proposed_time;
if (resize_mode_ == kResizeIn) {
proposed_time = qMax(rational(0), qMin(resize_item_range_.out(), resize_item_range_.in() + SceneToTimeNoGrid(diff)));
} else {
proposed_time = qMax(resize_item_range_.in(), resize_item_range_.out() + SceneToTimeNoGrid(diff));
}
rational presnap_time = proposed_time;
if (Core::instance()->snapping() && GetSnapService()) {
rational movement;
GetSnapService()->SnapPoint({proposed_time}, &movement, resize_snap_mask_);
proposed_time += movement;
}
TimeRange new_range = resize_item_range_;
if (resize_mode_ == kResizeIn) {
// Markers should not have the same time as anything else
// NOTE: This code is largely duplicated from TimeBasedViewSelectionManager::DragMove. Not ideal,
// but I'm not sure if there's a good way to re-use that code
if (TimelineMarker *marker = dynamic_cast<TimelineMarker*>(resize_item_)) {
if (marker->has_sibling_at_time(proposed_time)) {
proposed_time = presnap_time;
if (GetSnapService()) {
GetSnapService()->HideSnaps();
}
}
while (marker->has_sibling_at_time(proposed_time)) {
proposed_time += rational(1, 1000);
}
}
new_range.set_in(proposed_time);
} else {
new_range.set_out(proposed_time);
}
if (TimelineMarker *marker = dynamic_cast<TimelineMarker*>(resize_item_)) {
marker->set_time(new_range);
} else if (TimelineWorkArea *workarea = dynamic_cast<TimelineWorkArea*>(resize_item_)) {
workarea->set_range(new_range);
}
}
void SeekableWidget::CommitResizeHandle()
{
MultiUndoCommand *command = new MultiUndoCommand();
QString command_name;
if (TimelineMarker *marker = dynamic_cast<TimelineMarker*>(resize_item_)) {
command->add_child(new MarkerChangeTimeCommand(marker, marker->time(), resize_item_range_));
command_name = tr("Changed Marker Length");
} else if (TimelineWorkArea *workarea = dynamic_cast<TimelineWorkArea*>(resize_item_)) {
command->add_child(new WorkareaSetRangeCommand(workarea, workarea->range(), resize_item_range_));
command_name = tr("Changed Workarea Length");
}
Core::instance()->undo_stack()->push(command, command_name);
}
}
| 17,975
|
C++
|
.cpp
| 495
| 31.917172
| 147
| 0.684802
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,881
|
nodetablewidget.cpp
|
olive-editor_olive/app/widget/nodetableview/nodetablewidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodetablewidget.h"
#include <QVBoxLayout>
namespace olive {
NodeTableWidget::NodeTableWidget(QWidget* parent) :
TimeBasedWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
view_ = new NodeTableView();
layout->addWidget(view_);
}
}
| 1,044
|
C++
|
.cpp
| 27
| 35.925926
| 71
| 0.767396
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,882
|
nodetableview.cpp
|
olive-editor_olive/app/widget/nodetableview/nodetableview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "nodetableview.h"
#include <QCheckBox>
#include <QHeaderView>
#include "node/traverser.h"
namespace olive {
NodeTableView::NodeTableView(QWidget* parent) :
QTreeWidget(parent)
{
setColumnCount(3);
setHeaderLabels({tr("Type"),
tr("Source"),
tr("R/X"),
tr("G/Y"),
tr("B/Z"),
tr("A/W")});
}
void NodeTableView::SelectNodes(const QVector<Node *> &nodes)
{
foreach (Node* n, nodes) {
QTreeWidgetItem* top_item = new QTreeWidgetItem();
top_item->setText(0, n->GetLabelAndName());
top_item->setFirstColumnSpanned(true);
this->addTopLevelItem(top_item);
top_level_item_map_.insert(n, top_item);
}
SetTime(last_time_);
}
void NodeTableView::DeselectNodes(const QVector<Node *> &nodes)
{
foreach (Node* n, nodes) {
delete top_level_item_map_.take(n);
}
}
void NodeTableView::SetTime(const rational &time)
{
last_time_ = time;
NodeTraverser traverser;
for (auto i=top_level_item_map_.constBegin(); i!=top_level_item_map_.constEnd(); i++) {
Node* node = i.key();
QTreeWidgetItem* item = i.value();
// Generate a value database for this node at this time
NodeValueDatabase db = traverser.GenerateDatabase(node, TimeRange(time, time));
// Delete any children of this item that aren't in this database
for (int j=0; j<item->childCount(); j++) {
if (!db.contains(item->child(j)->data(0, Qt::UserRole).toString())) {
delete item->takeChild(j);
j--;
}
}
// Update all inputs
for (auto l=db.begin(); l!=db.end(); l++) {
const NodeValueTable& table = l.value();
if (!node->HasInputWithID(l.key())) {
// Filters out table entries that aren't inputs (like "global")
continue;
}
QTreeWidgetItem* input_item = nullptr;
for (int j=0; j<item->childCount(); j++) {
QTreeWidgetItem* compare = item->child(j);
if (compare->data(0, Qt::UserRole).toString() == l.key()) {
input_item = compare;
break;
}
}
if (!input_item) {
input_item = new QTreeWidgetItem();
input_item->setText(0, node->GetInputName(l.key()));
input_item->setData(0, Qt::UserRole, l.key());
input_item->setFirstColumnSpanned(true);
item->addChild(input_item);
}
// Create children if necessary
while (input_item->childCount() < table.Count()) {
input_item->addChild(new QTreeWidgetItem());
}
// Remove children if necessary
while (input_item->childCount() > table.Count()) {
delete input_item->takeChild(input_item->childCount() - 1);
}
for (int j=0;j<table.Count();j++) {
const NodeValue& value = table.at(table.Count() - 1 - j);
// Create item
QTreeWidgetItem* sub_item = input_item->child(j);
// Set data type name
sub_item->setText(0, NodeValue::GetPrettyDataTypeName(value.type()));
// Determine source
QString source_name;
if (value.source()) {
source_name = value.source()->GetLabelAndName();
} else {
source_name = tr("(unknown)");
}
sub_item->setText(1, source_name);
switch (value.type()) {
case NodeValue::kVideoParams:
case NodeValue::kAudioParams:
// These types have no string representation
break;
case NodeValue::kTexture:
{
// NodeTraverser puts video params in here
for (int k=0;k<VideoParams::kRGBAChannelCount;k++) {
this->setItemWidget(sub_item, 2 + k, new QCheckBox());
}
break;
}
default:
{
QVector<QVariant> split_values = value.to_split_value();
for (int k=0;k<split_values.size();k++) {
sub_item->setText(2 + k, NodeValue::ValueToString(value.type(), split_values.at(k), true));
}
}
}
}
}
}
}
}
| 4,732
|
C++
|
.cpp
| 133
| 28.706767
| 103
| 0.618349
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,883
|
filefield.cpp
|
olive-editor_olive/app/widget/filefield/filefield.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "filefield.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QHBoxLayout>
#include "ui/icons/icons.h"
namespace olive {
FileField::FileField(QWidget* parent) :
QWidget(parent),
directory_mode_(false)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
line_edit_ = new QLineEdit();
connect(line_edit_, &QLineEdit::textChanged, this, &FileField::LineEditChanged);
connect(line_edit_, &QLineEdit::textEdited, this, &FileField::FilenameChanged);
layout->addWidget(line_edit_);
browse_btn_ = new QPushButton();
browse_btn_->setIcon(icon::Open);
connect(browse_btn_, &QPushButton::clicked, this, &FileField::BrowseBtnClicked);
layout->addWidget(browse_btn_);
}
void FileField::BrowseBtnClicked()
{
QString s;
if (directory_mode_) {
s = QFileDialog::getExistingDirectory(this, tr("Open Directory"));
} else {
s = QFileDialog::getOpenFileName(this, tr("Open File"));
}
if (!s.isEmpty()) {
line_edit_->setText(s);
emit FilenameChanged(s);
}
}
void FileField::LineEditChanged(const QString& text)
{
if (QFileInfo::exists(text) || text.isEmpty()) {
line_edit_->setStyleSheet(QString());
} else {
line_edit_->setStyleSheet(QStringLiteral("QLineEdit {color: red;}"));
}
}
}
| 2,003
|
C++
|
.cpp
| 57
| 32.245614
| 82
| 0.735477
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,884
|
taskview.cpp
|
olive-editor_olive/app/widget/taskview/taskview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "taskview.h"
#include <QPushButton>
namespace olive {
TaskView::TaskView(QWidget* parent) :
QScrollArea(parent)
{
// Allow scroll area to resize widget to fit
setWidgetResizable(true);
// Create central widget
central_widget_ = new QWidget(this);
setWidget(central_widget_);
// Create layout for central widget
layout_ = new QVBoxLayout(central_widget_);
layout_->setSpacing(0);
layout_->setContentsMargins(0, 0, 0, 0);
// Add a "stretch" so that TaskViewItems don't try to expand all the way to the bottom
layout_->addStretch();
}
void TaskView::AddTask(Task *t)
{
// Create TaskViewItem (UI representation of a Task) and connect it
TaskViewItem* item = new TaskViewItem(t);
connect(item, &TaskViewItem::TaskCancelled, this, &TaskView::TaskCancelled);
items_.insert(t, item);
layout_->insertWidget(layout_->count()-1, item);
}
void TaskView::TaskFailed(Task *t)
{
items_.value(t)->Failed();
}
void TaskView::RemoveTask(Task *t)
{
items_.value(t)->deleteLater();
items_.remove(t);
}
}
| 1,756
|
C++
|
.cpp
| 50
| 32.52
| 88
| 0.747929
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,885
|
taskviewitem.cpp
|
olive-editor_olive/app/widget/taskview/taskviewitem.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "taskviewitem.h"
#include <QDateTime>
#include <QVBoxLayout>
#include "ui/icons/icons.h"
namespace olive {
TaskViewItem::TaskViewItem(Task* task, QWidget *parent) :
QFrame(parent),
task_(task)
{
// Draw border around this item
setFrameShape(QFrame::StyledPanel);
// Create layout
QVBoxLayout* layout = new QVBoxLayout(this);
// Create header label
task_name_lbl_ = new QLabel(this);
task_name_lbl_->setText(task_->GetTitle());
layout->addWidget(task_name_lbl_);
// Create center layout (combines progress bar and a cancel button)
QHBoxLayout* middle_layout = new QHBoxLayout();
layout->addLayout(middle_layout);
// Create progress bar
progress_bar_ = new QProgressBar(this);
progress_bar_->setRange(0, 100);
middle_layout->addWidget(progress_bar_);
// Create cancel button
cancel_btn_ = new QPushButton(this);
cancel_btn_->setIcon(icon::Error);
middle_layout->addWidget(cancel_btn_);
// Create stack with error label and elapsed/remaining time
status_stack_ = new QStackedWidget();
status_stack_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
layout->addWidget(status_stack_);
// Create elapsed timer
elapsed_timer_lbl_ = new ElapsedCounterWidget();
status_stack_->addWidget(elapsed_timer_lbl_);
// Create error label
task_error_lbl_ = new QLabel(this);
status_stack_->addWidget(task_error_lbl_);
// Set up elapsed timer
status_stack_->setCurrentWidget(elapsed_timer_lbl_);
// Connect to the task
connect(task_, &Task::Started, elapsed_timer_lbl_, qOverload<qint64>(&ElapsedCounterWidget::Start));
connect(task_, &Task::ProgressChanged, this, &TaskViewItem::UpdateProgress);
connect(cancel_btn_, &QPushButton::clicked, this, [this] { emit TaskCancelled(task_); });
}
void TaskViewItem::Failed()
{
status_stack_->setCurrentWidget(task_error_lbl_);
task_error_lbl_->setStyleSheet("color: red");
task_error_lbl_->setText(tr("Error: %1").arg(task_->GetError()));
}
void TaskViewItem::UpdateProgress(double d)
{
progress_bar_->setValue(qRound(100.0 * d));
elapsed_timer_lbl_->SetProgress(d);
}
}
| 2,828
|
C++
|
.cpp
| 71
| 36.985915
| 102
| 0.745062
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,886
|
elapsedcounterwidget.cpp
|
olive-editor_olive/app/widget/taskview/elapsedcounterwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "elapsedcounterwidget.h"
#include <olive/core/core.h>
#include <QDateTime>
#include <QHBoxLayout>
#include <cmath>
namespace olive {
using namespace core;
ElapsedCounterWidget::ElapsedCounterWidget(QWidget* parent) :
QWidget(parent),
last_progress_(0),
start_time_(0)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(layout->spacing() * 8);
layout->setContentsMargins(0, 0, 0, 0);
elapsed_lbl_ = new QLabel();
layout->addWidget(elapsed_lbl_);
remaining_lbl_ = new QLabel();
layout->addWidget(remaining_lbl_);
elapsed_timer_.setInterval(500);
connect(&elapsed_timer_, &QTimer::timeout, this, &ElapsedCounterWidget::UpdateTimers);
UpdateTimers();
}
void ElapsedCounterWidget::SetProgress(double d)
{
last_progress_ = d;
UpdateTimers();
}
void ElapsedCounterWidget::Start()
{
Start(QDateTime::currentMSecsSinceEpoch());
}
void ElapsedCounterWidget::Start(qint64 start_time)
{
start_time_ = start_time;
elapsed_timer_.start();
UpdateTimers();
}
void ElapsedCounterWidget::Stop()
{
elapsed_timer_.stop();
}
void ElapsedCounterWidget::UpdateTimers()
{
int64_t elapsed_ms, remaining_ms;
if (last_progress_ > 0) {
elapsed_ms = QDateTime::currentMSecsSinceEpoch() - start_time_;
double ms_per_progress_unit = elapsed_ms / last_progress_;
double remaining_progress = 1.0 - last_progress_;
remaining_ms = std::ceil(ms_per_progress_unit * remaining_progress);
} else {
elapsed_ms = 0;
remaining_ms = 0;
}
elapsed_lbl_->setText(tr("Elapsed: %1").arg(QString::fromStdString(Timecode::time_to_string(elapsed_ms))));
remaining_lbl_->setText(tr("Remaining: %1").arg(QString::fromStdString(Timecode::time_to_string(remaining_ms))));
}
}
| 2,450
|
C++
|
.cpp
| 72
| 31.319444
| 115
| 0.746072
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,887
|
resizabletimelinescrollbar.cpp
|
olive-editor_olive/app/widget/resizablescrollbar/resizabletimelinescrollbar.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "resizabletimelinescrollbar.h"
#include <QPainter>
#include <QStyle>
#include <QStyleOptionSlider>
#include <QtMath>
#include "ui/colorcoding.h"
namespace olive {
ResizableTimelineScrollBar::ResizableTimelineScrollBar(QWidget* parent) :
ResizableScrollBar(parent),
markers_(nullptr),
workarea_(nullptr),
scale_(1.0)
{
}
ResizableTimelineScrollBar::ResizableTimelineScrollBar(Qt::Orientation orientation, QWidget* parent) :
ResizableScrollBar(orientation, parent),
markers_(nullptr),
workarea_(nullptr),
scale_(1.0)
{
}
void ResizableTimelineScrollBar::ConnectMarkers(TimelineMarkerList *markers)
{
if (markers_) {
disconnect(markers_, &TimelineMarkerList::MarkerAdded, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(markers_, &TimelineMarkerList::MarkerRemoved, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(markers_, &TimelineMarkerList::MarkerModified, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
markers_ = markers;
if (markers_) {
connect(markers_, &TimelineMarkerList::MarkerAdded, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(markers_, &TimelineMarkerList::MarkerRemoved, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(markers_, &TimelineMarkerList::MarkerModified, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
update();
}
void ResizableTimelineScrollBar::ConnectWorkArea(TimelineWorkArea *workarea)
{
if (workarea_) {
disconnect(workarea_, &TimelineWorkArea::RangeChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(workarea_, &TimelineWorkArea::EnabledChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
workarea_ = workarea;
if (workarea_) {
connect(workarea_, &TimelineWorkArea::RangeChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(workarea_, &TimelineWorkArea::EnabledChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
update();
}
void ResizableTimelineScrollBar::SetScale(double d)
{
scale_ = d;
update();
}
void ResizableTimelineScrollBar::paintEvent(QPaintEvent *event)
{
ResizableScrollBar::paintEvent(event);
if (!timebase().isNull() && ((workarea_ && workarea_->enabled()) || (markers_ && !markers_->empty()))) {
// Draw workarea
QStyleOptionSlider opt;
initStyleOption(&opt);
QRect gr = style()->subControlRect(QStyle::CC_ScrollBar, &opt,
QStyle::SC_ScrollBarGroove, this);
double ratio = scale_ * double(gr.width()) / double(this->maximum() + gr.width());
QPainter p(this);
if (workarea_ && workarea_->enabled()) {
QColor workarea_color(this->palette().highlight().color());
workarea_color.setAlpha(128);
qint64 in = qMax(qint64(0), qRound64(ratio * TimeToScene(workarea_->in())));
qint64 out;
if (workarea_->out() == RATIONAL_MAX) {
out = gr.width();
} else {
out = qMin(qint64(gr.width()), qRound64(ratio * TimeToScene(workarea_->out())));
}
qint64 length = qMax(qint64(1), out-in);
p.fillRect(gr.x() + in,
0,
length,
height(),
workarea_color);
}
// Draw markers
if (markers_ && !markers_->empty()) {
for (auto it=markers_->cbegin(); it!=markers_->cend(); it++) {
TimelineMarker* marker = *it;
QColor marker_color = QtUtils::toQColor(ColorCoding::GetColor(marker->color()));
int64_t in = qRound64(ratio * TimeToScene(marker->time().in()));
int64_t out = qRound64(ratio * TimeToScene(marker->time().out()));
int64_t length = qMax(int64_t(1), out-in);
p.fillRect(gr.x() + in,
0,
length,
height(),
marker_color);
}
}
}
}
}
| 5,032
|
C++
|
.cpp
| 114
| 38.701754
| 158
| 0.698341
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,888
|
resizablescrollbar.cpp
|
olive-editor_olive/app/widget/resizablescrollbar/resizablescrollbar.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "resizablescrollbar.h"
#include <QDebug>
#include <QMouseEvent>
#include <QStyle>
#include <QStyleOptionSlider>
#include "common/range.h"
namespace olive {
const int ResizableScrollBar::kHandleWidth = 10;
ResizableScrollBar::ResizableScrollBar(QWidget *parent) :
QScrollBar(parent)
{
Init();
}
ResizableScrollBar::ResizableScrollBar(Qt::Orientation orientation, QWidget *parent):
QScrollBar(orientation, parent)
{
Init();
}
void ResizableScrollBar::mousePressEvent(QMouseEvent *event)
{
if (mouse_handle_state_ == kNotInHandle) {
QScrollBar::mousePressEvent(event);
} else {
dragging_ = true;
drag_start_point_ = GetActiveMousePos(event);
emit ResizeBegan(GetActiveBarSize(), (mouse_handle_state_ == kInTopHandle));
}
}
void ResizableScrollBar::mouseMoveEvent(QMouseEvent *event)
{
QRect sr = GetScrollBarRect();
if (dragging_) {
// Determine how much the cursor has moved
int mouse_movement = GetActiveMousePos(event) - drag_start_point_;
emit ResizeMoved(mouse_movement);
} else {
int mouse_pos, top, bottom;
Qt::CursorShape target_cursor;
mouse_pos = GetActiveMousePos(event);
if (orientation() == Qt::Horizontal) {
top = sr.left();
bottom = sr.right();
target_cursor = Qt::SizeHorCursor;
} else {
top = sr.top();
bottom = sr.bottom();
target_cursor = Qt::SizeVerCursor;
}
if (InRange(mouse_pos, top, kHandleWidth)) {
mouse_handle_state_ = kInTopHandle;
} else if (InRange(mouse_pos, bottom, kHandleWidth)) {
mouse_handle_state_ = kInBottomHandle;
} else {
mouse_handle_state_ = kNotInHandle;
}
if (mouse_handle_state_ == kNotInHandle) {
unsetCursor();
} else {
setCursor(target_cursor);
}
QScrollBar::mouseMoveEvent(event);
}
}
void ResizableScrollBar::mouseReleaseEvent(QMouseEvent *event)
{
if (dragging_) {
dragging_ = false;
emit ResizeEnded();
} else {
QScrollBar::mouseReleaseEvent(event);
}
}
QRect ResizableScrollBar::GetScrollBarRect()
{
// Initialize "style option". I don't know what this does, I just ripped it straight from
// Qt source code
QStyleOptionSlider opt;
initStyleOption(&opt);
// Determine rect of slider bar
return style()->subControlRect(QStyle::CC_ScrollBar, &opt,
QStyle::SC_ScrollBarSlider, this);
}
void ResizableScrollBar::Init()
{
setSingleStep(20);
setMaximum(0);
setMouseTracking(true);
mouse_handle_state_= kNotInHandle;
dragging_ = false;
}
int ResizableScrollBar::GetActiveMousePos(QMouseEvent *event)
{
if (orientation() == Qt::Horizontal) {
return event->pos().x();
} else {
return event->pos().y();
}
}
int ResizableScrollBar::GetActiveBarSize()
{
QRect sr = GetScrollBarRect();
if (orientation() == Qt::Horizontal) {
return sr.width();
} else {
return sr.height();
}
}
}
| 3,642
|
C++
|
.cpp
| 122
| 26.114754
| 91
| 0.712769
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,889
|
colorlabelmenu.cpp
|
olive-editor_olive/app/widget/colorlabelmenu/colorlabelmenu.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorlabelmenu.h"
#include <QEvent>
#include <QPainter>
#include <QWidgetAction>
#include "common/qtutils.h"
#include "ui/colorcoding.h"
namespace olive {
ColorLabelMenu::ColorLabelMenu(QWidget *parent) :
Menu(parent)
{
// Used for size calculations
int box_size = fontMetrics().height();
color_items_.resize(ColorCoding::standard_colors().size());
for (int i=0; i<ColorCoding::standard_colors().size(); i++) {
QPixmap p(box_size, box_size);
QPainter painter(&p);
painter.setPen(Qt::black);
painter.setBrush(QtUtils::toQColor(ColorCoding::standard_colors().at(i)));
painter.drawRect(p.rect().adjusted(0, 0, -1, -1));
QAction *a = AddItem(QStringLiteral("colorlabel%1").arg(i), this, &ColorLabelMenu::ActionTriggered);
a->setIcon(p);
a->setData(i);
color_items_.replace(i, a);
}
Retranslate();
}
void ColorLabelMenu::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
Retranslate();
}
Menu::changeEvent(event);
}
void ColorLabelMenu::Retranslate()
{
this->setTitle(tr("Color"));
for (int i=0; i<color_items_.size(); i++) {
color_items_.at(i)->setText(ColorCoding::GetColorName(i));
}
}
void ColorLabelMenu::ActionTriggered()
{
QAction* a = static_cast<QAction*>(sender());
emit ColorSelected(a->data().toInt());
}
}
| 2,050
|
C++
|
.cpp
| 60
| 31.2
| 104
| 0.724365
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,890
|
colorcodingcombobox.cpp
|
olive-editor_olive/app/widget/colorlabelmenu/colorcodingcombobox.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorcodingcombobox.h"
#include "ui/colorcoding.h"
namespace olive {
ColorCodingComboBox::ColorCodingComboBox(QWidget *parent) :
QComboBox(parent)
{
SetColor(0);
}
void ColorCodingComboBox::showPopup()
{
ColorLabelMenu menu(this);
menu.setMinimumWidth(width());
QAction* a = menu.exec(parentWidget()->mapToGlobal(pos()));
if (a) {
SetColor(a->data().toInt());
}
}
void ColorCodingComboBox::SetColor(int index)
{
clear();
addItem(ColorCoding::GetColorName(index));
index_ = index;
}
}
| 1,239
|
C++
|
.cpp
| 38
| 29.947368
| 71
| 0.759696
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,891
|
focusablelineedit.cpp
|
olive-editor_olive/app/widget/focusablelineedit/focusablelineedit.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "focusablelineedit.h"
#include <QKeyEvent>
namespace olive {
FocusableLineEdit::FocusableLineEdit(QWidget *parent) :
QLineEdit(parent)
{
}
void FocusableLineEdit::keyPressEvent(QKeyEvent *e)
{
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
emit Confirmed();
break;
case Qt::Key_Escape:
emit Cancelled();
break;
default:
QLineEdit::keyPressEvent(e);
}
}
void FocusableLineEdit::focusOutEvent(QFocusEvent *e)
{
QLineEdit::focusOutEvent(e);
emit Confirmed();
}
}
| 1,241
|
C++
|
.cpp
| 41
| 27.414634
| 71
| 0.756324
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,892
|
colorbutton.cpp
|
olive-editor_olive/app/widget/colorbutton/colorbutton.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorbutton.h"
#include "dialog/color/colordialog.h"
namespace olive {
ColorButton::ColorButton(ColorManager* color_manager, bool show_dialog_on_click, QWidget *parent) :
QPushButton(parent),
color_manager_(color_manager),
color_processor_(nullptr),
dialog_open_(false)
{
setAutoFillBackground(true);
if (show_dialog_on_click) {
connect(this, &ColorButton::clicked, this, &ColorButton::ShowColorDialog);
}
SetColor(Color(1.0f, 1.0f, 1.0f));
}
const ManagedColor &ColorButton::GetColor() const
{
return color_;
}
void ColorButton::SetColor(const ManagedColor &c)
{
color_ = c;
color_.set_color_input(color_manager_->GetCompliantColorSpace(color_.color_input()));
color_.set_color_output(color_manager_->GetCompliantColorSpace(color_.color_output()));
UpdateColor();
}
void ColorButton::ShowColorDialog()
{
if (!dialog_open_) {
dialog_open_ = true;
ColorDialog *cd = new ColorDialog(color_manager_, color_, this);
connect(cd, &ColorDialog::finished, this, &ColorButton::ColorDialogFinished);
cd->show();
}
}
void ColorButton::ColorDialogFinished(int e)
{
ColorDialog *cd = static_cast<ColorDialog*>(sender());
if (e == QDialog::Accepted) {
color_ = cd->GetSelectedColor();
UpdateColor();
emit ColorChanged(color_);
}
cd->deleteLater();
dialog_open_ = false;
}
void ColorButton::UpdateColor()
{
color_processor_ = ColorProcessor::Create(color_manager_,
color_.color_input(),
color_.color_output());
QColor managed = QtUtils::toQColor(color_processor_->ConvertColor(color_));
setStyleSheet(QStringLiteral("%1--ColorButton {background: %2;}").arg(MACRO_VAL_AS_STR(olive), managed.name()));
}
}
| 2,499
|
C++
|
.cpp
| 69
| 32.057971
| 114
| 0.71607
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,893
|
pathwidget.cpp
|
olive-editor_olive/app/widget/path/pathwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "pathwidget.h"
#include <QDir>
#include <QFileDialog>
#include <QHBoxLayout>
#include "common/filefunctions.h"
namespace olive {
PathWidget::PathWidget(const QString &path, QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
path_edit_ = new QLineEdit();
path_edit_->setText(path);
layout->addWidget(path_edit_);
connect(path_edit_, &QLineEdit::textChanged, this, &PathWidget::LineEditChanged);
browse_btn_ = new QPushButton(tr("Browse"));
layout->addWidget(browse_btn_);
connect(browse_btn_, &QPushButton::clicked, this, &PathWidget::BrowseClicked);
}
void PathWidget::BrowseClicked()
{
QString dir = QFileDialog::getExistingDirectory(static_cast<QWidget*>(parent()),
tr("Browse for path"),
path_edit_->text());
if (!dir.isEmpty()) {
path_edit_->setText(dir);
}
}
void PathWidget::LineEditChanged()
{
if (FileFunctions::DirectoryIsValid(text(), false)) {
path_edit_->setStyleSheet(QString());
} else {
path_edit_->setStyleSheet(QStringLiteral("QLineEdit {color: red;}"));
}
}
}
| 1,925
|
C++
|
.cpp
| 51
| 33.117647
| 83
| 0.704362
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,894
|
colorpreviewbox.cpp
|
olive-editor_olive/app/widget/colorwheel/colorpreviewbox.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorpreviewbox.h"
#include <QPainter>
#include "common/qtutils.h"
namespace olive {
ColorPreviewBox::ColorPreviewBox(QWidget *parent) :
QWidget(parent),
to_ref_processor_(nullptr),
to_display_processor_(nullptr)
{
}
void ColorPreviewBox::SetColorProcessor(ColorProcessorPtr to_ref, ColorProcessorPtr to_display)
{
to_ref_processor_ = to_ref;
to_display_processor_ = to_display;
update();
}
void ColorPreviewBox::SetColor(const Color &c)
{
color_ = c;
update();
}
void ColorPreviewBox::paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e);
QColor c;
// Color management
if (to_ref_processor_ && to_display_processor_) {
c = QtUtils::toQColor(to_display_processor_->ConvertColor(to_ref_processor_->ConvertColor(color_)));
} else {
c = QtUtils::toQColor(color_);
}
QPainter p(this);
QRect draw_rect = rect().adjusted(0, 0, -1, -1);
p.setPen(Qt::black);
if (color_.alpha() < 1.0) {
// Draw black background so the background isn't the window color
p.setBrush(Qt::black);
p.drawRect(draw_rect);
}
// Draw with color over the top
p.setBrush(c);
p.drawRect(draw_rect);
}
}
| 1,868
|
C++
|
.cpp
| 58
| 29.310345
| 104
| 0.736577
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,895
|
colorswatchchooser.cpp
|
olive-editor_olive/app/widget/colorwheel/colorswatchchooser.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorswatchchooser.h"
#include <QGridLayout>
#include "common/filefunctions.h"
#include "widget/menu/menu.h"
namespace olive {
const int kDefaultColorCount = 16;
const Color kDefaultColors[kDefaultColorCount] = {
Color(1.0, 1.0, 1.0),
Color(1.0, 1.0, 0.0),
Color(1.0, 0.5, 0.0),
Color(1.0, 0.0, 0.0),
Color(1.0, 0.0, 1.0),
Color(0.5, 0.0, 1.0),
Color(0.0, 0.0, 1.0),
Color(0.0, 0.5, 1.0),
Color(0.0, 1.0, 0.0),
Color(0.0, 0.5, 0.0),
Color(0.5, 0.25, 0.0),
Color(0.75, 0.5, 0.25),
Color(0.75, 0.75, 0.75),
Color(0.5, 0.5, 0.5),
Color(0.25, 0.25, 0.25),
Color(0.0, 0.0, 0.0)
};
ColorSwatchChooser::ColorSwatchChooser(ColorManager *manager, QWidget *parent) :
QWidget(parent)
{
auto layout = new QGridLayout(this);
for (int x=0; x<kColCount; x++) {
for (int y=0; y<kRowCount; y++) {
// Create button
auto b = new ColorButton(manager, false);
b->setFixedWidth(b->sizeHint().height()/2*3);
b->setContextMenuPolicy(Qt::CustomContextMenu);
layout->addWidget(b, y, x);
// Save button in buttons array
int btn_index = x + kColCount*y;
buttons_[btn_index] = b;
// Set default color
SetDefaultColor(btn_index);
// Connect clicks
connect(b, &ColorButton::clicked, this, &ColorSwatchChooser::HandleButtonClick);
connect(b, &ColorButton::customContextMenuRequested, this, &ColorSwatchChooser::HandleContextMenu);
}
}
LoadSwatches();
}
void ColorSwatchChooser::SetDefaultColor(int index)
{
if (index < kDefaultColorCount) {
buttons_[index]->SetColor(kDefaultColors[index]);
} else {
buttons_[index]->SetColor(Color(1.0, 1.0, 1.0));
}
}
void ColorSwatchChooser::HandleButtonClick()
{
auto b = static_cast<ColorButton*>(sender());
emit ColorClicked(b->GetColor());
SetCurrentColor(b->GetColor());
}
void ColorSwatchChooser::HandleContextMenu()
{
Menu m(this);
auto save_action = m.addAction(tr("Save Color Here"));
connect(save_action, &QAction::triggered, this, &ColorSwatchChooser::SaveCurrentColor);
m.addSeparator();
auto reset_action = m.addAction(tr("Reset To Default"));
connect(reset_action, &QAction::triggered, this, &ColorSwatchChooser::ResetMenuButton);
menu_btn_ = static_cast<ColorButton*>(sender());
m.exec(QCursor::pos());
}
void ColorSwatchChooser::SaveCurrentColor()
{
menu_btn_->SetColor(current_);
SaveSwatches();
}
void ColorSwatchChooser::ResetMenuButton()
{
for (int i=0; i<kBtnCount; i++) {
if (buttons_[i] == menu_btn_) {
SetDefaultColor(i);
break;
}
}
}
QString ColorSwatchChooser::GetSwatchFilename()
{
return QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("swatch"));
}
void ColorSwatchChooser::LoadSwatches()
{
QFile f(GetSwatchFilename());
if (f.open(QFile::ReadOnly)) {
QDataStream d(&f);
uint version;
d >> version;
if (version == 1) {
int index = 0;
while (index < kBtnCount && !d.atEnd()) {
Color::DataType r;
QString s;
ManagedColor c;
ColorTransform t;
bool is_display;
c.set_alpha(1.0);
d >> r;
c.set_red(r);
d >> r;
c.set_green(r);
d >> r;
c.set_blue(r);
d >> s;
c.set_color_input(s);
d >> is_display;
if (is_display) {
QString display, view, look;
d >> display;
d >> view;
d >> look;
c.set_color_output(ColorTransform(display, view, look));
} else {
d >> s;
c.set_color_output(ColorTransform(s));
}
buttons_[index]->SetColor(c);
index++;
}
}
f.close();
}
}
void ColorSwatchChooser::SaveSwatches()
{
QString fn = GetSwatchFilename();
QFile f(fn);
if (f.open(QFile::WriteOnly)) {
QDataStream d(&f);
const uint version = 1;
d << version;
for (int i=0; i<kBtnCount; i++) {
const ManagedColor &c = buttons_[i]->GetColor();
d << c.red();
d << c.green();
d << c.blue();
d << c.color_input();
d << c.color_output().is_display();
if (c.color_output().is_display()) {
d << c.color_output().display();
d << c.color_output().view();
d << c.color_output().look();
} else {
d << c.color_output().output();
}
}
f.close();
} else {
qCritical() << "Failed to open swatch file" << fn << "for writing";
}
}
}
| 5,197
|
C++
|
.cpp
| 175
| 24.88
| 105
| 0.635907
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,896
|
colorgradientwidget.cpp
|
olive-editor_olive/app/widget/colorwheel/colorgradientwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorgradientwidget.h"
#include <QPainter>
#include "common/lerp.h"
#include "node/node.h"
namespace olive {
ColorGradientWidget::ColorGradientWidget(Qt::Orientation orientation, QWidget *parent) :
ColorSwatchWidget(parent),
orientation_(orientation),
val_(1.0)
{
}
Color ColorGradientWidget::GetColorFromScreenPos(const QPoint &p) const
{
if (orientation_ == Qt::Horizontal) {
return LerpColor(start_, end_, p.x(), width());
} else {
return LerpColor(start_, end_, p.y(), height());
}
}
void ColorGradientWidget::paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e);
QPainter p(this);
int min;
int max;
if (orientation_ == Qt::Horizontal) {
min = height();
max = width();
} else {
min = width();
max = height();
}
for (int i=0;i<max;i++) {
p.setPen(QtUtils::toQColor(GetManagedColor(LerpColor(start_, end_, i, max))));
if (orientation_ == Qt::Horizontal) {
p.drawLine(i, 0, i, height());
} else {
p.drawLine(0, i, width(), i);
}
}
// Draw selector
int selector_radius = qMax(2, min / 8);
p.setPen(QPen(GetUISelectorColor(), qMax(1, selector_radius / 2)));
p.setBrush(Qt::NoBrush);
float clamped_val = std::clamp(val_, 0.0f, 1.0f);
if (orientation_ == Qt::Horizontal) {
p.drawRect(qRound(width() * (1.0 - clamped_val)) - selector_radius, 0, selector_radius * 2, height() - 1);
} else {
p.drawRect(0, qRound(height() * (1.0 - clamped_val)) - selector_radius, width() - 1, selector_radius * 2);
}
}
void ColorGradientWidget::SelectedColorChangedEvent(const Color &c, bool external)
{
float hue, sat;
c.toHsv(&hue, &sat, &val_);
if (external) {
start_ = Color::fromHsv(hue, sat, 1.0);
end_ = Color::fromHsv(hue, sat, 0.0);
}
}
Color ColorGradientWidget::LerpColor(const Color &a, const Color &b, int i, int max)
{
float t = std::clamp(static_cast<float>(i) / static_cast<float>(max), 0.0f, 1.0f);
return Color(lerp(a.red(), b.red(), t),
lerp(a.green(), b.green(), t),
lerp(a.blue(), b.blue(), t));
}
}
| 2,796
|
C++
|
.cpp
| 82
| 30.585366
| 110
| 0.677455
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,897
|
colorswatchwidget.cpp
|
olive-editor_olive/app/widget/colorwheel/colorswatchwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorswatchwidget.h"
#include <QMouseEvent>
#include "ui/colorcoding.h"
namespace olive {
ColorSwatchWidget::ColorSwatchWidget(QWidget *parent) :
QWidget(parent),
to_linear_processor_(nullptr),
to_display_processor_(nullptr)
{
}
const Color &ColorSwatchWidget::GetSelectedColor() const
{
return selected_color_;
}
void ColorSwatchWidget::SetColorProcessor(ColorProcessorPtr to_linear, ColorProcessorPtr to_display)
{
to_linear_processor_ = to_linear;
to_display_processor_ = to_display;
// Force full update
SelectedColorChangedEvent(GetSelectedColor(), true);
update();
}
void ColorSwatchWidget::SetSelectedColor(const Color &c)
{
SetSelectedColorInternal(c, true);
}
void ColorSwatchWidget::mousePressEvent(QMouseEvent *e)
{
QWidget::mousePressEvent(e);
SetSelectedColorInternal(GetColorFromScreenPos(e->pos()), false);
emit SelectedColorChanged(GetSelectedColor());
}
void ColorSwatchWidget::mouseMoveEvent(QMouseEvent *e)
{
QWidget::mouseMoveEvent(e);
if (e->buttons() & Qt::LeftButton) {
SetSelectedColorInternal(GetColorFromScreenPos(e->pos()), false);
emit SelectedColorChanged(GetSelectedColor());
}
}
void ColorSwatchWidget::SelectedColorChangedEvent(const Color &, bool)
{
}
Qt::GlobalColor ColorSwatchWidget::GetUISelectorColor() const
{
return ColorCoding::GetUISelectorColor(GetSelectedColor());
}
Color ColorSwatchWidget::GetManagedColor(const Color &input) const
{
if (to_linear_processor_ && to_display_processor_) {
return to_display_processor_->ConvertColor(to_linear_processor_->ConvertColor(input));
}
return input;
}
void ColorSwatchWidget::SetSelectedColorInternal(const Color &c, bool external)
{
selected_color_ = c;
SelectedColorChangedEvent(c, external);
update();
}
}
| 2,493
|
C++
|
.cpp
| 75
| 30.826667
| 100
| 0.78655
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,898
|
colorvalueswidget.cpp
|
olive-editor_olive/app/widget/colorwheel/colorvalueswidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorvalueswidget.h"
#include <QGridLayout>
#include <QMouseEvent>
#include <QTabWidget>
#include "config/config.h"
#include "core.h"
#include "ui/icons/icons.h"
namespace olive {
ColorValuesWidget::ColorValuesWidget(ColorManager *manager, QWidget *parent) :
QWidget(parent),
manager_(manager),
input_to_ref_(nullptr),
ref_to_display_(nullptr),
display_to_ref_(nullptr),
ref_to_input_(nullptr)
{
QVBoxLayout* layout = new QVBoxLayout(this);
// Create preview box
{
QHBoxLayout* preview_layout = new QHBoxLayout();
preview_layout->setContentsMargins(0, 0, 0, 0);
preview_layout->addWidget(new QLabel(tr("Preview")));
preview_ = new ColorPreviewBox();
preview_->setFixedHeight(fontMetrics().height() * 3 / 2);
preview_layout->addWidget(preview_);
color_picker_btn_ = new QPushButton();
color_picker_btn_->setIcon(icon::ColorPicker);
color_picker_btn_->setFixedWidth(color_picker_btn_->sizeHint().height());
color_picker_btn_->setCheckable(true);
connect(color_picker_btn_, &QPushButton::toggled, this, &ColorValuesWidget::ColorPickedBtnToggled);
connect(Core::instance(), &Core::ColorPickerColorEmitted, this, &ColorValuesWidget::SetReferenceColor);
preview_layout->addWidget(color_picker_btn_);
layout->addLayout(preview_layout);
}
// Create value tabs
{
QTabWidget* tabs = new QTabWidget();
input_tab_ = new ColorValuesTab(true);
tabs->addTab(input_tab_, tr("Input"));
connect(input_tab_, &ColorValuesTab::ColorChanged, this, &ColorValuesWidget::UpdateValuesFromInput);
connect(input_tab_, &ColorValuesTab::ColorChanged, this, &ColorValuesWidget::ColorChanged);
connect(input_tab_, &ColorValuesTab::ColorChanged, preview_, &ColorPreviewBox::SetColor);
reference_tab_ = new ColorValuesTab();
tabs->addTab(reference_tab_, tr("Reference"));
connect(reference_tab_, &ColorValuesTab::ColorChanged, this, &ColorValuesWidget::UpdateValuesFromRef);
display_tab_ = new ColorValuesTab();
tabs->addTab(display_tab_, tr("Display"));
connect(display_tab_, &ColorValuesTab::ColorChanged, this, &ColorValuesWidget::UpdateValuesFromDisplay);
// FIXME: Display -> Ref temporarily disabled due to OCIO crash (see ColorDialog::ColorSpaceChanged for more info)
display_tab_->setEnabled(false);
layout->addWidget(tabs);
}
}
Color ColorValuesWidget::GetColor() const
{
return reference_tab_->GetColor();
}
void ColorValuesWidget::SetColorProcessor(ColorProcessorPtr input_to_ref, ColorProcessorPtr ref_to_display, ColorProcessorPtr display_to_ref, ColorProcessorPtr ref_to_input)
{
input_to_ref_ = input_to_ref;
ref_to_display_ = ref_to_display;
display_to_ref_ = display_to_ref;
ref_to_input_ = ref_to_input;
UpdateValuesFromInput();
preview_->SetColorProcessor(input_to_ref_, ref_to_display_);
}
bool ColorValuesWidget::eventFilter(QObject *watcher, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress) {
// Should signal to Core to stop pixel sampling and to us to remove our event filter
bool use_this_color = true;
foreach (QWidget *w, ignore_pick_from_) {
if (w->underMouse()) {
use_this_color = false;
break;
}
}
if (use_this_color) {
picker_end_color_ = GetColor();
}
color_picker_btn_->setChecked(false);
return true;
} else if (event->type() == QEvent::KeyPress) {
QKeyEvent *key_ev = static_cast<QKeyEvent*>(event);
if (key_ev->key() == Qt::Key_Escape) {
color_picker_btn_->setChecked(false);
return true;
}
}
return QWidget::eventFilter(watcher, event);
}
void ColorValuesWidget::SetColor(const Color &c)
{
input_tab_->SetColor(c);
preview_->SetColor(c);
UpdateValuesFromInput();
}
void ColorValuesWidget::SetReferenceColor(const Color &c)
{
reference_tab_->SetColor(c);
UpdateValuesFromRef();
}
void ColorValuesWidget::UpdateValuesFromInput()
{
UpdateRefFromInput();
UpdateDisplayFromRef();
}
void ColorValuesWidget::UpdateValuesFromRef()
{
UpdateInputFromRef();
UpdateDisplayFromRef();
}
void ColorValuesWidget::UpdateValuesFromDisplay()
{
UpdateRefFromDisplay();
UpdateInputFromRef();
}
void ColorValuesWidget::ColorPickedBtnToggled(bool e)
{
Core::instance()->RequestPixelSamplingInViewers(e);
if (e) {
qApp->installEventFilter(this);
// Store current color in case it needs to be restored
picker_end_color_ = GetColor();
} else {
qApp->removeEventFilter(this);
// Restore original color (or use overridden color from eventFilter)
SetReferenceColor(picker_end_color_);
emit ColorChanged(input_tab_->GetColor());
}
}
void ColorValuesWidget::UpdateInputFromRef()
{
if (ref_to_input_) {
input_tab_->SetColor(ref_to_input_->ConvertColor(reference_tab_->GetColor()));
} else {
input_tab_->SetColor(reference_tab_->GetColor());
}
preview_->SetColor(input_tab_->GetColor());
emit ColorChanged(input_tab_->GetColor());
}
void ColorValuesWidget::UpdateDisplayFromRef()
{
if (ref_to_display_) {
display_tab_->SetColor(ref_to_display_->ConvertColor(reference_tab_->GetColor()));
} else {
display_tab_->SetColor(reference_tab_->GetColor());
}
}
void ColorValuesWidget::UpdateRefFromInput()
{
if (input_to_ref_) {
reference_tab_->SetColor(input_to_ref_->ConvertColor(input_tab_->GetColor()));
} else {
reference_tab_->SetColor(input_tab_->GetColor());
}
}
void ColorValuesWidget::UpdateRefFromDisplay()
{
if (display_to_ref_) {
reference_tab_->SetColor(display_to_ref_->ConvertColor(display_tab_->GetColor()));
} else {
reference_tab_->SetColor(display_tab_->GetColor());
}
}
const double ColorValuesTab::kLegacyMultiplier = 255.0;
ColorValuesTab::ColorValuesTab(bool with_legacy_option, QWidget *parent) :
QWidget(parent)
{
QGridLayout* layout = new QGridLayout(this);
int row = 0;
if (with_legacy_option) {
legacy_box_ = new QCheckBox(tr("Use legacy (8-bit) values"));
legacy_box_->setChecked(OLIVE_CONFIG("UseLegacyColorInInputTab").toBool());
connect(legacy_box_, &QCheckBox::clicked, this, &ColorValuesTab::LegacyChanged);
layout->addWidget(legacy_box_, row, 0, 1, 2);
row++;
} else {
legacy_box_ = nullptr;
}
sliders_.resize(3);
layout->addWidget(new QLabel(tr("Red")), row, 0);
red_slider_ = CreateColorSlider();
sliders_[0] = red_slider_;
layout->addWidget(red_slider_, row, 1);
row++;
layout->addWidget(new QLabel(tr("Green")), row, 0);
green_slider_ = CreateColorSlider();
sliders_[1] = green_slider_;
layout->addWidget(green_slider_, row, 1);
row++;
layout->addWidget(new QLabel(tr("Blue")), row, 0);
blue_slider_ = CreateColorSlider();
sliders_[2] = blue_slider_;
layout->addWidget(blue_slider_, row, 1);
row++;
hex_lbl_ = new QLabel(tr("Web"));
layout->addWidget(hex_lbl_, row, 0);
hex_slider_ = new StringSlider();
connect(hex_slider_, &StringSlider::ValueChanged, this, &ColorValuesTab::HexChanged);
layout->addWidget(hex_slider_, row, 1);
if (legacy_box_) {
LegacyChanged(AreSlidersLegacyValues());
}
}
Color ColorValuesTab::GetColor() const
{
return Color(GetRed(), GetGreen(), GetBlue());
}
void ColorValuesTab::SetColor(const Color &c)
{
SetRed(c.red());
SetGreen(c.green());
SetBlue(c.blue());
}
double ColorValuesTab::GetRed() const
{
return GetValueInternal(red_slider_);
}
double ColorValuesTab::GetGreen() const
{
return GetValueInternal(green_slider_);
}
double ColorValuesTab::GetBlue() const
{
return GetValueInternal(blue_slider_);
}
void ColorValuesTab::SetRed(double r)
{
SetValueInternal(red_slider_, r);
}
void ColorValuesTab::SetGreen(double g)
{
SetValueInternal(green_slider_, g);
}
void ColorValuesTab::SetBlue(double b)
{
SetValueInternal(blue_slider_, b);
}
double ColorValuesTab::GetValueInternal(FloatSlider *slider) const
{
double d = slider->GetValue();
if (AreSlidersLegacyValues()) {
d /= kLegacyMultiplier;
}
return d;
}
void ColorValuesTab::SetValueInternal(FloatSlider *slider, double v)
{
if (AreSlidersLegacyValues()) {
v *= kLegacyMultiplier;
}
slider->SetValue(v);
UpdateHex();
}
FloatSlider *ColorValuesTab::CreateColorSlider()
{
FloatSlider* fs = new FloatSlider();
fs->SetLadderElementCount(1);
connect(fs, &FloatSlider::ValueChanged, this, &ColorValuesTab::SliderChanged);
return fs;
}
void ColorValuesTab::SliderChanged()
{
emit ColorChanged(GetColor());
UpdateHex();
}
void ColorValuesTab::LegacyChanged(bool legacy)
{
OLIVE_CONFIG("UseLegacyColorInInputTab") = legacy;
double legacy_multiplier = legacy ? kLegacyMultiplier : 1.0/kLegacyMultiplier;
int decimal_places = legacy ? 0 : 5;
double drag_multiplier = legacy ? 1.0 : 0.01;
foreach (FloatSlider *s, sliders_) {
s->SetValue(s->GetValue() * legacy_multiplier);
s->SetDecimalPlaces(decimal_places);
s->SetDragMultiplier(drag_multiplier);
}
UpdateHex();
}
QString RGBValToString(double d)
{
QString s = QString::number(d);
if (!s.contains('.')) {
s.append(QStringLiteral(".0"));
}
return s;
}
void ColorValuesTab::UpdateHex()
{
if (AreSlidersLegacyValues()) {
double r = red_slider_->GetValue();
double g = green_slider_->GetValue();
double b = blue_slider_->GetValue();
if (r > kLegacyMultiplier || g > kLegacyMultiplier || b > kLegacyMultiplier) {
hex_slider_->SetValue(tr("(Invalid)"));
} else {
uint32_t rgb = (uint8_t(r) << 16) | (uint8_t(g) << 8) | uint8_t(b);
hex_slider_->SetValue(QStringLiteral("%1").arg(rgb, 6, 16, QLatin1Char('0')).toUpper());
}
} else {
hex_slider_->SetValue(QStringLiteral("rgb(%1, %2, %3)").arg(RGBValToString(red_slider_->GetValue()), RGBValToString(green_slider_->GetValue()), RGBValToString(blue_slider_->GetValue())));
}
}
bool ParseRGBString(QString s, double *r, double *g, double *b)
{
// Trim whitespace
s = s.trimmed();
s.remove(QStringLiteral("rgba"), Qt::CaseInsensitive);
s.remove(QStringLiteral("rgb"), Qt::CaseInsensitive);
s.remove('(');
s.remove(')');
QStringList vals = s.split(',');
if (vals.size() < 3) {
return false;
}
bool ok;
*r = vals.at(0).toDouble(&ok);
if (!ok) return false;
*g = vals.at(1).toDouble(&ok);
if (!ok) return false;
*b = vals.at(2).toDouble(&ok);
if (!ok) return false;
return true;
}
void ColorValuesTab::HexChanged(const QString &s)
{
bool ok;
uint32_t hex = s.toULong(&ok, 16);
if (ok) {
if (hex >= 0x1000000) {
hex >>= 8;
}
uint32_t r = (hex & 0xFF0000) >> 16;
uint32_t g = (hex & 0x00FF00) >> 8;
uint32_t b = (hex & 0x0000FF);
if (AreSlidersLegacyValues()) {
red_slider_->SetValue(r);
green_slider_->SetValue(g);
blue_slider_->SetValue(b);
} else {
red_slider_->SetValue(double(r)/kLegacyMultiplier);
green_slider_->SetValue(double(g)/kLegacyMultiplier);
blue_slider_->SetValue(double(b)/kLegacyMultiplier);
}
emit ColorChanged(GetColor());
} else {
// Attempt to parse rgb/rgba
double r, g, b;
if (ParseRGBString(s, &r, &g, &b)) {
if (AreSlidersLegacyValues()) {
red_slider_->SetValue(r*kLegacyMultiplier);
green_slider_->SetValue(g*kLegacyMultiplier);
blue_slider_->SetValue(b*kLegacyMultiplier);
} else {
red_slider_->SetValue(r);
green_slider_->SetValue(g);
blue_slider_->SetValue(b);
}
emit ColorChanged(GetColor());
}
}
// Conform string to our formatting
UpdateHex();
}
bool ColorValuesTab::AreSlidersLegacyValues() const
{
return legacy_box_ && legacy_box_->isChecked();
}
}
| 12,409
|
C++
|
.cpp
| 384
| 28.833333
| 191
| 0.705453
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,899
|
colorspacechooser.cpp
|
olive-editor_olive/app/widget/colorwheel/colorspacechooser.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorspacechooser.h"
#include <QGridLayout>
#include <QLabel>
namespace olive {
ColorSpaceChooser::ColorSpaceChooser(ColorManager* color_manager, bool enable_input_field, bool enable_display_fields, QWidget *parent):
QGroupBox(parent),
color_manager_(color_manager)
{
QGridLayout* layout = new QGridLayout(this);
setTitle(tr("Color Management"));
int row = 0;
if (enable_input_field) {
QString field_text;
if (enable_display_fields) {
// If the display fields are visible, identify this as the input
field_text = tr("Input:");
} else {
// Otherwise, this widget will essentially just serve as a list of standard color spaces
field_text = tr("Color Space:");
}
layout->addWidget(new QLabel(field_text), row, 0);
input_combobox_ = new QComboBox();
layout->addWidget(input_combobox_, row, 1);
QStringList input_spaces = color_manager->ListAvailableColorspaces();
foreach (const QString& s, input_spaces) {
input_combobox_->addItem(s);
}
if (!color_manager_->GetDefaultInputColorSpace().isEmpty()) {
input_combobox_->setCurrentText(color_manager_->GetDefaultInputColorSpace());
}
connect(input_combobox_, &QComboBox::currentTextChanged, this, &ColorSpaceChooser::ComboBoxChanged);
row++;
} else {
input_combobox_ = nullptr;
}
if (enable_display_fields) {
{
layout->addWidget(new QLabel(tr("Display:")), row, 0);
display_combobox_ = new QComboBox();
layout->addWidget(display_combobox_, row, 1);
QStringList display_spaces = color_manager->ListAvailableDisplays();
foreach (const QString& s, display_spaces) {
display_combobox_->addItem(s);
}
display_combobox_->setCurrentText(color_manager_->GetDefaultDisplay());
connect(display_combobox_, &QComboBox::currentTextChanged, this, &ColorSpaceChooser::ComboBoxChanged);
}
row++;
{
layout->addWidget(new QLabel(tr("View:")), row, 0);
view_combobox_ = new QComboBox();
layout->addWidget(view_combobox_, row, 1);
UpdateViews(display_combobox_->currentText());
connect(view_combobox_, &QComboBox::currentTextChanged, this, &ColorSpaceChooser::ComboBoxChanged);
}
row++;
{
layout->addWidget(new QLabel(tr("Look:")), row, 0);
look_combobox_ = new QComboBox();
layout->addWidget(look_combobox_, row, 1);
QStringList looks = color_manager->ListAvailableLooks();
look_combobox_->addItem(tr("(None)"), QString());
foreach (const QString& s, looks) {
look_combobox_->addItem(s, s);
}
connect(look_combobox_, &QComboBox::currentTextChanged, this, &ColorSpaceChooser::ComboBoxChanged);
}
} else {
display_combobox_ = nullptr;
view_combobox_ = nullptr;
look_combobox_ = nullptr;
}
}
QString ColorSpaceChooser::input() const
{
if (input_combobox_) {
return input_combobox_->currentText();
} else {
return QString();
}
}
ColorTransform ColorSpaceChooser::output() const
{
return ColorTransform(display_combobox_->currentText(),
view_combobox_->currentText(),
look_combobox_->currentIndex() == 0 ? QString() : look_combobox_->currentText());
}
void ColorSpaceChooser::set_input(const QString &s)
{
input_combobox_->setCurrentText(color_manager_->GetCompliantColorSpace(s));
}
void ColorSpaceChooser::set_output(const ColorTransform &out)
{
ColorTransform compliant = color_manager_->GetCompliantColorSpace(out);
display_combobox_->setCurrentText(compliant.display());
view_combobox_->setCurrentText(compliant.view());
if (compliant.look().isEmpty()) {
look_combobox_->setCurrentIndex(0);
} else {
look_combobox_->setCurrentText(compliant.look());
}
}
void ColorSpaceChooser::UpdateViews(const QString& display)
{
QString v = view_combobox_->currentText();
view_combobox_->clear();
QStringList views = color_manager_->ListAvailableViews(display);
foreach (const QString& s, views) {
view_combobox_->addItem(s);
}
if (views.contains(v)) {
// If we have the view we had before, set it again
view_combobox_->setCurrentText(v);
} else {
// Otherwise reset to default view for this display
view_combobox_->setCurrentText(color_manager_->GetDefaultView(display));
}
}
void ColorSpaceChooser::ComboBoxChanged()
{
if (sender() == display_combobox_) {
UpdateViews(display_combobox_->currentText());
}
if (input_combobox_) {
emit InputColorSpaceChanged(input());
}
if (display_combobox_) {
emit OutputColorSpaceChanged(output());
}
if (input_combobox_ && display_combobox_) {
emit ColorSpaceChanged(input(), output());
}
}
}
| 5,469
|
C++
|
.cpp
| 148
| 32.324324
| 136
| 0.703
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,900
|
colorwheelwidget.cpp
|
olive-editor_olive/app/widget/colorwheel/colorwheelwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "colorwheelwidget.h"
#include <QPainter>
#include <QtMath>
#include "node/node.h"
namespace olive {
#define M_180_OVER_PI 57.295791433133264917914229473464
#define M_RADIAN_TO_0_1 0.15915497620314795810531730409296
ColorWheelWidget::ColorWheelWidget(QWidget *parent) :
ColorSwatchWidget(parent),
val_(1.0f),
force_redraw_(false)
{
}
Color ColorWheelWidget::GetColorFromScreenPos(const QPoint &p) const
{
return GetColorFromTriangle(GetTriangleFromCoords(rect().center(), p));
}
void ColorWheelWidget::resizeEvent(QResizeEvent *e)
{
ColorSwatchWidget::resizeEvent(e);
emit DiameterChanged(GetDiameter());
}
void ColorWheelWidget::paintEvent(QPaintEvent *e)
{
ColorSwatchWidget::paintEvent(e);
int diameter = GetDiameter();
// Half diameter
int radius = diameter / 2;
if (cached_wheel_.width() != diameter || force_redraw_) {
cached_wheel_ = QPixmap(QSize(diameter, diameter));
cached_wheel_.fill(Qt::transparent);
force_redraw_ = false;
QPainter p(&cached_wheel_);
QPoint center(radius, radius);
for (int i=0;i<diameter;i++) {
for (int j=0;j<diameter;j++) {
Triangle tri = GetTriangleFromCoords(center, j, i);
if (tri.hypotenuse <= radius) {
Color managed = GetManagedColor(GetColorFromTriangle(tri));
QColor c = QtUtils::toQColor(managed);
// Very basic antialiasing around the edges of the wheel
qreal alpha = qMin(1.0, radius - tri.hypotenuse);
c.setAlphaF(alpha);
p.setPen(c);
p.drawPoint(i, j);
}
}
}
}
QPainter p(this);
// Draw wheel pixmap
int x, y;
if (width() == height()) {
x = 0;
y = 0;
} else if (width() > height()) {
x = (width() - height()) / 2;
y = 0;
} else {
x = 0;
y = (height() - width()) / 2;
}
p.drawPixmap(x, y, cached_wheel_);
// Draw selection
// Really rough algorithm for determining whether the selector UI should be white or black
int selector_radius = qMax(1, radius / 32);
p.setPen(QPen(GetUISelectorColor(), qMax(1, selector_radius / 4)));
p.setBrush(Qt::NoBrush);
p.drawEllipse(GetCoordsFromColor(GetSelectedColor()), selector_radius, selector_radius);
}
void ColorWheelWidget::SelectedColorChangedEvent(const Color &c, bool external)
{
if (external) {
force_redraw_ = true;
val_ = std::clamp(c.value(), 0.0f, 1.0f);
}
}
int ColorWheelWidget::GetDiameter() const
{
return qMin(width(), height());
}
qreal ColorWheelWidget::GetRadius() const
{
return GetDiameter() * 0.5;
}
ColorWheelWidget::Triangle ColorWheelWidget::GetTriangleFromCoords(const QPoint ¢er, const QPoint &p) const
{
return GetTriangleFromCoords(center, p.y(), p.x());
}
ColorWheelWidget::Triangle ColorWheelWidget::GetTriangleFromCoords(const QPoint ¢er, qreal y, qreal x) const
{
qreal opposite = y - center.y();
qreal adjacent = x - center.x();
qreal hypotenuse = qSqrt(qPow(adjacent, 2) + qPow(opposite, 2));
return {opposite, adjacent, hypotenuse};
}
Color ColorWheelWidget::GetColorFromTriangle(const ColorWheelWidget::Triangle &tri) const
{
qreal hue = qAtan2(tri.opposite, tri.adjacent) * M_180_OVER_PI + 180.0;
qreal sat = qMin(1.0, (tri.hypotenuse / GetRadius()));
return Color::fromHsv(hue, sat, val_);
}
QPoint ColorWheelWidget::GetCoordsFromColor(const Color &c) const
{
float hue, sat, val;
c.toHsv(&hue, &sat, &val);
qreal hypotenuse = sat * GetRadius();
qreal radian_angle = (hue - 180.0) / M_180_OVER_PI;
qreal opposite = qSin(radian_angle) * hypotenuse;
qreal adjacent = qCos(radian_angle) * hypotenuse;
QPoint pos(qRound(adjacent), qRound(opposite));
pos += rect().center();
return pos;
}
}
| 4,441
|
C++
|
.cpp
| 129
| 30.837209
| 112
| 0.710465
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,901
|
nodevaluetree.cpp
|
olive-editor_olive/app/widget/nodevaluetree/nodevaluetree.cpp
|
#include "nodevaluetree.h"
#include <QEvent>
#include "node/traverser.h"
namespace olive {
#define super QTreeWidget
NodeValueTree::NodeValueTree(QWidget *parent) :
super(parent)
{
setColumnWidth(0, 0);
setColumnCount(4);
QSizePolicy p = sizePolicy();
p.setHorizontalStretch(1);
setSizePolicy(p);
static const int kMinimumRows = 10;
setMinimumHeight(fontMetrics().height() * kMinimumRows);
Retranslate();
}
void NodeValueTree::SetNode(const NodeInput &input, const rational &time)
{
clear();
NodeTraverser traverser;
Node *connected_node = input.GetConnectedOutput();
NodeValueTable table = traverser.GenerateTable(connected_node, TimeRange(time, time));
int index = traverser.GenerateRowValueElementIndex(input.node(), input.input(), input.element(), &table);
for (int i=0; i<table.Count(); i++) {
const NodeValue &value = table.at(i);
QTreeWidgetItem *item = new QTreeWidgetItem(this);
Node::ValueHint hint({value.type()}, table.Count()-1-i, value.tag());
QRadioButton *radio = new QRadioButton(this);
radio->setProperty("input", QVariant::fromValue(input));
radio->setProperty("hint", QVariant::fromValue(hint));
if (i == index) {
radio->setChecked(true);
}
connect(radio, &QRadioButton::clicked, this, &NodeValueTree::RadioButtonChecked);
setItemWidget(item, 0, radio);
item->setText(1, NodeValue::GetPrettyDataTypeName(value.type()));
item->setText(2, NodeValue::ValueToString(value, false));
item->setText(3, value.source()->GetLabelAndName());
}
}
void NodeValueTree::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
Retranslate();
}
super::changeEvent(event);
}
void NodeValueTree::Retranslate()
{
setHeaderLabels({QString(), tr("Type"), tr("Value"), tr("Source")});
}
void NodeValueTree::RadioButtonChecked(bool e)
{
if (e) {
QRadioButton *btn = static_cast<QRadioButton*>(sender());
Node::ValueHint hint = btn->property("hint").value<Node::ValueHint>();
NodeInput input = btn->property("input").value<NodeInput>();
input.node()->SetValueHintForInput(input.input(), hint, input.element());
}
}
}
| 2,177
|
C++
|
.cpp
| 62
| 31.774194
| 107
| 0.718929
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,902
|
projectexplorericonview.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorericonview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorericonview.h"
namespace olive {
ProjectExplorerIconView::ProjectExplorerIconView(QWidget *parent) :
ProjectExplorerListViewBase(parent)
{
setViewMode(QListView::IconMode);
setItemDelegate(&delegate_);
}
}
| 950
|
C++
|
.cpp
| 23
| 38.565217
| 71
| 0.78735
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,903
|
projectexplorer.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorer.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorer.h"
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QProcess>
#include <QUrl>
#include <QVBoxLayout>
#include "common/define.h"
#include "core.h"
#include "dialog/footageproperties/footageproperties.h"
#include "dialog/sequence/sequence.h"
#include "projectexplorerundo.h"
#include "task/precache/precachetask.h"
#include "task/taskmanager.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
#include "node/nodeundo.h"
#include "window/mainwindow/mainwindow.h"
#include "window/mainwindow/mainwindowundo.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
ProjectExplorer::ProjectExplorer(QWidget *parent) :
QWidget(parent),
model_(this)
{
// Create layout
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
// Set up navigation bar
nav_bar_ = new ProjectExplorerNavigation(this);
connect(nav_bar_, &ProjectExplorerNavigation::SizeChanged, this, &ProjectExplorer::SizeChangedSlot);
connect(nav_bar_, &ProjectExplorerNavigation::DirectoryUpClicked, this, &ProjectExplorer::DirUpSlot);
layout->addWidget(nav_bar_);
// Set up stacked widget
stacked_widget_ = new QStackedWidget(this);
layout->addWidget(stacked_widget_);
// Set up sort filter proxy model
sort_model_.setSourceModel(&model_);
sort_model_.setFilterCaseSensitivity(Qt::CaseInsensitive);
sort_model_.setSortRole(ProjectViewModel::kInnerTextRole);
// Add tree view to stacked widget
tree_view_ = new ProjectExplorerTreeView(stacked_widget_);
tree_view_->setSortingEnabled(true);
tree_view_->sortByColumn(0, Qt::AscendingOrder);
tree_view_->setContextMenuPolicy(Qt::CustomContextMenu);
AddView(tree_view_);
// Add list view to stacked widget
list_view_ = new ProjectExplorerListView(stacked_widget_);
list_view_->setContextMenuPolicy(Qt::CustomContextMenu);
AddView(list_view_);
// Add icon view to stacked widget
icon_view_ = new ProjectExplorerIconView(stacked_widget_);
icon_view_->setContextMenuPolicy(Qt::CustomContextMenu);
AddView(icon_view_);
// Set default view to tree view
set_view_type(ProjectToolbar::TreeView);
// Set default icon size
SizeChangedSlot(kProjectIconSizeDefault);
connect(tree_view_, &ProjectExplorerTreeView::customContextMenuRequested, this, &ProjectExplorer::ShowContextMenu);
connect(list_view_, &ProjectExplorerListView::customContextMenuRequested, this, &ProjectExplorer::ShowContextMenu);
connect(icon_view_, &ProjectExplorerIconView::customContextMenuRequested, this, &ProjectExplorer::ShowContextMenu);
UpdateNavBarText();
}
const ProjectToolbar::ViewType &ProjectExplorer::view_type() const
{
return view_type_;
}
void ProjectExplorer::set_view_type(ProjectToolbar::ViewType type)
{
view_type_ = type;
// Set widget based on view type
switch (view_type_) {
case ProjectToolbar::TreeView:
stacked_widget_->setCurrentWidget(tree_view_);
nav_bar_->setVisible(false);
break;
case ProjectToolbar::ListView:
stacked_widget_->setCurrentWidget(list_view_);
nav_bar_->setVisible(true);
break;
case ProjectToolbar::IconView:
stacked_widget_->setCurrentWidget(icon_view_);
nav_bar_->setVisible(true);
break;
}
}
void ProjectExplorer::Edit(Node *item)
{
CurrentView()->edit(sort_model_.mapFromSource(model_.CreateIndexFromItem(item)));
}
void ProjectExplorer::AddView(QAbstractItemView *view)
{
view->setModel(&sort_model_);
view->setEditTriggers(QAbstractItemView::SelectedClicked);
connect(view, &QAbstractItemView::doubleClicked, this, &ProjectExplorer::ItemDoubleClickedSlot);
connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ProjectExplorer::ViewSelectionChanged);
connect(view, SIGNAL(DoubleClickedEmptyArea()), this, SLOT(ViewEmptyAreaDoubleClickedSlot()));
stacked_widget_->addWidget(view);
}
void ProjectExplorer::BrowseToFolder(const QModelIndex &index)
{
// Set appropriate views to this index
icon_view_->setRootIndex(index);
list_view_->setRootIndex(index);
// Set navbar text to folder's name
UpdateNavBarText();
// Set directory up enabled button based on whether we're in root or not
nav_bar_->set_dir_up_enabled(index.isValid());
}
int ProjectExplorer::ConfirmItemDeletion(Node* item)
{
QMessageBox msgbox(this);
msgbox.setWindowTitle(tr("Confirm Item Deletion"));
msgbox.setIcon(QMessageBox::Warning);
QStringList connected_nodes_names;
foreach (const Node::OutputConnection& connected, item->output_connections()) {
if (!dynamic_cast<Folder*>(connected.second.node())) {
connected_nodes_names.append(GetHumanReadableNodeName(connected.second.node()));
}
}
msgbox.setText(tr("The item \"%1\" is currently connected to the following nodes:\n\n"
"%2\n\n"
"Are you sure you wish to delete this footage?")
.arg(GetHumanReadableNodeName(item), connected_nodes_names.join('\n')));
// Set up buttons
msgbox.addButton(QMessageBox::Yes);
msgbox.addButton(QMessageBox::YesToAll);
msgbox.addButton(QMessageBox::No);
msgbox.addButton(QMessageBox::Cancel);
// Run messagebox
return msgbox.exec();
}
bool ProjectExplorer::DeleteItemsInternal(const QVector<Node*>& selected, bool& check_if_item_is_in_use, MultiUndoCommand* command)
{
for (int i=0; i<selected.size(); i++) {
// Delete sequences first
Node* node = selected.at(i);
bool can_delete_item = true;
if (check_if_item_is_in_use) {
foreach (const Node::OutputConnection& oc, node->output_connections()) {
Folder* folder_test = dynamic_cast<Folder*>(oc.second.node());
if (!folder_test) {
// This sequence outputs to SOMETHING, confirm the user if they want to delete this
int r = ConfirmItemDeletion(node);
switch (r) {
case QMessageBox::No:
can_delete_item = false;
break;
case QMessageBox::Cancel:
return false;
case QMessageBox::YesToAll:
check_if_item_is_in_use = false;
break;
}
}
}
}
if (can_delete_item) {
Sequence* sequence = dynamic_cast<Sequence*>(node);
if (sequence && Core::instance()->main_window()->IsSequenceOpen(sequence)) {
command->add_child(new CloseSequenceCommand(sequence));
}
if (node->folder()) {
command->add_child(new Folder::RemoveElementCommand(node->folder(), node));
}
command->add_child(new NodeRemoveWithExclusiveDependenciesAndDisconnect(node));
}
}
return true;
}
QString ProjectExplorer::GetHumanReadableNodeName(Node *node)
{
if (node->GetLabel().isEmpty()) {
return node->Name();
} else {
return tr("%1 (%2)").arg(node->GetLabel(), node->Name());
}
}
void ProjectExplorer::UpdateNavBarText()
{
QString absolute;
Folder* f = static_cast<Folder*>(sort_model_.mapToSource(list_view_->rootIndex()).internalPointer());
while (f && f != project()->root()) {
absolute.prepend(QStringLiteral("%1 / ").arg(f->GetLabel()));
f = f->folder();
}
absolute.prepend(QStringLiteral("/ "));
nav_bar_->set_text(absolute);
}
QAbstractItemView *ProjectExplorer::CurrentView() const
{
return static_cast<QAbstractItemView*>(stacked_widget_->currentWidget());
}
void ProjectExplorer::ViewEmptyAreaDoubleClickedSlot()
{
emit DoubleClickedItem(nullptr);
}
void ProjectExplorer::ItemDoubleClickedSlot(const QModelIndex &index)
{
// Retrieve source item from index
Node* i = static_cast<Node*>(sort_model_.mapToSource(index).internalPointer());
// If the item is a folder, browse to it
if (dynamic_cast<Folder*>(i) && (view_type() == ProjectToolbar::ListView || view_type() == ProjectToolbar::IconView)) {
BrowseToFolder(index);
}
// Emit a signal
emit DoubleClickedItem(i);
}
void ProjectExplorer::SizeChangedSlot(int s)
{
icon_view_->setGridSize(QSize(s, s));
list_view_->setIconSize(QSize(s, s));
}
void ProjectExplorer::DirUpSlot()
{
QModelIndex current_root = icon_view_->rootIndex();
if (current_root.isValid()) {
QModelIndex parent = current_root.parent();
BrowseToFolder(parent);
}
}
void ProjectExplorer::RenameSelectedItem()
{
auto indexes = CurrentView()->selectionModel()->selectedRows();
if (!indexes.empty()) {
CurrentView()->edit(indexes.first());
}
}
void ProjectExplorer::SetSearchFilter(const QString &s)
{
sort_model_.setFilterFixedString(s);
}
void ProjectExplorer::ShowContextMenu()
{
Menu menu;
Menu new_menu;
context_menu_items_ = SelectedItems();
if (context_menu_items_.isEmpty()) {
// Items to show if no items are selected
// "New" menu
new_menu.setTitle(tr("&New"));
MenuShared::instance()->AddItemsForNewMenu(&new_menu);
menu.addMenu(&new_menu);
// "Import" action
QAction* import_action = menu.addAction(tr("&Import..."));
connect(import_action, &QAction::triggered, Core::instance(), &Core::DialogImportShow);
} else {
// Actions to add when only one item is selected
if (context_menu_items_.size() == 1) {
Node* context_menu_item = context_menu_items_.first();
if (dynamic_cast<Folder*>(context_menu_item)) {
QAction* open_in_new_tab = menu.addAction(tr("Open in New Tab"));
connect(open_in_new_tab, &QAction::triggered, this, &ProjectExplorer::OpenContextMenuItemInNewTab);
QAction* open_in_new_window = menu.addAction(tr("Open in New Window"));
connect(open_in_new_window, &QAction::triggered, this, &ProjectExplorer::OpenContextMenuItemInNewWindow);
} else if (dynamic_cast<Footage*>(context_menu_item)) {
QString reveal_text;
#if defined(Q_OS_WINDOWS)
reveal_text = tr("Reveal in Explorer");
#elif defined(Q_OS_MAC)
reveal_text = tr("Reveal in Finder");
#else
reveal_text = tr("Reveal in File Manager");
#endif
QAction* reveal_action = menu.addAction(reveal_text);
connect(reveal_action, &QAction::triggered, this, &ProjectExplorer::RevealSelectedFootage);
QAction *replace_action = menu.addAction(tr("Replace Footage"));
connect(replace_action, &QAction::triggered, this, &ProjectExplorer::ReplaceSelectedFootage);
}
menu.addSeparator();
}
bool all_items_are_footage = true;
bool all_items_have_video_streams = true;
bool all_items_are_footage_or_sequence = true;
foreach (Node* i, context_menu_items_) {
Footage* footage_cast_test = dynamic_cast<Footage*>(i);
Sequence* sequence_cast_test = dynamic_cast<Sequence*>(i);
if (footage_cast_test && !footage_cast_test->HasEnabledVideoStreams()) {
all_items_have_video_streams = false;
}
if (!footage_cast_test) {
all_items_are_footage = false;
}
if (!footage_cast_test && !sequence_cast_test) {
all_items_are_footage_or_sequence = false;
}
}
if (all_items_are_footage && all_items_have_video_streams) {
Menu* proxy_menu = new Menu(tr("Pre-Cache"), &menu);
menu.addMenu(proxy_menu);
QVector<Sequence*> sequences = project()->root()->ListChildrenOfType<Sequence>();
if (sequences.isEmpty()) {
QAction* a = proxy_menu->addAction(tr("No sequences exist in project"));
a->setEnabled(false);
} else {
foreach (Sequence* i, sequences) {
QAction* a = proxy_menu->addAction(tr("For \"%1\"").arg(i->GetLabel()));
a->setData(QtUtils::PtrToValue(i));
}
connect(proxy_menu, &Menu::triggered, this, &ProjectExplorer::ContextMenuStartProxy);
}
}
Q_UNUSED(all_items_are_footage_or_sequence)
if (context_menu_items_.size() == 1) {
menu.addSeparator();
auto rename_action = menu.addAction(tr("Rename"));
connect(rename_action, &QAction::triggered, this, &ProjectExplorer::RenameSelectedItem);
}
auto delete_action = menu.addAction(tr("Delete"));
connect(delete_action, &QAction::triggered, this, &ProjectExplorer::DeleteSelected);
if (context_menu_items_.size() == 1) {
menu.addSeparator();
QAction* properties_action = menu.addAction(tr("P&roperties"));
connect(properties_action, &QAction::triggered, this, &ProjectExplorer::ShowItemPropertiesDialog);
}
}
menu.exec(QCursor::pos());
}
void ProjectExplorer::ShowItemPropertiesDialog()
{
Node* sel = context_menu_items_.first();
// FIXME: Support for multiple items
if (dynamic_cast<Footage*>(sel)) {
FootagePropertiesDialog fpd(this, static_cast<Footage*>(sel));
fpd.exec();
} else if (dynamic_cast<Folder*>(sel)) {
Core::instance()->LabelNodes(context_menu_items_);
} else if (dynamic_cast<Sequence*>(sel)) {
SequenceDialog sd(static_cast<Sequence*>(sel), SequenceDialog::kExisting, this);
sd.exec();
}
}
void ProjectExplorer::RevealSelectedFootage()
{
Footage* footage = static_cast<Footage*>(context_menu_items_.first());
#if defined(Q_OS_WINDOWS)
// Explorer
QStringList args;
args << "/select," << QDir::toNativeSeparators(footage->filename());
QProcess::startDetached("explorer", args);
#elif defined(Q_OS_MAC)
QStringList args;
args << "-e";
args << "tell application \"Finder\"";
args << "-e";
args << "activate";
args << "-e";
args << "select POSIX file \""+footage->filename()+"\"";
args << "-e";
args << "end tell";
QProcess::startDetached("osascript", args);
#else
QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(footage->filename()).dir().absolutePath()));
#endif
}
void ProjectExplorer::ReplaceSelectedFootage()
{
Footage* footage = static_cast<Footage*>(context_menu_items_.first());
QString file = QFileDialog::getOpenFileName(this, tr("Replace Footage"));
if (!file.isEmpty()) {
auto p = new MultiUndoCommand();
// Change filename parameter
p->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(footage, Footage::kFilenameInput)), file));
if (QFileInfo(footage->filename()).fileName() == footage->GetLabel()) {
// Footage label == filename, change label too
p->add_child(new NodeRenameCommand(footage, QFileInfo(file).fileName()));
}
Core::instance()->undo_stack()->push(p, tr("Replaced Footage"));
}
}
void ProjectExplorer::OpenContextMenuItemInNewTab()
{
Core::instance()->main_window()->OpenFolder(static_cast<Folder*>(context_menu_items_.first()), false);
}
void ProjectExplorer::OpenContextMenuItemInNewWindow()
{
Core::instance()->main_window()->OpenFolder(static_cast<Folder*>(context_menu_items_.first()), true);
}
void ProjectExplorer::ContextMenuStartProxy(QAction *a)
{
Sequence* sequence = QtUtils::ValueToPtr<Sequence>(a->data());
// To get here, the `context_menu_items_` must be all kFootage
foreach (Node* item, context_menu_items_) {
Footage* f = static_cast<Footage*>(item);
int sz = f->InputArraySize(Footage::kVideoParamsInput);
for (int j=0; j<sz; j++) {
VideoParams vp = f->GetVideoParams(j);
if (vp.enabled()) {
// Start a background task for proxying
PreCacheTask* proxy_task = new PreCacheTask(f, j, sequence);
TaskManager::instance()->AddTask(proxy_task);
}
}
}
}
void ProjectExplorer::ViewSelectionChanged()
{
QItemSelectionModel *model = static_cast<QItemSelectionModel *>(sender());
QModelIndexList selection = model->selectedIndexes();
QVector<Node *> nodes;
foreach (const QModelIndex &index, selection) {
Node *sel = static_cast<Node*>(sort_model_.mapToSource(index).internalPointer());
if (!nodes.contains(sel)) {
nodes.append(sel);
}
}
if (nodes.isEmpty()) {
nodes.append(get_root());
}
emit SelectionChanged(nodes);
}
Project *ProjectExplorer::project() const
{
return model_.project();
}
void ProjectExplorer::set_project(Project *p)
{
model_.set_project(p);
}
Folder *ProjectExplorer::get_root() const
{
QModelIndex root_index = sort_model_.mapToSource(tree_view_->rootIndex());
if (!root_index.isValid()) {
return project()->root();
}
return static_cast<Folder *>(root_index.internalPointer());
}
void ProjectExplorer::set_root(Folder *item)
{
QModelIndex index = sort_model_.mapFromSource(model_.CreateIndexFromItem(item));
BrowseToFolder(index);
tree_view_->setRootIndex(index);
}
QVector<Node *> ProjectExplorer::SelectedItems() const
{
// Determine which view is active and get its selected indexes
QModelIndexList index_list = CurrentView()->selectionModel()->selectedRows();
// Convert indexes to item objects
QVector<Node*> selected_items;
for (int i=0;i<index_list.size();i++) {
QModelIndex index = sort_model_.mapToSource(index_list.at(i));
Node* item = static_cast<Node*>(index.internalPointer());
selected_items.append(item);
}
return selected_items;
}
Folder *ProjectExplorer::GetSelectedFolder() const
{
if (project() == nullptr) {
return nullptr;
}
Folder* folder = nullptr;
// Get the selected items from the panel
QVector<Node*> selected_items = SelectedItems();
// Heuristic for finding the selected folder:
//
// - If `folder` is nullptr, we set the first folder we find. Either the item itself if it's a folder, or the
// item's parent.
// - Otherwise, if all folders found are the same, we'll use that to import into.
// - If more than one folder is found, we play it safe and import into the root folder
for (int i=0;i<selected_items.size();i++) {
Node* sel_item = selected_items.at(i);
// If this item is not a folder, presumably it's parent is
if (!dynamic_cast<Folder*>(sel_item)) {
sel_item = sel_item->folder();
}
if (folder == nullptr) {
// If the folder is nullptr, cache it as this folder
folder = static_cast<Folder*>(sel_item);
} else if (folder != sel_item) {
// If not, we've already cached a folder so we check if it's the same
// If it isn't, we "play it safe" and use the root folder
folder = nullptr;
break;
}
}
// If we didn't pick up a folder from the heuristic above for whatever reason, use root
if (folder == nullptr) {
folder = project()->root();
}
return folder;
}
ProjectViewModel *ProjectExplorer::model()
{
return &model_;
}
void ProjectExplorer::SelectAll()
{
CurrentView()->selectAll();
}
void ProjectExplorer::DeselectAll()
{
CurrentView()->selectionModel()->clearSelection();
}
void ProjectExplorer::DeleteSelected()
{
QVector<Node*> selected = SelectedItems();
if (selected.isEmpty()) {
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
bool check_if_item_is_in_use = true;
if (DeleteItemsInternal(selected, check_if_item_is_in_use, command)) {
Core::instance()->undo_stack()->push(command, tr("Deleted %1 Item(s)").arg(selected.size()));
} else {
delete command;
}
}
bool ProjectExplorer::SelectItem(Node *n, bool deselect_all_first)
{
if (deselect_all_first) {
DeselectAll();
}
QModelIndex index = model_.CreateIndexFromItem(n);
if (index.isValid()) {
index = sort_model_.mapFromSource(index);
QModelIndex parent = index.parent();
if (view_type() == ProjectToolbar::TreeView) {
// Expand all folders until this index is visible
while (parent.isValid()) {
tree_view_->expand(parent);
parent = parent.parent();
}
} else {
BrowseToFolder(parent);
}
CurrentView()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows);
return true;
}
return false;
}
}
| 20,435
|
C++
|
.cpp
| 549
| 33.098361
| 134
| 0.707197
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,904
|
projectexplorerlistview.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorerlistview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorerlistview.h"
namespace olive {
ProjectExplorerListView::ProjectExplorerListView(QWidget *parent) :
ProjectExplorerListViewBase(parent)
{
setViewMode(QListView::ListMode);
setItemDelegate(&delegate_);
}
}
| 950
|
C++
|
.cpp
| 23
| 38.565217
| 71
| 0.78735
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,905
|
projectviewmodel.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectviewmodel.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectviewmodel.h"
#include <QDebug>
#include <QMimeData>
#include <QUrl>
#include "common/qtutils.h"
#include "core.h"
#include "node/nodeundo.h"
namespace olive {
ProjectViewModel::ProjectViewModel(QObject *parent) :
QAbstractItemModel(parent),
project_(nullptr)
{
}
Project *ProjectViewModel::project() const
{
return project_;
}
void ProjectViewModel::set_project(Project *p)
{
beginResetModel();
if (project_) {
DisconnectItem(project_->root());
}
project_ = p;
if (project_) {
ConnectItem(project_->root());
}
endResetModel();
}
QModelIndex ProjectViewModel::index(int row, int column, const QModelIndex &parent) const
{
// I'm actually not 100% sure what this does, but it seems logical and was in the earlier code
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
// Get the parent object, we assume it's a folder since only folders can have children
Folder* item_parent = static_cast<Folder*>(GetItemObjectFromIndex(parent));
// Return an index to this object
return createIndex(row, column, item_parent->item_child(row));
}
QModelIndex ProjectViewModel::parent(const QModelIndex &child) const
{
// Get the Item object from the index
Node* item = GetItemObjectFromIndex(child);
// Get Item's parent object
Folder* par = item->folder();
// If the parent is the root, return an empty index
if (par == project_->root()) {
return QModelIndex();
}
// Otherwise return a true index to its parent
int parent_index = IndexOfChild(par);
// Make sure the index is valid (there's no reason it shouldn't be)
Q_ASSERT(parent_index > -1);
// Return an index to the parent
return createIndex(parent_index, 0, par);
}
int ProjectViewModel::rowCount(const QModelIndex &parent) const
{
// If there's no project, there are obviously no items to show
if (project_ == nullptr) {
return 0;
}
// If the index is the root, return the root child count
if (parent == QModelIndex()) {
return project_->root()->item_child_count();
}
// Otherwise, the index must contain a valid pointer, so we just return its child count
return static_cast<Folder*>(GetItemObjectFromIndex(parent))->item_child_count();
}
int ProjectViewModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
// Not strictly necessary, but a decent visual cue that there's no project currently active
if (project_ == nullptr) {
return 0;
}
return kColumnCount;
}
QVariant ProjectViewModel::data(const QModelIndex &index, int role) const
{
Node* internal_item = GetItemObjectFromIndex(index);
ColumnType column_type = static_cast<ColumnType>(index.column());
switch (role) {
case Qt::DisplayRole:
case kInnerTextRole:
{
// Standard text role
switch (column_type) {
case kName:
return internal_item->GetLabel();
case kDuration:
return internal_item->data(Node::DURATION);
case kRate:
return internal_item->data(Node::FREQUENCY_RATE);
case kLastModified:
case kCreatedTime:
{
qint64 using_time = (column_type == kLastModified) ? internal_item->data(Node::MODIFIED_TIME).toLongLong() : internal_item->data(Node::CREATED_TIME).toLongLong();
if (using_time == 0) {
// 0 is the null value, return nothing
break;
}
QVariant ret;
if (role == kInnerTextRole) {
// Use time value directly for correct sorting
ret = using_time;
} else {
// Display role, format to a human readable string
ret = QtUtils::GetFormattedDateTime(QDateTime::fromSecsSinceEpoch(using_time));
}
return ret;
}
case kColumnCount:
break;
}
}
break;
case Qt::EditRole:
if (column_type == kName) {
return internal_item->GetLabel();
}
break;
case Qt::DecorationRole:
// If this is the first column, return the Item's icon
if (column_type == kName) {
return internal_item->data(Node::ICON);
}
break;
case Qt::ToolTipRole:
return internal_item->data(Node::TOOLTIP);
}
return QVariant();
}
QVariant ProjectViewModel::headerData(int section, Qt::Orientation orientation, int role) const
{
// Check if we need text data (DisplayRole) and orientation is horizontal
// FIXME I'm not 100% sure what happens if the orientation is vertical/if that check is necessary
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
ColumnType column_type = static_cast<ColumnType>(section);
// Return the name based on the column's current type
switch (column_type) {
case kName:
return tr("Name");
case kDuration:
return tr("Duration");
case kRate:
return tr("Rate");
case kLastModified:
return tr("Modified");
case kCreatedTime:
return tr("Created");
case kColumnCount:
break;
}
}
return QAbstractItemModel::headerData(section, orientation, role);
}
bool ProjectViewModel::hasChildren(const QModelIndex &parent) const
{
// If it's a folder, we always return TRUE in order to always show the "expand triangle" icon,
// even when there are no "physical" children
Node* item = GetItemObjectFromIndex(parent);
return dynamic_cast<Folder*>(item);
}
bool ProjectViewModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
// The name is editable
if (index.isValid() && index.column() == kName && role == Qt::EditRole) {
Node* item = GetItemObjectFromIndex(index);
QString new_name = value.toString();
if (!new_name.isEmpty()) {
NodeRenameCommand* nrc = new NodeRenameCommand();
nrc->AddNode(item, value.toString());
Core::instance()->undo_stack()->push(nrc, tr("Renamed Item \"%1\" to \"%2\"").arg(item->GetLabel(), new_name));
return true;
}
}
return false;
}
bool ProjectViewModel::canFetchMore(const QModelIndex &parent) const
{
// Use the same hack that always returns true with folders so the expand triangle is always visible
return hasChildren(parent);
}
Qt::ItemFlags ProjectViewModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
// Allow dropping files from external sources
return Qt::ItemIsDropEnabled;
}
Qt::ItemFlags f = Qt::ItemIsDragEnabled | QAbstractItemModel::flags(index);
if (dynamic_cast<Folder*>(GetItemObjectFromIndex(index))) {
f |= Qt::ItemIsDropEnabled;
}
// If the column is the kName column, that means it's editable
if (index.column() == kName) {
f |= Qt::ItemIsEditable;
}
return f;
}
QStringList ProjectViewModel::mimeTypes() const
{
// Allow data from this model and a file list from external sources
return {Project::kItemMimeType, QStringLiteral("text/uri-list")};
}
QMimeData *ProjectViewModel::mimeData(const QModelIndexList &indexes) const
{
// Compliance with Qt standard
if (indexes.isEmpty()) {
return nullptr;
}
// Encode mime data for the rows/items that were dragged
QMimeData* data = new QMimeData();
// Use QDataStream to stream the item data into a byte array
QByteArray encoded_data;
QDataStream stream(&encoded_data, QIODevice::WriteOnly);
// The indexes list includes indexes for each column which we don't use. To make sure each row only gets sent *once*,
// we keep a list of dragged items
QVector<void*> dragged_items;
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
// Check if we've dragged this item before
if (!dragged_items.contains(index.internalPointer())) {
// If not, add it to the stream (and also keep track of it in the vector)
Node *item = static_cast<Node*>(index.internalPointer());
QVector<Track::Reference> streams;
if (ViewerOutput* footage = dynamic_cast<ViewerOutput*>(item)) {
streams = footage->GetEnabledStreamsAsReferences();
}
stream << streams << reinterpret_cast<quintptr>(item);
dragged_items.append(item);
}
}
}
// Set byte array as the mime data and return the mime data
data->setData(Project::kItemMimeType, encoded_data);
return data;
}
bool ProjectViewModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &drop)
{
// Default recommended checks from https://doc.qt.io/qt-5/model-view-programming.html#using-drag-and-drop-with-item-views
if (!canDropMimeData(data, action, row, column, drop)) {
return false;
}
if (action == Qt::IgnoreAction) {
return true;
}
// Probe mime data for its format
QStringList mime_formats = data->formats();
if (mime_formats.contains(Project::kItemMimeType)) {
// Data is drag/drop data from this model
QByteArray model_data = data->data(Project::kItemMimeType);
// Use QDataStream to deserialize the data
QDataStream stream(&model_data, QIODevice::ReadOnly);
// Get the Item object that the items were dropped on
Folder* drop_location = dynamic_cast<Folder*>(GetItemObjectFromIndex(drop));
// If this is not a folder, we cannot drop these items here
if (!drop_location) {
return false;
}
// Variables to deserialize into
quintptr item_ptr;
QList<Track::Reference> streams;
// Loop through all data
MultiUndoCommand* move_command = new MultiUndoCommand();
int count = 0;
while (!stream.atEnd()) {
stream >> streams >> item_ptr;
Node* item = reinterpret_cast<Node*>(item_ptr);
// Check if Item is already the drop location or if its parent is the drop location, in which case this is a
// no-op
if (item != drop_location && item->folder() != drop_location
&& (!dynamic_cast<Folder*>(item) || !ItemIsParentOfChild(static_cast<Folder*>(item), drop_location))) {
move_command->add_child(new NodeEdgeRemoveCommand(item, NodeInput(item->folder(), Folder::kChildInput, item->folder()->index_of_child_in_array(item))));
move_command->add_child(new FolderAddChild(drop_location, item));
count++;
}
}
Core::instance()->undo_stack()->push(move_command, tr("Move %1 Item(s)").arg(count));
return true;
} else if (mime_formats.contains(QStringLiteral("text/uri-list"))) {
// We received a list of files
QByteArray file_data = data->data(QStringLiteral("text/uri-list"));
// Use text stream to parse (just an easy way of sifting through line breaks
QTextStream stream(&file_data);
// Convert QByteArray to QStringList (which Core takes for importing)
QStringList urls;
while (!stream.atEnd()) {
QUrl url = stream.readLine();
if (!url.isEmpty()) {
urls.append(url.toLocalFile());
}
}
// Get folder dropped onto
Node* drop_item = GetItemObjectFromIndex(drop);
// If we didn't drop onto an item, find the nearest parent folder (should eventually terminate at root either way)
if (!dynamic_cast<Folder*>(drop_item)) {
drop_item = drop_item->folder();
if (!drop_item) {
// Failed to find folder to place this in
return false;
}
}
// Trigger an import
Core::instance()->ImportFiles(urls, static_cast<Folder*>(drop_item));
return true;
}
return false;
}
int ProjectViewModel::IndexOfChild(Node *item) const
{
// Find parent's index within its own parent
Folder* parent = item->folder();
if (parent) {
return parent->index_of_child(item);
}
return -1;
}
Node *ProjectViewModel::GetItemObjectFromIndex(const QModelIndex &index) const
{
if (index.isValid()) {
return static_cast<Node*>(index.internalPointer());
}
return project_ ? project_->root() : nullptr;
}
bool ProjectViewModel::ItemIsParentOfChild(Folder *parent, Node *child) const
{
// Loop through parent hierarchy checking if `parent` is one of its parents
do {
child = child->folder();
if (parent == child) {
return true;
}
} while (child != nullptr);
return false;
}
void ProjectViewModel::ConnectItem(Node *n)
{
connect(n, &Node::LabelChanged, this, &ProjectViewModel::ItemRenamed);
Folder* f = dynamic_cast<Folder*>(n);
if (f) {
connect(f, &Folder::BeginInsertItem, this, &ProjectViewModel::FolderBeginInsertItem);
connect(f, &Folder::EndInsertItem, this, &ProjectViewModel::FolderEndInsertItem);
connect(f, &Folder::BeginRemoveItem, this, &ProjectViewModel::FolderBeginRemoveItem);
connect(f, &Folder::EndRemoveItem, this, &ProjectViewModel::FolderEndRemoveItem);
foreach (Node* c, f->children()) {
ConnectItem(c);
}
}
}
void ProjectViewModel::DisconnectItem(Node *n)
{
disconnect(n, &Node::LabelChanged, this, &ProjectViewModel::ItemRenamed);
Folder* f = dynamic_cast<Folder*>(n);
if (f) {
disconnect(f, &Folder::BeginInsertItem, this, &ProjectViewModel::FolderBeginInsertItem);
disconnect(f, &Folder::EndInsertItem, this, &ProjectViewModel::FolderEndInsertItem);
disconnect(f, &Folder::BeginRemoveItem, this, &ProjectViewModel::FolderBeginRemoveItem);
disconnect(f, &Folder::EndRemoveItem, this, &ProjectViewModel::FolderEndRemoveItem);
foreach (Node* c, f->children()) {
DisconnectItem(c);
}
}
}
void ProjectViewModel::FolderBeginInsertItem(Node *n, int insert_index)
{
Folder* folder = static_cast<Folder*>(sender());
ConnectItem(n);
QModelIndex index;
if (folder != project_->root()) {
index = CreateIndexFromItem(folder);
}
beginInsertRows(index, insert_index, insert_index);
}
void ProjectViewModel::FolderEndInsertItem()
{
endInsertRows();
}
void ProjectViewModel::FolderBeginRemoveItem(Node *n, int child_index)
{
Folder* folder = static_cast<Folder*>(sender());
DisconnectItem(n);
QModelIndex index;
if (folder != project_->root()) {
index = CreateIndexFromItem(folder);
}
beginRemoveRows(index, child_index, child_index);
}
void ProjectViewModel::FolderEndRemoveItem()
{
endRemoveRows();
}
void ProjectViewModel::ItemRenamed()
{
Node* item = static_cast<Node*>(sender());
QModelIndex index = CreateIndexFromItem(item);
emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole});
}
QModelIndex ProjectViewModel::CreateIndexFromItem(Node *item, int column)
{
return createIndex(IndexOfChild(item), column, item);
}
}
| 14,989
|
C++
|
.cpp
| 418
| 31.777512
| 168
| 0.707927
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,906
|
projectexplorertreeview.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorertreeview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorertreeview.h"
#include <QMouseEvent>
namespace olive {
ProjectExplorerTreeView::ProjectExplorerTreeView(QWidget *parent) :
QTreeView(parent)
{
// Set selection mode (allows multiple item selection)
setSelectionMode(QAbstractItemView::ExtendedSelection);
// Allow dragging and dropping
setDragDropMode(QAbstractItemView::DragDrop);
// Enable dragging
setDragEnabled(true);
// Allow dropping from external sources
setAcceptDrops(true);
// Set context menu to emit a signal
setContextMenuPolicy(Qt::CustomContextMenu);
}
void ProjectExplorerTreeView::mouseDoubleClickEvent(QMouseEvent *event)
{
// Perform default double click functions
QTreeView::mouseDoubleClickEvent(event);
// QAbstractItemView already has a doubleClicked() signal, but we emit another here for double clicking empty space
if (!indexAt(event->pos()).isValid()) {
emit DoubleClickedEmptyArea();
}
}
}
| 1,649
|
C++
|
.cpp
| 41
| 37.365854
| 117
| 0.78706
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,907
|
projectexplorericonviewitemdelegate.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorericonviewitemdelegate.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorericonviewitemdelegate.h"
#include <QPainter>
#include "common/qtutils.h"
namespace olive {
ProjectExplorerIconViewItemDelegate::ProjectExplorerIconViewItemDelegate(QObject *parent) :
QStyledItemDelegate (parent)
{
}
QSize ProjectExplorerIconViewItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &) const
{
Q_UNUSED(option)
return QSize(256, 256);
}
void ProjectExplorerIconViewItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QFontMetrics fm = painter->fontMetrics();
QRect img_rect = option.rect;
// Draw Text
if (fm.height() < option.rect.height() / 2) {
img_rect.setHeight(img_rect.height()-fm.height());
QRect text_rect = option.rect;
text_rect.setTop(text_rect.top() + option.rect.height() - fm.height());
QColor text_bgcolor;
QColor text_fgcolor;
if (option.state & QStyle::State_Selected) {
text_bgcolor = option.palette.highlight().color();
text_fgcolor = option.palette.highlightedText().color();
} else {
text_bgcolor = Qt::white;
text_fgcolor = Qt::black;
}
painter->fillRect(text_rect, text_bgcolor);
painter->setPen(text_fgcolor);
QString duration_str = index.data(Qt::UserRole).toString();
int timecode_width = QtUtils::QFontMetricsWidth(fm, duration_str);
int max_name_width = option.rect.width();
if (timecode_width < option.rect.width() / 2) {
painter->drawText(text_rect, static_cast<int>(Qt::AlignBottom | Qt::AlignRight), index.data(Qt::UserRole).toString());
max_name_width -= timecode_width;
}
painter->drawText(text_rect,
static_cast<int>(Qt::AlignBottom | Qt::AlignLeft),
fm.elidedText(index.data(Qt::DisplayRole).toString(), Qt::ElideRight, max_name_width));
}
// Draw image
QIcon ico = index.data(Qt::DecorationRole).value<QIcon>();
QSize icon_size = ico.actualSize(img_rect.size());
img_rect = QRect(img_rect.x() + (img_rect.width() / 2 - icon_size.width() / 2),
img_rect.y() + (img_rect.height() / 2 - icon_size.height() / 2),
icon_size.width(),
icon_size.height());
painter->drawPixmap(img_rect, ico.pixmap(icon_size));
if (option.state & QStyle::State_Selected) {
QColor highlight_color = option.palette.highlight().color();
highlight_color.setAlphaF(0.5);
painter->setCompositionMode(QPainter::CompositionMode_SourceAtop);
painter->fillRect(img_rect, highlight_color);
}
}
}
| 3,298
|
C++
|
.cpp
| 74
| 39.527027
| 134
| 0.70776
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,908
|
projectexplorerlistviewbase.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorerlistviewbase.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorerlistviewbase.h"
#include <QMouseEvent>
namespace olive {
ProjectExplorerListViewBase::ProjectExplorerListViewBase(QWidget *parent) :
QListView(parent)
{
// FIXME Is this necessary?
setMovement(QListView::Free);
// Set selection mode (allows multiple item selection)
setSelectionMode(QAbstractItemView::ExtendedSelection);
// Set resize mode
setResizeMode(QListView::Adjust);
// Set widget to emit a signal on right click
setContextMenuPolicy(Qt::CustomContextMenu);
}
void ProjectExplorerListViewBase::mouseDoubleClickEvent(QMouseEvent *event)
{
// Cache here so if the index becomes invalid after the base call, we still know the truth
bool item_at_location = indexAt(event->pos()).isValid();
// Perform default double click functions
QListView::mouseDoubleClickEvent(event);
// QAbstractItemView already has a doubleClicked() signal, but we emit another here for double clicking empty space
if (!item_at_location) {
emit DoubleClickedEmptyArea();
}
}
}
| 1,738
|
C++
|
.cpp
| 41
| 39.536585
| 117
| 0.783462
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,909
|
projectexplorernavigation.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorernavigation.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorernavigation.h"
#include <QEvent>
#include <QHBoxLayout>
#include "common/define.h"
#include "ui/icons/icons.h"
namespace olive {
ProjectExplorerNavigation::ProjectExplorerNavigation(QWidget *parent) :
QWidget(parent)
{
// Create widget layout
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
// Create "directory up" button
dir_up_btn_ = new QPushButton(this);
dir_up_btn_->setEnabled(false);
dir_up_btn_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
layout->addWidget(dir_up_btn_);
connect(dir_up_btn_, SIGNAL(clicked(bool)), this, SIGNAL(DirectoryUpClicked()));
// Create directory tree label
dir_lbl_ = new QLabel(this);
dir_lbl_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
layout->addWidget(dir_lbl_);
// Create size slider
size_slider_ = new QSlider(this);
size_slider_->setOrientation(Qt::Horizontal);
size_slider_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
layout->addWidget(size_slider_);
connect(size_slider_, SIGNAL(valueChanged(int)), this, SIGNAL(SizeChanged(int)));
Retranslate();
UpdateIcons();
}
void ProjectExplorerNavigation::set_text(const QString &s)
{
dir_lbl_->setText(s);
}
void ProjectExplorerNavigation::set_dir_up_enabled(bool e)
{
dir_up_btn_->setEnabled(e);
}
void ProjectExplorerNavigation::set_size_value(int s)
{
size_slider_->setValue(s);
}
void ProjectExplorerNavigation::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
Retranslate();
} else if (e->type() == QEvent::StyleChange) {
UpdateIcons();
}
QWidget::changeEvent(e);
}
void ProjectExplorerNavigation::Retranslate()
{
dir_up_btn_->setToolTip(tr("Go to parent folder"));
}
void ProjectExplorerNavigation::UpdateIcons()
{
dir_up_btn_->setIcon(icon::DirUp);
size_slider_->setMinimum(kProjectIconSizeMinimum);
size_slider_->setMaximum(kProjectIconSizeMaximum);
size_slider_->setValue(kProjectIconSizeDefault);
}
}
| 2,734
|
C++
|
.cpp
| 78
| 32.5
| 83
| 0.757116
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,910
|
projectexplorerlistviewitemdelegate.cpp
|
olive-editor_olive/app/widget/projectexplorer/projectexplorerlistviewitemdelegate.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projectexplorerlistviewitemdelegate.h"
#include <QPainter>
namespace olive {
ProjectExplorerListViewItemDelegate::ProjectExplorerListViewItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
QSize ProjectExplorerListViewItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &) const
{
return QSize(option.decorationSize.height(), option.decorationSize.height());
}
void ProjectExplorerListViewItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QFontMetrics fm = painter->fontMetrics();
QRect img_rect = option.rect;
if (option.state & QStyle::State_Selected) {
painter->fillRect(option.rect, option.palette.highlight());
}
img_rect.setWidth(qMin(img_rect.width(), img_rect.height()));
QIcon ico = index.data(Qt::DecorationRole).value<QIcon>();
QSize icon_size = ico.actualSize(img_rect.size());
img_rect = QRect(img_rect.x() + (img_rect.width() / 2 - icon_size.width() / 2),
img_rect.y() + (img_rect.height() / 2 - icon_size.height() / 2),
icon_size.width(),
icon_size.height());
painter->drawPixmap(img_rect, ico.pixmap(icon_size));
QRect text_rect = option.rect;
text_rect.setLeft(text_rect.left() + option.rect.height());
int maximum_line_count = qMax(1, option.rect.height() / fm.height() - 1);
QString text;
if (maximum_line_count == 1) {
text = index.data(Qt::DisplayRole).toString();
} else {
text = index.data(Qt::ToolTipRole).toString();
if (text.isEmpty()) {
text = index.data(Qt::DisplayRole).toString();
} else {
QStringList strings = text.split("\n");
while (strings.size() > maximum_line_count) {
strings.removeLast();
}
text = strings.join("\n");
}
}
painter->setPen(option.state & QStyle::State_Selected ?
option.palette.highlightedText().color() : option.palette.text().color());
painter->drawText(text_rect, static_cast<int>(Qt::AlignLeft | Qt::AlignVCenter), text);
}
}
| 2,795
|
C++
|
.cpp
| 63
| 39.825397
| 134
| 0.710177
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,911
|
projecttoolbar.cpp
|
olive-editor_olive/app/widget/projecttoolbar/projecttoolbar.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "projecttoolbar.h"
#include <QHBoxLayout>
#include <QEvent>
#include <QButtonGroup>
#include "ui/icons/icons.h"
namespace olive {
ProjectToolbar::ProjectToolbar(QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
new_button_ = new QPushButton();
connect(new_button_, &QPushButton::clicked, this, &ProjectToolbar::NewClicked);
layout->addWidget(new_button_);
open_button_ = new QPushButton();
connect(open_button_, &QPushButton::clicked, this, &ProjectToolbar::OpenClicked);
layout->addWidget(open_button_);
save_button_ = new QPushButton();
connect(save_button_, &QPushButton::clicked, this, &ProjectToolbar::SaveClicked);
layout->addWidget(save_button_);
search_field_ = new QLineEdit();
search_field_->setClearButtonEnabled(true);
connect(search_field_, &QLineEdit::textChanged, this, &ProjectToolbar::SearchChanged);
layout->addWidget(search_field_);
tree_button_ = new QPushButton();
tree_button_->setCheckable(true);
connect(tree_button_, &QPushButton::clicked, this, &ProjectToolbar::ViewButtonClicked);
layout->addWidget(tree_button_);
list_button_ = new QPushButton();
list_button_->setCheckable(true);
connect(list_button_, &QPushButton::clicked, this, &ProjectToolbar::ViewButtonClicked);
layout->addWidget(list_button_);
icon_button_ = new QPushButton();
icon_button_->setCheckable(true);
connect(icon_button_, &QPushButton::clicked, this, &ProjectToolbar::ViewButtonClicked);
layout->addWidget(icon_button_);
// Group Tree/List/Icon view buttons into a button group for easy exclusive-buttons
QButtonGroup* view_button_group = new QButtonGroup(this);
view_button_group->setExclusive(true);
view_button_group->addButton(tree_button_);
view_button_group->addButton(list_button_);
view_button_group->addButton(icon_button_);
Retranslate();
UpdateIcons();
}
void ProjectToolbar::SetView(ViewType type)
{
switch (type) {
case TreeView:
tree_button_->setChecked(true);
break;
case IconView:
icon_button_->setChecked(true);
break;
case ListView:
list_button_->setChecked(true);
break;
}
}
void ProjectToolbar::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
Retranslate();
} else if (e->type() == QEvent::StyleChange) {
UpdateIcons();
}
QWidget::changeEvent(e);
}
void ProjectToolbar::Retranslate()
{
new_button_->setToolTip(tr("New..."));
open_button_->setToolTip(tr("Open Project"));
save_button_->setToolTip(tr("Save Project"));
search_field_->setPlaceholderText(tr("Search media, markers, etc."));
tree_button_->setToolTip(tr("Tree View"));
list_button_->setToolTip(tr("List View"));
icon_button_->setToolTip(tr("Icon View"));
}
void ProjectToolbar::UpdateIcons()
{
new_button_->setIcon(icon::New);
open_button_->setIcon(icon::Open);
save_button_->setIcon(icon::Save);
tree_button_->setIcon(icon::TreeView);
list_button_->setIcon(icon::ListView);
icon_button_->setIcon(icon::IconView);
}
void ProjectToolbar::ViewButtonClicked()
{
// Determine which view button triggered this slot and emit a signal accordingly
if (sender() == tree_button_) {
emit ViewChanged(ProjectToolbar::TreeView);
} else if (sender() == icon_button_) {
emit ViewChanged(ProjectToolbar::IconView);
} else if (sender() == list_button_) {
emit ViewChanged(ProjectToolbar::ListView);
} else {
// Assert that it was one of the above buttons
abort();
}
}
}
| 4,271
|
C++
|
.cpp
| 117
| 33.512821
| 89
| 0.735643
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,912
|
timetarget.cpp
|
olive-editor_olive/app/widget/timetarget/timetarget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timetarget.h"
namespace olive {
TimeTargetObject::TimeTargetObject() :
time_target_(nullptr),
path_index_(0)
{
}
ViewerOutput *TimeTargetObject::GetTimeTarget() const
{
return time_target_;
}
void TimeTargetObject::SetTimeTarget(ViewerOutput *target)
{
if (time_target_) {
TimeTargetDisconnectEvent(time_target_);
}
time_target_ = target;
TimeTargetChangedEvent(time_target_);
if (time_target_) {
TimeTargetConnectEvent(time_target_);
}
}
void TimeTargetObject::SetPathIndex(int index)
{
path_index_ = index;
}
rational TimeTargetObject::GetAdjustedTime(Node* from, Node* to, const rational &r, Node::TransformTimeDirection dir) const
{
if (!from || !to) {
return r;
}
return GetAdjustedTime(from, to, TimeRange(r, r), dir).in();
}
TimeRange TimeTargetObject::GetAdjustedTime(Node* from, Node* to, const TimeRange &r, Node::TransformTimeDirection dir) const
{
if (!from || !to) {
return r;
}
return from->TransformTimeTo(r, to, dir, path_index_);
}
/*int TimeTargetObject::GetNumberOfPathAdjustments(Node* from, NodeParam::Type direction) const
{
if (!time_target_) {
return 0;
}
QList<TimeRange> adjusted = from->TransformTimeTo(TimeRange(), time_target_, direction);
return adjusted.size();
}*/
}
| 1,996
|
C++
|
.cpp
| 63
| 29.015873
| 125
| 0.75
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,913
|
timebasedviewselectionmanager.cpp
|
olive-editor_olive/app/widget/timebased/timebasedviewselectionmanager.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timebasedviewselectionmanager.h"
namespace olive {
}
| 777
|
C++
|
.cpp
| 17
| 42.823529
| 71
| 0.777926
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,914
|
timebasedwidget.cpp
|
olive-editor_olive/app/widget/timebased/timebasedwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timebasedwidget.h"
#include <QInputDialog>
#include "common/autoscroll.h"
#include "common/range.h"
#include "config/config.h"
#include "core.h"
#include "dialog/markerproperties/markerpropertiesdialog.h"
#include "node/project/sequence/sequence.h"
#include "timeline/timelineundoworkarea.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
TimeBasedWidget::TimeBasedWidget(bool ruler_text_visible, bool ruler_cache_status_visible, QWidget *parent) :
TimelineScaledWidget(parent),
viewer_node_(nullptr),
auto_max_scrollbar_(false),
toggle_show_all_(false),
auto_set_timebase_(true),
workarea_(nullptr),
markers_(nullptr)
{
scrollbar_ = new ResizableTimelineScrollBar(Qt::Horizontal, this);
connect(scrollbar_, &ResizableScrollBar::ResizeBegan, this, &TimeBasedWidget::ScrollBarResizeBegan);
connect(scrollbar_, &ResizableScrollBar::ResizeMoved, this, &TimeBasedWidget::ScrollBarResizeMoved);
ruler_ = new TimeRuler(ruler_text_visible, ruler_cache_status_visible, this);
ConnectTimelineView(ruler_);
ruler()->SetSnapService(this);
connect(ruler(), &TimeRuler::DragMoved, this, static_cast<void(TimeBasedWidget::*)(int)>(&TimeBasedWidget::SetCatchUpScrollValue));
connect(ruler(), &TimeRuler::DragReleased, this, static_cast<void(TimeBasedWidget::*)()>(&TimeBasedWidget::StopCatchUpScrollTimer));
catchup_scroll_timer_ = new QTimer(this);
catchup_scroll_timer_->setInterval(250); // Hardcoded 1/4 scroll limit value
connect(catchup_scroll_timer_, &QTimer::timeout, this, &TimeBasedWidget::CatchUpTimerTimeout);
}
void TimeBasedWidget::SetScaleAndCenterOnPlayhead(const double &scale)
{
SetScale(scale);
// Zoom towards the playhead
// (using a hacky singleShot so the scroll occurs after the scene and its scrollbars have updated)
QTimer::singleShot(0, this, &TimeBasedWidget::CenterScrollOnPlayhead);
}
ViewerOutput *TimeBasedWidget::GetConnectedNode() const
{
return viewer_node_;
}
void TimeBasedWidget::ConnectViewerNode(ViewerOutput *node)
{
// Ignore no-op
if (viewer_node_ == node) {
return;
}
// Set viewer node
ViewerOutput* old = viewer_node_;
viewer_node_ = node;
if (old) {
// Call potential derivative functions for disconnecting the viewer node
DisconnectNodeEvent(old);
// Disconnect length changed signal
disconnect(old, &ViewerOutput::LengthChanged, this, &TimeBasedWidget::UpdateMaximumScroll);
disconnect(old, &ViewerOutput::RemovedFromGraph, this, &TimeBasedWidget::ConnectedNodeRemovedFromGraph);
disconnect(old, &ViewerOutput::PlayheadChanged, this, &TimeBasedWidget::PlayheadTimeChanged);
// Disconnect rate change signals if they were connected
disconnect(old, &ViewerOutput::FrameRateChanged, this, &TimeBasedWidget::AutoUpdateTimebase);
disconnect(old, &ViewerOutput::SampleRateChanged, this, &TimeBasedWidget::AutoUpdateTimebase);
// Reset timebase to null
SetTimebase(rational());
// Disconnect ruler and scrollbar from timeline points
ConnectWorkArea(nullptr);
ConnectMarkers(nullptr);
}
// Call derivatives
for (TimeBasedView *view : timeline_views_) {
view->SetViewerNode(viewer_node_);
}
ConnectedNodeChangeEvent(viewer_node_);
if (viewer_node_) {
// Connect length changed signal
connect(viewer_node_, &ViewerOutput::LengthChanged, this, &TimeBasedWidget::UpdateMaximumScroll);
connect(viewer_node_, &ViewerOutput::RemovedFromGraph, this, &TimeBasedWidget::ConnectedNodeRemovedFromGraph);
connect(viewer_node_, &ViewerOutput::PlayheadChanged, this, &TimeBasedWidget::PlayheadTimeChanged);
// Connect ruler and scrollbar to timeline points
ConnectWorkArea(viewer_node_->GetWorkArea());
ConnectMarkers(viewer_node_->GetMarkers());
// If we're setting the timebase, set it automatically based on the video and audio parameters
if (auto_set_timebase_) {
AutoUpdateTimebase();
connect(viewer_node_, &ViewerOutput::FrameRateChanged, this, &TimeBasedWidget::AutoUpdateTimebase);
connect(viewer_node_, &ViewerOutput::SampleRateChanged, this, &TimeBasedWidget::AutoUpdateTimebase);
}
// Call derivatives
ConnectNodeEvent(viewer_node_);
}
UpdateMaximumScroll();
emit ConnectedNodeChanged(old, node);
}
void TimeBasedWidget::ConnectWorkArea(TimelineWorkArea *workarea)
{
workarea_ = workarea;
ruler()->SetWorkArea(workarea);
scrollbar_->ConnectWorkArea(workarea);
}
void TimeBasedWidget::ConnectMarkers(TimelineMarkerList *markers)
{
markers_ = markers;
ruler()->SetMarkers(markers);
scrollbar_->ConnectMarkers(markers);
}
void TimeBasedWidget::UpdateMaximumScroll()
{
rational length = (viewer_node_) ? viewer_node_->GetLength() : 0;
if (auto_max_scrollbar_) {
scrollbar_->setMaximum(std::max(0, int(std::ceil(TimeToScene(length)) - width())));
}
foreach (TimeBasedView* base, timeline_views_) {
base->SetEndTime(length);
}
}
void TimeBasedWidget::ScrollBarResizeBegan(int current_bar_width, bool top_handle)
{
QScrollBar* bar = static_cast<QScrollBar*>(sender());
scrollbar_start_width_ = current_bar_width;
scrollbar_start_value_ = bar->value();
scrollbar_start_scale_ = GetScale();
scrollbar_top_handle_ = top_handle;
}
void TimeBasedWidget::ScrollBarResizeMoved(int movement)
{
ResizableScrollBar* bar = static_cast<ResizableScrollBar*>(sender());
// Negate movement for the top handle
if (scrollbar_top_handle_) {
movement = -movement;
}
// The user wants the bar to be this size
int proposed_size = scrollbar_start_width_ + movement;
double ratio = double(scrollbar_start_width_) / double(proposed_size);
if (ratio > 0) {
SetScale(scrollbar_start_scale_ * ratio);
if (scrollbar_top_handle_) {
int viewable_area;
if (timeline_views_.isEmpty()) {
viewable_area = width();
} else {
viewable_area = timeline_views_.first()->width();
}
bar->setValue((scrollbar_start_value_ + viewable_area) * ratio - viewable_area);
} else {
bar->setValue(scrollbar_start_value_ * ratio);
}
}
}
void TimeBasedWidget::PageScrollToPlayhead()
{
if (GetConnectedNode()) {
PageScrollInternal(qRound(TimeToScene(GetConnectedNode()->GetPlayhead())), true);
}
}
void TimeBasedWidget::CatchUpScrollToPlayhead()
{
if (GetConnectedNode()) {
CatchUpScrollToPoint(qRound(TimeToScene(GetConnectedNode()->GetPlayhead())));
}
}
void TimeBasedWidget::CatchUpScrollToPoint(int point)
{
PageScrollInternal(point, false);
}
void TimeBasedWidget::CatchUpTimerTimeout()
{
for (auto it=catchup_scroll_values_.cbegin(); it!=catchup_scroll_values_.cend(); it++) {
QScrollBar *sb = it.key();
const CatchUpScrollData &d = it.value();
PageScrollInternal(sb, d.maximum, sb->value() + d.value, false);
}
SendCatchUpScrollEvent();
}
void TimeBasedWidget::SendCatchUpScrollEvent()
{
for (auto v : this->timeline_views_) {
v->CatchUpScrollEvent();
}
}
void TimeBasedWidget::AutoUpdateTimebase()
{
rational video_tb = viewer_node_->GetVideoParams().frame_rate_as_time_base();
if (!video_tb.isNull()) {
SetTimebase(video_tb);
} else {
rational audio_tb = viewer_node_->GetAudioParams().sample_rate_as_time_base();
if (!audio_tb.isNull()) {
SetTimebase(audio_tb);
} else {
SetTimebase(rational());
}
}
}
void TimeBasedWidget::ConnectedNodeRemovedFromGraph()
{
ConnectViewerNode(nullptr);
}
TimeRuler *TimeBasedWidget::ruler() const
{
return ruler_;
}
ResizableTimelineScrollBar *TimeBasedWidget::scrollbar() const
{
return scrollbar_;
}
void TimeBasedWidget::TimebaseChangedEvent(const rational &timebase)
{
TimelineScaledWidget::TimebaseChangedEvent(timebase);
ruler_->SetTimebase(timebase);
scrollbar_->SetTimebase(timebase);
emit TimebaseChanged(timebase);
}
void TimeBasedWidget::ScaleChangedEvent(const double &scale)
{
TimelineScaledWidget::ScaleChangedEvent(scale);
ruler_->SetScale(scale);
scrollbar_->SetScale(scale);
UpdateMaximumScroll();
QMetaObject::invokeMethod(this, &TimeBasedWidget::SendCatchUpScrollEvent, Qt::QueuedConnection);
toggle_show_all_ = false;
}
void TimeBasedWidget::SetAutoMaxScrollBar(bool e)
{
auto_max_scrollbar_ = e;
}
void TimeBasedWidget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
// Update horizontal scrollbar's page step to the width of the panel
scrollbar()->setPageStep(scrollbar()->width());
UpdateMaximumScroll();
}
void TimeBasedWidget::ConnectTimelineView(TimeBasedView *base)
{
// Connect scale
connect(base, &TimeBasedView::ScaleChanged, this, &TimeBasedWidget::SetScale);
// Main scrollbar to view scrollbar and vice versa
connect(scrollbar(), &QScrollBar::valueChanged, base->horizontalScrollBar(), &QScrollBar::setValue);
connect(base->horizontalScrollBar(), &QScrollBar::valueChanged, scrollbar(), &QScrollBar::setValue);
// Connect scrollbar to other scrollbars
for (TimeBasedView *other : qAsConst(timeline_views_)) {
connect(other->horizontalScrollBar(), &QScrollBar::valueChanged, base->horizontalScrollBar(), &QScrollBar::setValue);
connect(base->horizontalScrollBar(), &QScrollBar::valueChanged, other->horizontalScrollBar(), &QScrollBar::setValue);
}
timeline_views_.append(base);
}
void TimeBasedWidget::SetCatchUpScrollValue(QScrollBar *b, int v, int maximum)
{
CatchUpScrollData &cudata = catchup_scroll_values_[b];
cudata.value = v;
cudata.maximum = maximum;
static const qint64 min_cooldown = 100; // Hardcoded 1/10 sec cooldown
if (QDateTime::currentMSecsSinceEpoch() - cudata.last_forced >= min_cooldown) {
QMetaObject::invokeMethod(this, &TimeBasedWidget::CatchUpTimerTimeout, Qt::QueuedConnection);
cudata.last_forced = QDateTime::currentMSecsSinceEpoch();
}
if (!catchup_scroll_timer_->isActive()) {
catchup_scroll_timer_->start();
}
}
void TimeBasedWidget::SetCatchUpScrollValue(int v)
{
SetCatchUpScrollValue(scrollbar_, v, ruler()->width());
}
void TimeBasedWidget::StopCatchUpScrollTimer(QScrollBar *b)
{
catchup_scroll_values_.remove(b);
if (catchup_scroll_values_.empty()) {
catchup_scroll_timer_->stop();
}
}
void TimeBasedWidget::PlayheadTimeChanged(const rational &time)
{
if (UserIsDraggingPlayhead()) {
// If the user is dragging the playhead, we will simply nudge over and not use autoscroll rules.
SetCatchUpScrollValue(qRound(TimeToScene(time)) - scrollbar_->value());
} else {
// Otherwise, assume we jumped to this out of nowhere and must now autoscroll
switch (static_cast<AutoScroll::Method>(OLIVE_CONFIG("Autoscroll").toInt())) {
case AutoScroll::kNone:
// Do nothing
break;
case AutoScroll::kPage:
QMetaObject::invokeMethod(this, "PageScrollToPlayhead", Qt::QueuedConnection);
break;
case AutoScroll::kSmooth:
QMetaObject::invokeMethod(this, "CenterScrollOnPlayhead", Qt::QueuedConnection);
break;
}
}
TimeChangedEvent(time);
}
void TimeBasedWidget::SetTimebase(const rational &timebase)
{
TimelineScaledWidget::SetTimebase(timebase);
}
void TimeBasedWidget::SetScale(const double &scale)
{
// Simple QObject slot wrapper around TimelineScaledWidget::SetScale()
TimelineScaledWidget::SetScale(scale);
}
void TimeBasedWidget::ZoomIn()
{
SetScaleAndCenterOnPlayhead(GetScale() * 2);
}
void TimeBasedWidget::ZoomOut()
{
SetScaleAndCenterOnPlayhead(GetScale() * 0.5);
}
void TimeBasedWidget::GoToPrevCut()
{
// Cuts are only possible in sequences
Sequence* sequence = dynamic_cast<Sequence*>(viewer_node_);
if (!sequence) {
return;
}
if (GetConnectedNode()->GetPlayhead().isNull()) {
return;
}
rational closest_cut = 0;
for (Track* track : sequence->GetTracks()) {
rational this_track_closest_cut = 0;
for (Block* block : track->Blocks()) {
if (block->out() < GetConnectedNode()->GetPlayhead()) {
this_track_closest_cut = block->out();
} else {
break;
}
}
closest_cut = qMax(closest_cut, this_track_closest_cut);
}
GetConnectedNode()->SetPlayhead(closest_cut);
}
void TimeBasedWidget::GoToNextCut()
{
// Cuts are only possible in sequences
Sequence* sequence = dynamic_cast<Sequence*>(viewer_node_);
if (!sequence) {
return;
}
rational closest_cut = RATIONAL_MAX;
for (Track* track : sequence->GetTracks()) {
rational this_track_closest_cut = track->track_length();
if (this_track_closest_cut <= GetConnectedNode()->GetPlayhead()) {
this_track_closest_cut = RATIONAL_MAX;
}
for (Block* block : track->Blocks()) {
if (block->in() > GetConnectedNode()->GetPlayhead()) {
this_track_closest_cut = block->in();
break;
}
}
closest_cut = qMin(closest_cut, this_track_closest_cut);
}
if (closest_cut < RATIONAL_MAX) {
GetConnectedNode()->SetPlayhead(closest_cut);
}
}
void TimeBasedWidget::GoToStart()
{
if (viewer_node_) {
viewer_node_->SetPlayhead(0);
}
}
void TimeBasedWidget::PrevFrame()
{
if (viewer_node_) {
rational proposed_time = Timecode::snap_time_to_timebase(GetConnectedNode()->GetPlayhead() - timebase(), timebase(), Timecode::kCeil);
if (proposed_time == GetConnectedNode()->GetPlayhead()) {
// Catch rounding error, assume this time is snapped and just subtract a timebase
proposed_time -= timebase();
}
viewer_node_->SetPlayhead(qMax(rational(0), proposed_time));
}
}
void TimeBasedWidget::NextFrame()
{
if (viewer_node_) {
rational proposed_time = Timecode::snap_time_to_timebase(GetConnectedNode()->GetPlayhead() + timebase(), timebase(), Timecode::kFloor);
if (proposed_time == GetConnectedNode()->GetPlayhead()) {
// Catch rounding error, assume this time is snapped and just add a timebase
proposed_time += timebase();
}
viewer_node_->SetPlayhead(proposed_time);
}
}
void TimeBasedWidget::GoToEnd()
{
if (viewer_node_) {
viewer_node_->SetPlayhead(viewer_node_->GetLength());
}
}
void TimeBasedWidget::CenterScrollOnPlayhead()
{
if (GetConnectedNode()) {
scrollbar_->setValue(qRound(TimeToScene(GetConnectedNode()->GetPlayhead())) - scrollbar_->width()/2);
}
}
void TimeBasedWidget::SetAutoSetTimebase(bool e)
{
auto_set_timebase_ = e;
}
void TimeBasedWidget::SetPoint(Timeline::MovementMode m, const rational& time)
{
if (!viewer_node_) {
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
TimelineWorkArea* points = viewer_node_->GetWorkArea();
// Enable workarea if it isn't already enabled
if (!points->enabled()) {
command->add_child(new WorkareaSetEnabledCommand(viewer_node_->project(), points, true));
}
// Determine our new range
rational in_point, out_point;
if (m == Timeline::kTrimIn) {
in_point = time;
if (!points->enabled() || points->out() < in_point) {
out_point = TimelineWorkArea::kResetOut;
} else {
out_point = points->out();
}
} else {
out_point = time;
if (!points->enabled() || points->in() > out_point) {
in_point = TimelineWorkArea::kResetIn;
} else {
in_point = points->in();
}
}
// Set workarea
command->add_child(new WorkareaSetRangeCommand(points, TimeRange(in_point, out_point)));
Core::instance()->undo_stack()->push(command, tr("Set In/Out Point"));
}
void TimeBasedWidget::ResetPoint(Timeline::MovementMode m)
{
if (!GetConnectedNode()) {
return;
}
TimelineWorkArea* points = GetConnectedNode()->GetWorkArea();
if (!points->enabled()) {
return;
}
TimeRange r = points->range();
if (m == Timeline::kTrimIn) {
r.set_in(TimelineWorkArea::kResetIn);
} else {
r.set_out(TimelineWorkArea::kResetOut);
}
Core::instance()->undo_stack()->push(new WorkareaSetRangeCommand(points, r), tr("Reset In/Out Points"));
}
void TimeBasedWidget::PageScrollInternal(QScrollBar *bar, int maximum, int screen_position, bool whole_page_scroll)
{
int viewport_padding = maximum / 16;
if (whole_page_scroll) {
if (screen_position < bar->value()) {
// Anchor the playhead to the RIGHT of where we scroll to
bar->setValue(screen_position - maximum + viewport_padding);
} else if (screen_position > bar->value() + maximum) {
// Anchor the playhead to the LEFT of where we scroll to
bar->setValue(screen_position - viewport_padding);
}
} else {
// Just jump in increments
if (screen_position < bar->value() + viewport_padding) {
bar->setValue(bar->value() - viewport_padding);
} else if (screen_position > bar->value() + maximum - viewport_padding) {
bar->setValue(bar->value() + viewport_padding);
}
}
}
void TimeBasedWidget::PageScrollInternal(int screen_position, bool whole_page_scroll)
{
PageScrollInternal(scrollbar(), ruler()->width(), screen_position, whole_page_scroll);
}
bool TimeBasedWidget::UserIsDraggingPlayhead() const
{
foreach (TimeBasedView* view, timeline_views_) {
if (view->IsDraggingPlayhead()) {
return true;
}
}
return false;
}
void TimeBasedWidget::SetInAtPlayhead()
{
SetPoint(Timeline::kTrimIn, GetConnectedNode()->GetPlayhead());
}
void TimeBasedWidget::SetOutAtPlayhead()
{
SetPoint(Timeline::kTrimOut, GetConnectedNode()->GetPlayhead());
}
void TimeBasedWidget::ResetIn()
{
ResetPoint(Timeline::kTrimIn);
}
void TimeBasedWidget::ResetOut()
{
ResetPoint(Timeline::kTrimOut);
}
void TimeBasedWidget::ClearInOutPoints()
{
if (!GetConnectedNode()) {
return;
}
Core::instance()->undo_stack()->push(new WorkareaSetEnabledCommand(GetConnectedNode()->project(), GetConnectedNode()->GetWorkArea(), false), tr("Cleared In/Out Points"));
}
void TimeBasedWidget::SetMarker()
{
if (!GetConnectedNode()) {
return;
}
TimelineMarkerList *markers = GetConnectedNode()->GetMarkers();
if (TimelineMarker *existing = markers->GetMarkerAtTime(GetConnectedNode()->GetPlayhead())) {
// We already have a marker here, so pop open the edit dialog
MarkerPropertiesDialog mpd({existing}, timebase(), this);
mpd.exec();
} else {
// Create a new marker and place it here
int color;
if (TimelineMarker *closest = markers->GetClosestMarkerToTime(GetConnectedNode()->GetPlayhead())) {
// Copy color of closest marker to this time
color = closest->color();
} else {
// Fallback to default color in preferences
color = OLIVE_CONFIG("MarkerColor").toInt();
}
TimelineMarker *marker = new TimelineMarker(color, TimeRange(GetConnectedNode()->GetPlayhead(), GetConnectedNode()->GetPlayhead()));
if (OLIVE_CONFIG("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), tr("Added Marker"));
}
}
}
void TimeBasedWidget::ToggleShowAll()
{
if (!GetConnectedNode()) {
return;
}
if (toggle_show_all_) {
SetScale(toggle_show_all_old_scale_);
scrollbar_->setValue(toggle_show_all_old_scroll_);
// Don't have to set toggle_show_all_ because SetScale() will automatically set it to false
} else {
int w;
if (timeline_views_.isEmpty()) {
w = width();
} else {
w = timeline_views_.first()->width();
}
toggle_show_all_old_scale_ = GetScale();
toggle_show_all_old_scroll_ = scrollbar_->value();
SetScaleFromDimensions(w, GetConnectedNode()->GetLength().toDouble());
scrollbar_->setValue(0);
// Must explicitly do this because SetScale() will automatically set this to false
toggle_show_all_ = true;
}
}
void TimeBasedWidget::GoToIn()
{
if (GetConnectedNode()) {
if (GetConnectedNode()->GetWorkArea()->enabled()) {
GetConnectedNode()->SetPlayhead(GetConnectedNode()->GetWorkArea()->in());
} else {
GoToStart();
}
}
}
void TimeBasedWidget::GoToOut()
{
if (GetConnectedNode()) {
if (GetConnectedNode()->GetWorkArea()->enabled()) {
GetConnectedNode()->SetPlayhead(GetConnectedNode()->GetWorkArea()->out());
} else {
GoToEnd();
}
}
}
void TimeBasedWidget::DeleteSelected()
{
if (ruler_->HasItemsSelected()) {
ruler_->DeleteSelected();
}
}
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 = GetConnectedNode()->GetPlayhead();
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()->GetMarkers();
for (auto jt=markers->cbegin(); jt!=markers->cend(); jt++) {
TimelineMarker *marker = *jt;
TimeRange marker_range = marker->time() + 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()->GetMarkers()) {
for (auto it=ruler()->GetMarkers()->cbegin(); it!=ruler()->GetMarkers()->cend(); it++) {
TimelineMarker* m = *it;
// Ignore selected markers
if (std::find(ruler()->GetSelectedMarkers().cbegin(), ruler()->GetSelectedMarkers().cend(), m) != ruler()->GetSelectedMarkers().cend()) {
continue;
}
qreal marker_pos = TimeToScene(m->time().in());
AttemptSnap(potential_snaps, screen_pt, marker_pos, start_times, m->time().in());
if (m->time().in() != m->time().out()) {
marker_pos = TimeToScene(m->time().out());
AttemptSnap(potential_snaps, screen_pt, marker_pos, start_times, m->time().out());
}
}
}
if ((snap_points & kSnapToWorkarea) && ruler()->GetWorkArea() && ruler()->GetWorkArea()->enabled()) {
const rational &workarea_in = ruler()->GetWorkArea()->in();
const rational &workarea_out = ruler()->GetWorkArea()->out();
AttemptSnap(potential_snaps, screen_pt, TimeToScene(workarea_in), start_times, workarea_in);
AttemptSnap(potential_snaps, screen_pt, TimeToScene(workarea_out), start_times, workarea_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;
}
rational time = key->time();
if (const TimeTargetObject *target = GetKeyframeTimeTarget()) {
if (Node *parent = key->parent()) {
time = target->GetAdjustedTime(parent, target->GetTimeTarget(), time, Node::kTransformTowardsOutput);
}
}
qreal key_scene_pt = TimeToScene(time);
AttemptSnap(potential_snaps, screen_pt, key_scene_pt, start_times, 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> ×)
{
foreach (TimeBasedView* view, timeline_views_) {
view->EnableSnap(times);
}
}
void TimeBasedWidget::HideSnaps()
{
foreach (TimeBasedView* view, timeline_views_) {
view->DisableSnap();
}
}
bool TimeBasedWidget::CopySelected(bool cut)
{
if (ruler()->CopySelected(cut)) {
return true;
}
return false;
}
bool TimeBasedWidget::Paste()
{
if (ruler()->PasteMarkers()) {
return true;
}
return false;
}
}
| 27,022
|
C++
|
.cpp
| 754
| 31.785146
| 172
| 0.705138
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,915
|
timebasedview.cpp
|
olive-editor_olive/app/widget/timebased/timebasedview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timebasedview.h"
#include <QGraphicsRectItem>
#include <QMouseEvent>
#include <QScrollBar>
#include <QTimer>
#include "widget/timebased/timebasedwidget.h"
namespace olive {
TimeBasedView::TimeBasedView(QWidget *parent) :
HandMovableView(parent),
playhead_scene_left_(-1),
playhead_scene_right_(-1),
dragging_playhead_(false),
snapped_(false),
snap_service_(nullptr),
y_axis_enabled_(false),
y_scale_(1.0),
viewer_(nullptr)
{
// Sets scene to our scene
setScene(&scene_);
// Set default scale (ensures non-zero scale from beginning)
SetScale(1.0);
// Default to no default drag mode
SetDefaultDragMode(NoDrag);
// Signal to update bounding rect when the scene changes
connect(&scene_, &QGraphicsScene::changed, this, &TimeBasedView::UpdateSceneRect);
// Workaround for Qt drawing issues with the default MinimalViewportUpdate. While this might be
// slower (Qt documentation says it may actually be faster in some situations),
// MinimalViewportUpdate causes all sorts of graphical crud building up in the scene
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
}
void TimeBasedView::TimebaseChangedEvent(const rational &)
{
// Timebase influences position/visibility of playhead
viewport()->update();
}
void TimeBasedView::EnableSnap(const std::vector<rational> &points)
{
snapped_ = true;
snap_time_ = points;
viewport()->update();
}
void TimeBasedView::DisableSnap()
{
snapped_ = false;
viewport()->update();
}
const double &TimeBasedView::GetYScale() const
{
return y_scale_;
}
void TimeBasedView::VerticalScaleChangedEvent(double)
{
}
void TimeBasedView::ZoomIntoCursorPosition(QWheelEvent *event, double scale_multiplier, const QPointF &cursor_pos)
{
// If CTRL is held (or a preference is set to swap CTRL behavior), we zoom instead of scrolling
bool only_vertical = false;
bool only_horizontal = false;
// Ctrl+Shift limits to only one axis
// Alt switches between horizontal only (alt held) or vertical only (alt not held)
if (y_axis_enabled_) {
if (event->modifiers() & Qt::ShiftModifier) {
if (event->modifiers() & Qt::AltModifier) {
only_horizontal = true;
} else {
only_vertical = true;
}
}
} else {
only_horizontal = true;
}
if (!only_vertical) {
double old_scroll = horizontalScrollBar()->value();
double old_scale = GetScale();
emit ScaleChanged(old_scale * scale_multiplier);
// Use GetScale so that if this value was clamped, we don't erroneously use an unclamped value
int new_x_scroll = qRound((cursor_pos.x() + old_scroll) / old_scale * GetScale() - cursor_pos.x());
horizontalScrollBar()->setValue(new_x_scroll);
}
if (!only_horizontal) {
double old_y_scroll = verticalScrollBar()->value();
double old_y_scale = GetYScale();
SetYScale(old_y_scale * scale_multiplier);
// Use GetYScale so that if this value was clamped, we don't erroneously use an unclamped value
int new_y_scroll = qRound((cursor_pos.y() + old_y_scroll) / old_y_scale * GetYScale() - cursor_pos.y());
verticalScrollBar()->setValue(new_y_scroll);
}
}
void TimeBasedView::SetYScale(const double &y_scale)
{
Q_ASSERT(y_scale > 0);
y_scale_ = y_scale;
if (y_axis_enabled_) {
VerticalScaleChangedEvent(y_scale_);
viewport()->update();
}
}
void TimeBasedView::SetViewerNode(ViewerOutput *v)
{
if (viewer_) {
disconnect(viewer_, &ViewerOutput::PlayheadChanged, viewport(), static_cast<void(QWidget::*)()>(&TimeBasedView::update));
}
viewer_ = v;
if (viewer_) {
connect(viewer_, &ViewerOutput::PlayheadChanged, viewport(), static_cast<void(QWidget::*)()>(&TimeBasedView::update));
}
}
QPointF TimeBasedView::ScalePoint(const QPointF &p) const
{
return QPointF(p.x() * GetScale(), p.y() * GetYScale());
}
QPointF TimeBasedView::UnscalePoint(const QPointF &p) const
{
return QPointF(p.x() / GetScale(), p.y() / GetYScale());
}
void TimeBasedView::drawForeground(QPainter *painter, const QRectF &rect)
{
QGraphicsView::drawForeground(painter, rect);
if (!timebase().isNull()) {
double width = TimeToScene(timebase());
playhead_scene_left_ = GetPlayheadX();
playhead_scene_right_ = playhead_scene_left_ + width;
QRectF playhead_rect(playhead_scene_left_, rect.top(), width, rect.height());
// Get playhead highlight color
QColor highlight = palette().text().color();
highlight.setAlpha(32);
painter->setPen(Qt::NoPen);
painter->setBrush(highlight);
painter->drawRect(playhead_rect);
// FIXME: Hardcoded...
painter->setPen(PLAYHEAD_COLOR);
painter->setBrush(Qt::NoBrush);
painter->drawLine(QLineF(playhead_rect.topLeft(), playhead_rect.bottomLeft()));
}
if (snapped_) {
painter->setPen(palette().text().color());
foreach (const rational& r, snap_time_) {
double x = TimeToScene(r);
painter->drawLine(x, rect.top(), x, rect.height());
}
}
}
bool TimeBasedView::PlayheadPress(QMouseEvent *event)
{
QPointF scene_pos = mapToScene(event->pos());
dragging_playhead_ = (event->button() == Qt::LeftButton
&& scene_pos.x() >= playhead_scene_left_
&& scene_pos.x() < playhead_scene_right_);
return dragging_playhead_;
}
bool TimeBasedView::PlayheadMove(QMouseEvent *event)
{
if (!dragging_playhead_) {
return false;
}
if (viewer_) {
QPointF scene_pos = mapToScene(event->pos());
rational mouse_time = qMax(rational(0), SceneToTime(scene_pos.x()));
if (Core::instance()->snapping() && snap_service_) {
rational movement;
snap_service_->SnapPoint({mouse_time}, &movement, TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToPlayhead);
mouse_time += movement;
}
viewer_->SetPlayhead(mouse_time);
}
return true;
}
bool TimeBasedView::PlayheadRelease(QMouseEvent*)
{
if (dragging_playhead_) {
dragging_playhead_ = false;
if (snap_service_) {
snap_service_->HideSnaps();
}
return true;
}
return false;
}
qreal TimeBasedView::GetPlayheadX()
{
if (viewer_) {
return TimeToScene(viewer_->GetPlayhead());
} else {
return 0;
}
}
void TimeBasedView::SetEndTime(const rational &length)
{
end_time_ = length;
UpdateSceneRect();
}
void TimeBasedView::UpdateSceneRect()
{
QRectF bounding_rect = scene_.itemsBoundingRect();
// There's no need for a timeline to ever go below 0 on the X scale
bounding_rect.setLeft(0);
// Ensure the scene is always the full length of the timeline with a gap at the end to work with
bounding_rect.setRight(TimeToScene(end_time_) + width());
// Any further rect processing from derivatives can be done here
SceneRectUpdateEvent(bounding_rect);
// If the scene is already this rect, do nothing
if (scene_.sceneRect() != bounding_rect) {
scene_.setSceneRect(bounding_rect);
}
}
void TimeBasedView::resizeEvent(QResizeEvent *event)
{
QGraphicsView::resizeEvent(event);
UpdateSceneRect();
}
void TimeBasedView::ScaleChangedEvent(const double &scale)
{
TimeScaledObject::ScaleChangedEvent(scale);
// Update scene rect
UpdateSceneRect();
// Force redraw for playhead if the above function didn't do it
viewport()->update();
}
}
| 7,997
|
C++
|
.cpp
| 234
| 30.641026
| 125
| 0.71514
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,916
|
timescaledobject.cpp
|
olive-editor_olive/app/widget/timebased/timescaledobject.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "timescaledobject.h"
#include <cfloat>
#include <QtMath>
#include "audio/audiovisualwaveform.h"
namespace olive {
const int TimeScaledObject::kCalculateDimensionsPadding = 10;
TimeScaledObject::TimeScaledObject() :
scale_(1.0),
min_scale_(0),
max_scale_(AudioVisualWaveform::kMaximumSampleRate.toDouble())
{
}
void TimeScaledObject::SetTimebase(const rational &timebase)
{
timebase_ = timebase;
timebase_dbl_ = timebase_.toDouble();
TimebaseChangedEvent(timebase);
}
const rational &TimeScaledObject::timebase() const
{
return timebase_;
}
const double &TimeScaledObject::timebase_dbl() const
{
return timebase_dbl_;
}
rational TimeScaledObject::SceneToTime(const double &x, const double &x_scale, const rational &timebase, bool round)
{
double unscaled_time = x / x_scale / timebase.toDouble();
// Adjust screen point by scale and timebase
qint64 rounded_x_mvmt;
if (round) {
rounded_x_mvmt = qRound64(unscaled_time);
} else if (unscaled_time < 0) {
// "floor" to zero
rounded_x_mvmt = qCeil(unscaled_time);
} else {
rounded_x_mvmt = qFloor(unscaled_time);
}
// Return a time in the timebase
return rational(rounded_x_mvmt * timebase.numerator(), timebase.denominator());
}
rational TimeScaledObject::SceneToTimeNoGrid(const double &x, const double &x_scale)
{
double unscaled_time = x / x_scale;
return rational::fromDouble(unscaled_time);
}
double TimeScaledObject::TimeToScene(const rational &time) const
{
return time.toDouble() * scale_;
}
rational TimeScaledObject::SceneToTime(const double &x, bool round) const
{
return SceneToTime(x, scale_, timebase_, round);
}
rational TimeScaledObject::SceneToTimeNoGrid(const double &x) const
{
return SceneToTimeNoGrid(x, scale_);
}
void TimeScaledObject::SetMaximumScale(const double &max)
{
max_scale_ = max;
if (GetScale() > max_scale_) {
SetScale(max_scale_);
}
}
void TimeScaledObject::SetMinimumScale(const double &min)
{
min_scale_ = min;
if (GetScale() < min_scale_) {
SetScale(min_scale_);
}
}
const double& TimeScaledObject::GetScale() const
{
return scale_;
}
void TimeScaledObject::SetScale(const double& scale)
{
Q_ASSERT(scale > 0);
scale_ = std::clamp(scale, min_scale_, max_scale_);
ScaleChangedEvent(scale_);
}
void TimeScaledObject::SetScaleFromDimensions(double viewport_width, double content_width)
{
SetScale(CalculateScaleFromDimensions(viewport_width, content_width));
}
double TimeScaledObject::CalculateScaleFromDimensions(double viewport_sz, double content_sz)
{
return static_cast<double>(viewport_sz / kCalculateDimensionsPadding * (kCalculateDimensionsPadding-1)) / static_cast<double>(content_sz);
}
double TimeScaledObject::CalculatePaddingFromDimensionScale(double viewport_sz)
{
return (viewport_sz / (kCalculateDimensionsPadding * 2));
}
TimelineScaledWidget::TimelineScaledWidget(QWidget *parent) :
QWidget(parent)
{
}
}
| 3,653
|
C++
|
.cpp
| 114
| 29.666667
| 140
| 0.767847
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,917
|
menu.cpp
|
olive-editor_olive/app/widget/menu/menu.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "menu.h"
#include "ui/style/style.h"
namespace olive {
Menu::Menu(QMenuBar *bar)
{
bar->addMenu(this);
Init();
}
Menu::Menu(Menu *menu)
{
menu->addMenu(this);
Init();
}
Menu::Menu(QWidget *parent) :
QMenu(parent)
{
Init();
}
Menu::Menu(const QString &s, QWidget *parent) :
QMenu(s, parent)
{
Init();
}
QAction *Menu::AddActionWithData(const QString &text, const QVariant &d, const QVariant &compare)
{
QAction* a = addAction(text);
a->setData(d);
a->setCheckable(true);
a->setChecked(d == compare);
return a;
}
QAction* Menu::InsertAlphabetically(const QString &s)
{
QAction* action = new QAction(s, this);
InsertAlphabetically(action);
return action;
}
void Menu::InsertAlphabetically(QAction *entry)
{
QList<QAction*> actions = this->actions();
foreach (QAction* action, actions) {
if (action->text() > entry->text()) {
insertAction(action, entry);
return;
}
}
addAction(entry);
}
void Menu::InsertAlphabetically(Menu *menu)
{
InsertAlphabetically(menu->menuAction());
}
void Menu::ConformItem(QAction *a, const QString &id, const QKeySequence &key)
{
a->setProperty("id", id);
if (!key.isEmpty()) {
a->setShortcut(key);
a->setProperty("keydefault", key);
// Set to application context so that ViewerWindows still trigger shortcuts
a->setShortcutContext(Qt::ApplicationShortcut);
}
}
void Menu::Init()
{
// HACK: Disables embossing on disabled text for a slightly nicer UI
QPalette p = palette();
p.setColor(QPalette::Disabled, QPalette::Light, QColor(0, 0, 0, 0));
setPalette(p);
}
}
| 2,321
|
C++
|
.cpp
| 84
| 24.928571
| 97
| 0.725339
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,918
|
menushared.cpp
|
olive-editor_olive/app/widget/menu/menushared.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "menushared.h"
#include <QActionGroup>
#include "core.h"
#include "panel/panelmanager.h"
#include "panel/timeline/timeline.h"
#include "window/mainwindow/mainwindow.h"
namespace olive {
MenuShared* MenuShared::instance_ = nullptr;
MenuShared::MenuShared()
{
// "New" menu shared items
new_project_item_ = Menu::CreateItem(this, "newproj", Core::instance(), &Core::CreateNewProject, tr("Ctrl+N"));
new_sequence_item_ = Menu::CreateItem(this, "newseq", Core::instance(), &Core::CreateNewSequence, tr("Ctrl+Shift+N"));
new_folder_item_ = Menu::CreateItem(this, "newfolder", Core::instance(), &Core::CreateNewFolder);
// "Edit" menu shared items
edit_cut_item_ = Menu::CreateItem(this, "cut", this, &MenuShared::CutTriggered, tr("Ctrl+X"));
edit_copy_item_ = Menu::CreateItem(this, "copy", this, &MenuShared::CopyTriggered, tr("Ctrl+C"));
edit_paste_item_ = Menu::CreateItem(this, "paste", this, &MenuShared::PasteTriggered, tr("Ctrl+V"));
edit_paste_insert_item_ = Menu::CreateItem(this, "pasteinsert", this, &MenuShared::PasteInsertTriggered, tr("Ctrl+Shift+V"));
edit_duplicate_item_ = Menu::CreateItem(this, "duplicate", this, &MenuShared::DuplicateTriggered, tr("Ctrl+D"));
edit_rename_item_ = Menu::CreateItem(this, "rename", this, &MenuShared::RenameSelectedTriggered, tr("F2"));
edit_delete_item_ = Menu::CreateItem(this, "delete", this, &MenuShared::DeleteSelectedTriggered, tr("Del"));
edit_ripple_delete_item_ = Menu::CreateItem(this, "rippledelete", this, &MenuShared::RippleDeleteTriggered, tr("Shift+Del"));
edit_split_item_ = Menu::CreateItem(this, "split", this, &MenuShared::SplitAtPlayheadTriggered, tr("Ctrl+K"));
edit_speedduration_item_ = Menu::CreateItem(this, "speeddur", this, &MenuShared::SpeedDurationTriggered, tr("Ctrl+R"));
// List of addable items
for (int i=0;i<Tool::kAddableCount;i++) {
Tool::AddableObject t = static_cast<Tool::AddableObject>(i);
QAction *a = Menu::CreateItem(this, QStringLiteral("add:%1").arg(Tool::GetAddableObjectID(t)), this, &MenuShared::AddableItemTriggered);
a->setData(t);
addable_items_.append(a);
}
// "In/Out" menu shared items
inout_set_in_item_ = Menu::CreateItem(this, "setinpoint", this, &MenuShared::SetInTriggered, tr("I"));
inout_set_out_item_ = Menu::CreateItem(this, "setoutpoint", this, &MenuShared::SetOutTriggered, tr("O"));
inout_reset_in_item_ = Menu::CreateItem(this, "resetin", this, &MenuShared::ResetInTriggered);
inout_reset_out_item_ = Menu::CreateItem(this, "resetout", this, &MenuShared::ResetOutTriggered);
inout_clear_inout_item_ = Menu::CreateItem(this, "clearinout", this, &MenuShared::ClearInOutTriggered, tr("G"));
// "Clip Edit" menu shared items
clip_add_default_transition_item_ = Menu::CreateItem(this, "deftransition", this, &MenuShared::DefaultTransitionTriggered, tr("Ctrl+Shift+D"));
clip_link_unlink_item_ = Menu::CreateItem(this, "linkunlink", this, &MenuShared::ToggleLinksTriggered, tr("Ctrl+L"));
clip_enable_disable_item_ = Menu::CreateItem(this, "enabledisable", this, &MenuShared::EnableDisableTriggered, tr("Shift+E"));
clip_nest_item_ = Menu::CreateItem(this, "nest", this, &MenuShared::NestTriggered);
// TimeRuler menu shared items
frame_view_mode_group_ = new QActionGroup(this);
view_timecode_view_dropframe_item_ = Menu::CreateItem(this, "modedropframe", this, &MenuShared::TimecodeDisplayTriggered);
view_timecode_view_dropframe_item_->setData(Timecode::kTimecodeDropFrame);
view_timecode_view_dropframe_item_->setCheckable(true);
frame_view_mode_group_->addAction(view_timecode_view_dropframe_item_);
view_timecode_view_nondropframe_item_ = Menu::CreateItem(this, "modenondropframe", this, &MenuShared::TimecodeDisplayTriggered);
view_timecode_view_nondropframe_item_->setData(Timecode::kTimecodeNonDropFrame);
view_timecode_view_nondropframe_item_->setCheckable(true);
frame_view_mode_group_->addAction(view_timecode_view_nondropframe_item_);
view_timecode_view_seconds_item_ = Menu::CreateItem(this, "modeseconds", this, &MenuShared::TimecodeDisplayTriggered);
view_timecode_view_seconds_item_->setData(Timecode::kTimecodeSeconds);
view_timecode_view_seconds_item_->setCheckable(true);
frame_view_mode_group_->addAction(view_timecode_view_seconds_item_);
view_timecode_view_frames_item_ = Menu::CreateItem(this, "modeframes", this, &MenuShared::TimecodeDisplayTriggered);
view_timecode_view_frames_item_->setData(Timecode::kFrames);
view_timecode_view_frames_item_->setCheckable(true);
frame_view_mode_group_->addAction(view_timecode_view_frames_item_);
view_timecode_view_milliseconds_item_ = Menu::CreateItem(this, "milliseconds", this, &MenuShared::TimecodeDisplayTriggered);
view_timecode_view_milliseconds_item_->setData(Timecode::kMilliseconds);
view_timecode_view_milliseconds_item_->setCheckable(true);
frame_view_mode_group_->addAction(view_timecode_view_milliseconds_item_);
// Color coding menu items
color_coding_menu_ = new ColorLabelMenu();
connect(color_coding_menu_, &ColorLabelMenu::ColorSelected, this, &MenuShared::ColorLabelTriggered);
Retranslate();
}
MenuShared::~MenuShared()
{
delete color_coding_menu_;
}
void MenuShared::CreateInstance()
{
instance_ = new MenuShared();
}
void MenuShared::DestroyInstance()
{
delete instance_;
}
void MenuShared::AddItemsForNewMenu(Menu *m)
{
m->addAction(new_project_item_);
m->addSeparator();
m->addAction(new_sequence_item_);
m->addAction(new_folder_item_);
}
void MenuShared::AddItemsForEditMenu(Menu *m, bool for_clips)
{
m->addAction(Core::instance()->undo_stack()->GetUndoAction());
m->addAction(Core::instance()->undo_stack()->GetRedoAction());
m->addSeparator();
m->addAction(edit_cut_item_);
m->addAction(edit_copy_item_);
m->addAction(edit_paste_item_);
m->addAction(edit_paste_insert_item_);
m->addAction(edit_duplicate_item_);
m->addAction(edit_rename_item_);
m->addAction(edit_delete_item_);
if (for_clips) {
m->addAction(edit_ripple_delete_item_);
m->addAction(edit_split_item_);
m->addAction(edit_speedduration_item_);
m->addSeparator();
m->addAction(clip_add_default_transition_item_);
m->addAction(clip_link_unlink_item_);
m->addAction(clip_enable_disable_item_);
m->addAction(clip_nest_item_);
}
}
void MenuShared::AddItemsForAddableObjectsMenu(Menu *m)
{
for (QAction *a : qAsConst(addable_items_)) {
a->setChecked((a->data().toInt() == Core::instance()->GetSelectedAddableObject()));
m->addAction(a);
}
}
void MenuShared::AddItemsForInOutMenu(Menu *m)
{
m->addAction(inout_set_in_item_);
m->addAction(inout_set_out_item_);
m->addSeparator();
m->addAction(inout_reset_in_item_);
m->addAction(inout_reset_out_item_);
m->addAction(inout_clear_inout_item_);
}
void MenuShared::AddColorCodingMenu(Menu *m)
{
m->addMenu(color_coding_menu_);
}
void MenuShared::AddItemsForClipEditMenu(Menu *m)
{
m->addAction(clip_add_default_transition_item_);
m->addAction(clip_link_unlink_item_);
m->addAction(clip_enable_disable_item_);
m->addAction(clip_nest_item_);
}
void MenuShared::AddItemsForTimeRulerMenu(Menu *m)
{
m->addAction(view_timecode_view_dropframe_item_);
m->addAction(view_timecode_view_nondropframe_item_);
m->addAction(view_timecode_view_seconds_item_);
m->addAction(view_timecode_view_frames_item_);
m->addAction(view_timecode_view_milliseconds_item_);
}
void MenuShared::AboutToShowTimeRulerActions(const rational& timebase)
{
QList<QAction*> timecode_display_actions = frame_view_mode_group_->actions();
Timecode::Display current_timecode_display = Core::instance()->GetTimecodeDisplay();
// Only show the drop-frame option if the timebase is drop-frame
view_timecode_view_dropframe_item_->setVisible(!timebase.isNull() && Timecode::timebase_is_drop_frame(timebase));
if (!view_timecode_view_dropframe_item_->isVisible() && current_timecode_display == Timecode::kTimecodeDropFrame) {
// If the current setting is drop-frame, correct to non-drop frame
current_timecode_display = Timecode::kTimecodeNonDropFrame;
}
foreach (QAction* a, timecode_display_actions) {
if (a->data() == current_timecode_display) {
a->setChecked(true);
break;
}
}
}
MenuShared *MenuShared::instance()
{
return instance_;
}
void MenuShared::SplitAtPlayheadTriggered()
{
TimelinePanel* timeline = PanelManager::instance()->MostRecentlyFocused<TimelinePanel>();
if (timeline != nullptr) {
timeline->SplitAtPlayhead();
}
}
void MenuShared::DeleteSelectedTriggered()
{
PanelManager::instance()->CurrentlyFocused()->DeleteSelected();
}
void MenuShared::RippleDeleteTriggered()
{
PanelManager::instance()->CurrentlyFocused()->RippleDelete();
}
void MenuShared::SetInTriggered()
{
PanelManager::instance()->CurrentlyFocused()->SetIn();
}
void MenuShared::SetOutTriggered()
{
PanelManager::instance()->CurrentlyFocused()->SetOut();
}
void MenuShared::ResetInTriggered()
{
PanelManager::instance()->CurrentlyFocused()->ResetIn();
}
void MenuShared::ResetOutTriggered()
{
PanelManager::instance()->CurrentlyFocused()->ResetOut();
}
void MenuShared::ClearInOutTriggered()
{
PanelManager::instance()->CurrentlyFocused()->ClearInOut();
}
void MenuShared::ToggleLinksTriggered()
{
PanelManager::instance()->CurrentlyFocused()->ToggleLinks();
}
void MenuShared::CutTriggered()
{
PanelManager::instance()->CurrentlyFocused()->CutSelected();
}
void MenuShared::CopyTriggered()
{
PanelManager::instance()->CurrentlyFocused()->CopySelected();
}
void MenuShared::PasteTriggered()
{
PanelManager::instance()->CurrentlyFocused()->Paste();
}
void MenuShared::PasteInsertTriggered()
{
PanelManager::instance()->CurrentlyFocused()->PasteInsert();
}
void MenuShared::DuplicateTriggered()
{
PanelManager::instance()->CurrentlyFocused()->Duplicate();
}
void MenuShared::RenameSelectedTriggered()
{
PanelManager::instance()->CurrentlyFocused()->RenameSelected();
}
void MenuShared::EnableDisableTriggered()
{
PanelManager::instance()->CurrentlyFocused()->ToggleSelectedEnabled();
}
void MenuShared::NestTriggered()
{
PanelManager::instance()->MostRecentlyFocused<TimelinePanel>()->NestSelectedClips();
}
void MenuShared::DefaultTransitionTriggered()
{
PanelManager::instance()->MostRecentlyFocused<TimelinePanel>()->AddDefaultTransitionsToSelected();
}
void MenuShared::TimecodeDisplayTriggered()
{
// Assume the sender is a QAction
QAction* action = static_cast<QAction*>(sender());
// Assume its data() is a member of Timecode::Display
Timecode::Display display = static_cast<Timecode::Display>(action->data().toInt());
// Set the current display mode
Core::instance()->SetTimecodeDisplay(display);
}
void MenuShared::ColorLabelTriggered(int color_index)
{
PanelManager::instance()->CurrentlyFocused()->SetColorLabel(color_index);
}
void MenuShared::SpeedDurationTriggered()
{
TimelinePanel* timeline = PanelManager::instance()->MostRecentlyFocused<TimelinePanel>();
if (timeline) {
timeline->ShowSpeedDurationDialogForSelectedClips();
}
}
void MenuShared::AddableItemTriggered()
{
QAction *a = static_cast<QAction*>(sender());
Tool::AddableObject i = static_cast<Tool::AddableObject>(a->data().toInt());
Core::instance()->SetTool(Tool::kAdd);
Core::instance()->SetSelectedAddableObject(i);
}
void MenuShared::Retranslate()
{
// "New" menu shared items
new_project_item_->setText(tr("&Project"));
new_sequence_item_->setText(tr("&Sequence"));
new_folder_item_->setText(tr("&Folder"));
// "Edit" menu shared items
edit_cut_item_->setText(tr("Cu&t"));
edit_copy_item_->setText(tr("Cop&y"));
edit_paste_item_->setText(tr("&Paste"));
edit_paste_insert_item_->setText(tr("Paste Insert"));
edit_duplicate_item_->setText(tr("Duplicate"));
edit_rename_item_->setText(tr("Rename"));
edit_delete_item_->setText(tr("Delete"));
edit_ripple_delete_item_->setText(tr("Ripple Delete"));
edit_split_item_->setText(tr("Split"));
edit_speedduration_item_->setText(tr("Speed/Duration"));
for (QAction *a : qAsConst(addable_items_)) {
a->setText(Tool::GetAddableObjectName(static_cast<Tool::AddableObject>(a->data().toInt())));
}
// "In/Out" menu shared items
inout_set_in_item_->setText(tr("Set In Point"));
inout_set_out_item_->setText(tr("Set Out Point"));
inout_reset_in_item_->setText(tr("Reset In Point"));
inout_reset_out_item_->setText(tr("Reset Out Point"));
inout_clear_inout_item_->setText(tr("Clear In/Out Point"));
// "Clip Edit" menu shared items
clip_add_default_transition_item_->setText(tr("Add Default Transition"));
clip_link_unlink_item_->setText(tr("Link/Unlink"));
clip_enable_disable_item_->setText(tr("Enable/Disable"));
clip_nest_item_->setText(tr("Nest"));
// TimeRuler menu shared items
view_timecode_view_frames_item_->setText(tr("Frames"));
view_timecode_view_dropframe_item_->setText(tr("Drop Frame"));
view_timecode_view_nondropframe_item_->setText(tr("Non-Drop Frame"));
view_timecode_view_milliseconds_item_->setText(tr("Milliseconds"));
view_timecode_view_seconds_item_->setText(tr("Seconds"));
}
}
| 13,882
|
C++
|
.cpp
| 323
| 40.325077
| 145
| 0.743826
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,919
|
toolbarbutton.cpp
|
olive-editor_olive/app/widget/toolbar/toolbarbutton.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "toolbarbutton.h"
namespace olive {
ToolbarButton::ToolbarButton(QWidget *parent, const Tool::Item &tool) :
QPushButton(parent),
tool_(tool)
{
setCheckable(true);
}
const Tool::Item &ToolbarButton::tool()
{
return tool_;
}
}
| 958
|
C++
|
.cpp
| 27
| 32.925926
| 71
| 0.766558
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,920
|
toolbar.cpp
|
olive-editor_olive/app/widget/toolbar/toolbar.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "toolbar.h"
#include <QButtonGroup>
#include <QEvent>
#include <QPushButton>
#include <QResizeEvent>
#include <QVariant>
#include "node/factory.h"
#include "ui/icons/icons.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
namespace olive {
#define super QWidget
Toolbar::Toolbar(QWidget *parent) :
super(parent)
{
layout_ = new FlowLayout(this);
layout_->setContentsMargins(0, 0, 0, 0);
// Create standard tool buttons
btn_pointer_tool_ = CreateToolButton(Tool::kPointer);
btn_trackselect_tool_ = CreateToolButton(Tool::kTrackSelect);
btn_edit_tool_ = CreateToolButton(Tool::kEdit);
btn_ripple_tool_ = CreateToolButton(Tool::kRipple);
btn_rolling_tool_ = CreateToolButton(Tool::kRolling);
btn_razor_tool_ = CreateToolButton(Tool::kRazor);
btn_slip_tool_ = CreateToolButton(Tool::kSlip);
btn_slide_tool_ = CreateToolButton(Tool::kSlide);
btn_hand_tool_ = CreateToolButton(Tool::kHand);
btn_zoom_tool_ = CreateToolButton(Tool::kZoom);
btn_record_ = CreateToolButton(Tool::kRecord);
btn_transition_tool_ = CreateToolButton(Tool::kTransition);
btn_add_ = CreateToolButton(Tool::kAdd);
// Create snapping button, which is not actually a tool, it's a toggle option
btn_snapping_toggle_ = CreateNonToolButton();
connect(btn_snapping_toggle_, &QPushButton::clicked, this, &Toolbar::SnappingButtonClicked);
// Connect transition button to menu signal
connect(btn_transition_tool_, &QPushButton::clicked, this, &Toolbar::TransitionButtonClicked);
// Connect add button to menu signal
connect(btn_add_, &QPushButton::clicked, this, &Toolbar::AddButtonClicked);
Retranslate();
UpdateIcons();
}
void Toolbar::SetTool(const Tool::Item& tool)
{
// For each tool, set the "checked" state to whether the button's tool is the current tool
for (int i=0;i<toolbar_btns_.size();i++) {
ToolbarButton* btn = toolbar_btns_.at(i);
btn->setChecked(btn->tool() == tool);
}
}
void Toolbar::SetSnapping(const bool& snapping)
{
// Set checked state of snapping toggle
btn_snapping_toggle_->setChecked(snapping);
}
void Toolbar::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
Retranslate();
} else if (e->type() == QEvent::StyleChange) {
UpdateIcons();
}
super::changeEvent(e);
}
void Toolbar::resizeEvent(QResizeEvent *e)
{
super::resizeEvent(e);
int min_height = toolbar_btns_.size() * toolbar_btns_.first()->height() + (toolbar_btns_.size()-1) * layout_->verticalSpacing();
int new_height = e->size().height();
int columns_required = min_height / new_height + (min_height % new_height != 0);
setMinimumWidth(toolbar_btns_.first()->width() * columns_required + layout_->horizontalSpacing() * (columns_required-1) + 1);
}
void Toolbar::Retranslate()
{
btn_pointer_tool_->setToolTip(tr("Pointer Tool"));
btn_trackselect_tool_->setToolTip(tr("Track Select Tool"));
btn_edit_tool_->setToolTip(tr("Edit Tool"));
btn_ripple_tool_->setToolTip(tr("Ripple Tool"));
btn_rolling_tool_->setToolTip(tr("Rolling Tool"));
btn_razor_tool_->setToolTip(tr("Razor Tool"));
btn_slip_tool_->setToolTip(tr("Slip Tool"));
btn_slide_tool_->setToolTip(tr("Slide Tool"));
btn_hand_tool_->setToolTip(tr("Hand Tool"));
btn_zoom_tool_->setToolTip(tr("Zoom Tool"));
btn_transition_tool_->setToolTip(tr("Transition Tool"));
btn_record_->setToolTip(tr("Record Tool"));
btn_add_->setToolTip(tr("Add Tool"));
btn_snapping_toggle_->setToolTip(tr("Toggle Snapping"));
}
void Toolbar::UpdateIcons()
{
btn_pointer_tool_->setIcon(icon::ToolPointer);
btn_trackselect_tool_->setIcon(icon::ToolTrackSelect);
btn_edit_tool_->setIcon(icon::ToolEdit);
btn_ripple_tool_->setIcon(icon::ToolRipple);
btn_rolling_tool_->setIcon(icon::ToolRolling);
btn_razor_tool_->setIcon(icon::ToolRazor);
btn_slip_tool_->setIcon(icon::ToolSlip);
btn_slide_tool_->setIcon(icon::ToolSlide);
btn_hand_tool_->setIcon(icon::ToolHand);
btn_zoom_tool_->setIcon(icon::ZoomIn);
btn_record_->setIcon(icon::Record);
btn_transition_tool_->setIcon(icon::ToolTransition);
btn_add_->setIcon(icon::Add);
btn_snapping_toggle_->setIcon(icon::Snapping);
}
ToolbarButton* Toolbar::CreateToolButton(const Tool::Item& tool)
{
// Create a ToolbarButton object
ToolbarButton* b = new ToolbarButton(this, tool);
// Add it to the layout
layout_->addWidget(b);
// Add it to the list for iterating through later
toolbar_btns_.append(b);
// Connect it to the tool button click handler
connect(b, SIGNAL(clicked(bool)), this, SLOT(ToolButtonClicked()));
return b;
}
ToolbarButton *Toolbar::CreateNonToolButton()
{
// Create a ToolbarButton object
ToolbarButton* b = new ToolbarButton(this, Tool::kNone);
// Add it to the layout
layout_->addWidget(b);
return b;
}
void Toolbar::ToolButtonClicked()
{
// Get new tool from ToolbarButton object
Tool::Item new_tool = static_cast<ToolbarButton*>(sender())->tool();
// Set checked state of all tool buttons
// NOTE: Not necessary if this is appropriately connected to Core
//SetTool(new_tool);
// Emit signal that the tool just changed
emit ToolChanged(new_tool);
}
void Toolbar::SnappingButtonClicked(bool b)
{
emit SnappingChanged(b);
}
void Toolbar::AddButtonClicked()
{
Menu m(this);
MenuShared::instance()->AddItemsForAddableObjectsMenu(&m);
m.exec(QCursor::pos());
}
void Toolbar::TransitionButtonClicked()
{
Menu* m = NodeFactory::CreateMenu(this, false, Node::kCategoryTransition);
connect(m, &QMenu::triggered, this, &Toolbar::TransitionMenuItemTriggered);
m->exec(QCursor::pos());
delete m;
}
void Toolbar::TransitionMenuItemTriggered(QAction *a)
{
emit SelectedTransitionChanged(NodeFactory::GetIDFromMenuAction(a));
}
}
| 6,466
|
C++
|
.cpp
| 171
| 35.169591
| 130
| 0.73728
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,921
|
multicamwidget.cpp
|
olive-editor_olive/app/widget/multicam/multicamwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "multicamwidget.h"
#include <QShortcut>
#include "node/nodeundo.h"
#include "timeline/timelineundosplit.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
#define super TimeBasedWidget
MulticamWidget::MulticamWidget(QWidget *parent) :
super{false, false, parent},
node_(nullptr),
clip_(nullptr)
{
auto layout = new QVBoxLayout(this);
sizer_ = new ViewerSizer(this);
layout->addWidget(sizer_);
display_ = new MulticamDisplay(this);
display_->SetShowWidgetBackground(true);
connect(display_, &ViewerDisplayWidget::DragStarted, this, &MulticamWidget::DisplayClicked);
connect(sizer_, &ViewerSizer::RequestScale, display_, &ViewerDisplayWidget::SetMatrixZoom);
connect(sizer_, &ViewerSizer::RequestTranslate, display_, &ViewerDisplayWidget::SetMatrixTranslate);
connect(display_, &ViewerDisplayWidget::HandDragMoved, sizer_, &ViewerSizer::HandDragMove);
sizer_->SetWidget(display_);
layout->addWidget(this->ruler());
layout->addWidget(this->scrollbar());
for (int i=0; i<9; i++) {
new QShortcut(QStringLiteral("Ctrl+%1").arg(QString::number(i+1)), this, this, [this, i]{Switch(i, false);});
new QShortcut(QString::number(i+1), this, this, [this, i]{Switch(i, true);});
}
}
void MulticamWidget::SetMulticamNodeInternal(ViewerOutput *viewer, MultiCamNode *n, ClipBlock *clip)
{
if (GetConnectedNode() != viewer) {
ConnectViewerNode(viewer);
}
if (node_ != n) {
node_ = n;
display_->SetMulticamNode(n);
}
if (clip_ != clip) {
clip_ = clip;
}
}
void MulticamWidget::SetMulticamNode(ViewerOutput *viewer, MultiCamNode *n, ClipBlock *clip, const rational &time)
{
if (time.isNaN() || !GetConnectedNode() || time == GetConnectedNode()->GetPlayhead()) {
SetMulticamNodeInternal(viewer, n, clip);
play_queue_.clear();
} else {
MulticamNodeQueue m = {time, viewer, n, clip};
play_queue_.push_back(m);
}
}
void MulticamWidget::ConnectNodeEvent(ViewerOutput *n)
{
connect(n, &ViewerOutput::SizeChanged, sizer_, &ViewerSizer::SetChildSize);
connect(n, &ViewerOutput::PixelAspectChanged, sizer_, &ViewerSizer::SetPixelAspectRatio);
VideoParams vp = n->GetVideoParams();
sizer_->SetChildSize(vp.width(), vp.height());
sizer_->SetPixelAspectRatio(vp.pixel_aspect_ratio());
}
void MulticamWidget::DisconnectNodeEvent(ViewerOutput *n)
{
disconnect(n, &ViewerOutput::SizeChanged, sizer_, &ViewerSizer::SetChildSize);
disconnect(n, &ViewerOutput::PixelAspectChanged, sizer_, &ViewerSizer::SetPixelAspectRatio);
}
void MulticamWidget::TimeChangedEvent(const rational &t)
{
super::TimeChangedEvent(t);
if (!play_queue_.empty()) {
const MulticamNodeQueue &m = play_queue_.front();
if (m.time >= t) {
SetMulticamNodeInternal(m.viewer, m.node, m.clip);
play_queue_.pop_front();
}
}
}
void MulticamWidget::Switch(int source, bool split_clip)
{
if (!node_) {
return;
}
MultiUndoCommand *command = new MultiUndoCommand();
MultiCamNode *cam = node_;
ClipBlock *clip = clip_;
BlockSplitPreservingLinksCommand *split = nullptr;
if (clip_ && split_clip && clip_->in() < GetConnectedNode()->GetPlayhead() && clip_->out() > GetConnectedNode()->GetPlayhead()) {
QVector<Block*> blocks;
blocks.append(clip_);
blocks.append(clip_->block_links());
split = new BlockSplitPreservingLinksCommand(blocks, {GetConnectedNode()->GetPlayhead()});
split->redo_now();
command->add_child(split);
clip = static_cast<ClipBlock*>(split->GetSplit(clip_, 0));
cam = clip->FindMulticam();
}
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(cam, cam->kCurrentInput)), source));
for (Block *link : clip->block_links()) {
if (ClipBlock *clink = dynamic_cast<ClipBlock*>(link)) {
if (MultiCamNode *mlink = clink->FindMulticam()) {
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(mlink, mlink->kCurrentInput)), source));
}
}
}
Core::instance()->undo_stack()->push(command, tr("Switched Multi-Camera Source"));
display_->update();
emit Switched();
}
void MulticamWidget::DisplayClicked(const QPoint &p)
{
if (!node_) {
return;
}
QPointF click = display_->ScreenToScenePoint(p);
int width = display_->GetVideoParams().width();
int height = display_->GetVideoParams().height();
if (click.x() < 0 || click.y() < 0 || click.x() >= width || click.y() >= height) {
return;
}
int rows, cols;
node_->GetRowsAndColumns(&rows, &cols);
int multi = std::max(cols, rows);
int c = click.x() / (width/multi);
int r = click.y() / (height/multi);
int source = node_->RowsColsToIndex(r, c, rows, cols);
Switch(source, true);
}
}
| 5,472
|
C++
|
.cpp
| 141
| 35.425532
| 141
| 0.717585
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,922
|
multicamdisplay.cpp
|
olive-editor_olive/app/widget/multicam/multicamdisplay.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "multicamdisplay.h"
namespace olive {
#define super ViewerDisplayWidget
MulticamDisplay::MulticamDisplay(QWidget *parent) :
super(parent),
node_(nullptr),
rows_(0),
cols_(0)
{
}
void MulticamDisplay::OnPaint()
{
super::OnPaint();
if (node_) {
QPainter p(paint_device());
p.setPen(QPen(Qt::yellow, fontMetrics().height()/4));
p.setBrush(Qt::NoBrush);
int rows, cols;
node_->GetRowsAndColumns(&rows, &cols);
int multi = std::max(rows, cols);
int cell_width = width() / multi;
int cell_height = height() / multi;
int col, row;
node_->IndexToRowCols(node_->GetCurrentSource(), rows, cols, &row, &col);
QRect r(cell_width * col, cell_height * row, cell_width, cell_height);
p.drawRect(GenerateWorldTransform().mapRect(r));
}
}
void MulticamDisplay::OnDestroy()
{
shader_ = QVariant();
}
TexturePtr MulticamDisplay::LoadCustomTextureFromFrame(const QVariant &v)
{
if (v.canConvert<QVector<TexturePtr> >()) {
QVector<TexturePtr> tex = v.value<QVector<TexturePtr> >();
TexturePtr main = renderer()->CreateTexture(this->GetViewportParams());
int rows, cols;
MultiCamNode::GetRowsAndColumns(tex.size(), &rows, &cols);
if (shader_.isNull() || rows_ != rows || cols_ != cols) {
if (!shader_.isNull()) {
renderer()->DestroyNativeShader(shader_);
}
shader_ = renderer()->CreateNativeShader(ShaderCode(GenerateShaderCode(rows, cols)));
rows_ = rows;
cols_ = cols;
}
ShaderJob job;
for (int i=0; i<tex.size(); i++) {
int c, r;
MultiCamNode::IndexToRowCols(i, rows, cols, &r, &c);
job.Insert(QStringLiteral("tex_%1_%2").arg(QString::number(r), QString::number(c)), NodeValue(NodeValue::kTexture, tex.at(i)));
}
renderer()->BlitToTexture(shader_, job, main.get());
return main;
} else {
return super::LoadCustomTextureFromFrame(v);
}
}
QString dblToGlsl(double d)
{
return QString::number(d, 'f');
}
QString MulticamDisplay::GenerateShaderCode(int rows, int cols)
{
int multiplier = std::max(cols, rows);
QStringList shader;
shader.append(QStringLiteral("in vec2 ove_texcoord;"));
shader.append(QStringLiteral("out vec4 frag_color;"));
for (int x=0;x<cols;x++) {
for (int y=0;y<rows;y++) {
shader.append(QStringLiteral("uniform sampler2D tex_%1_%2;").arg(QString::number(y), QString::number(x)));
shader.append(QStringLiteral("uniform bool tex_%1_%2_enabled;").arg(QString::number(y), QString::number(x)));
}
}
shader.append(QStringLiteral("void main() {"));
for (int x=0;x<cols;x++) {
if (x > 0) {
shader.append(QStringLiteral(" else"));
}
if (x == cols-1) {
shader.append(QStringLiteral(" {"));
} else {
shader.append(QStringLiteral(" if (ove_texcoord.x < %1) {").arg(dblToGlsl(double(x+1)/double(multiplier))));
}
for (int y=0;y<rows;y++) {
if (y > 0) {
shader.append(QStringLiteral(" else"));
}
if (y == rows-1) {
shader.append(QStringLiteral(" {"));
} else {
shader.append(QStringLiteral(" if (ove_texcoord.y < %1) {").arg(dblToGlsl(double(y+1)/double(multiplier))));
}
QString input = QStringLiteral("tex_%1_%2").arg(QString::number(y), QString::number(x));
shader.append(QStringLiteral(" vec2 coord = vec2((ove_texcoord.x+%1)*%2, (ove_texcoord.y+%3)*%4);").arg(
dblToGlsl( - double(x)/double(multiplier)),
dblToGlsl(multiplier),
dblToGlsl( - double(y)/double(multiplier)),
dblToGlsl(multiplier)
));
shader.append(QStringLiteral(" if (%1_enabled && coord.x >= 0.0 && coord.x < 1.0 && coord.y >= 0.0 && coord.y < 1.0) {").arg(input));
shader.append(QStringLiteral(" frag_color = texture(%1, coord);").arg(input));
shader.append(QStringLiteral(" } else {"));
shader.append(QStringLiteral(" discard;"));
shader.append(QStringLiteral(" }"));
shader.append(QStringLiteral(" }"));
}
shader.append(QStringLiteral(" }"));
}
shader.append(QStringLiteral("}"));
return shader.join('\n');
}
void MulticamDisplay::SetMulticamNode(MultiCamNode *n)
{
node_ = n;
}
}
| 5,027
|
C++
|
.cpp
| 132
| 32.94697
| 144
| 0.644902
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,923
|
handmovableview.cpp
|
olive-editor_olive/app/widget/handmovableview/handmovableview.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "handmovableview.h"
#include <QMouseEvent>
#include "config/config.h"
#include "core.h"
namespace olive {
#define super QGraphicsView
HandMovableView::HandMovableView(QWidget* parent) :
super(parent),
dragging_hand_(false),
is_timeline_axes_(false)
{
connect(Core::instance(), &Core::ToolChanged, this, &HandMovableView::ApplicationToolChanged);
}
void HandMovableView::ApplicationToolChanged(Tool::Item tool)
{
if (tool == Tool::kHand) {
setDragMode(ScrollHandDrag);
setInteractive(false);
} else {
setDragMode(default_drag_mode_);
setInteractive(true);
}
ToolChangedEvent(tool);
}
bool HandMovableView::HandPress(QMouseEvent *event)
{
if (event->button() == Qt::MiddleButton) {
pre_hand_drag_mode_ = dragMode();
dragging_hand_ = true;
setDragMode(ScrollHandDrag);
setInteractive(false);
// Transform mouse event to act like the left button is pressed
QMouseEvent transformed(event->type(),
event->pos(),
Qt::LeftButton,
Qt::LeftButton,
event->modifiers());
transformed_pos_ = QPoint(0, 0);
super::mousePressEvent(&transformed);
return true;
}
return false;
}
bool HandMovableView::HandMove(QMouseEvent *event)
{
if (dragging_hand_) {
// Transform mouse event to act like the left button is pressed
QPoint adjustment(0, 0);
QMouseEvent transformed(event->type(),
event->pos() - transformed_pos_,
Qt::LeftButton,
Qt::LeftButton,
event->modifiers());
if (event->pos().x() < 0) {
transformed_pos_.setX(transformed_pos_.x() + width());
adjustment.setX(width());
} else if (event->pos().x() >= width()) {
transformed_pos_.setX(transformed_pos_.x() - width());
adjustment.setX(-width());
}
if (event->pos().y() < 0) {
transformed_pos_.setY(transformed_pos_.y() + height());
adjustment.setY(height());
} else if (event->pos().y() >= height()) {
transformed_pos_.setY(transformed_pos_.y() - height());
adjustment.setY(-height());
}
if (!adjustment.isNull()) {
QCursor::setPos(QCursor::pos() + adjustment);
}
super::mouseMoveEvent(&transformed);
}
return dragging_hand_;
}
bool HandMovableView::HandRelease(QMouseEvent *event)
{
if (dragging_hand_) {
// Transform mouse event to act like the left button is pressed
QMouseEvent transformed(event->type(),
event->localPos(),
event->windowPos(),
event->screenPos(),
Qt::LeftButton,
Qt::LeftButton,
event->modifiers(),
event->source());
super::mouseReleaseEvent(&transformed);
setInteractive(true);
setDragMode(pre_hand_drag_mode_);
dragging_hand_ = false;
return true;
}
return false;
}
void HandMovableView::SetDefaultDragMode(HandMovableView::DragMode mode)
{
default_drag_mode_ = mode;
setDragMode(default_drag_mode_);
}
const HandMovableView::DragMode &HandMovableView::GetDefaultDragMode() const
{
return default_drag_mode_;
}
bool HandMovableView::WheelEventIsAZoomEvent(QWheelEvent *event)
{
return (static_cast<bool>(event->modifiers() & Qt::ControlModifier) == !OLIVE_CONFIG("ScrollZooms").toBool());
}
qreal HandMovableView::GetScrollZoomMultiplier(QWheelEvent *event)
{
qreal v = (static_cast<qreal>(event->angleDelta().x() + event->angleDelta().y()) * 0.001);
if (event->inverted()) {
v = -v;
}
return 1.0 + v;
}
void HandMovableView::wheelEvent(QWheelEvent *event)
{
if (WheelEventIsAZoomEvent(event)) {
if (!event->angleDelta().isNull()) {
qreal multiplier = GetScrollZoomMultiplier(event);
QPointF cursor_pos;
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
cursor_pos = event->position();
#else
cursor_pos = event->posF();
#endif
ZoomIntoCursorPosition(event, multiplier, cursor_pos);
}
} else if (is_timeline_axes_) {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
QPoint angle_delta = event->angleDelta();
if (OLIVE_CONFIG("InvertTimelineScrollAxes").toBool() // Check if config is set to invert timeline axes
&& event->source() != Qt::MouseEventSynthesizedBySystem) { // Never flip axes on Apple trackpads though
angle_delta = QPoint(angle_delta.y(), angle_delta.x());
}
QWheelEvent e(
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
event->position(),
event->globalPosition(),
#else
event->pos(),
event->globalPos(),
#endif
event->pixelDelta(),
angle_delta,
event->buttons(),
event->modifiers(),
event->phase(),
event->inverted(),
event->source()
);
#else
Qt::Orientation orientation = event->orientation();
if (OLIVE_CONFIG("InvertTimelineScrollAxes").toBool()) {
orientation = (orientation == Qt::Horizontal) ? Qt::Vertical : Qt::Horizontal;
}
QWheelEvent e(
event->pos(),
event->globalPos(),
event->pixelDelta(),
event->angleDelta(),
event->delta(),
orientation,
event->buttons(),
event->modifiers()
);
#endif
super::wheelEvent(&e);
} else {
super::wheelEvent(event);
}
}
void HandMovableView::ZoomIntoCursorPosition(QWheelEvent *event, double multiplier, const QPointF &cursor_pos)
{
Q_UNUSED(event)
Q_UNUSED(multiplier)
Q_UNUSED(cursor_pos)
}
}
| 6,465
|
C++
|
.cpp
| 193
| 26.958549
| 112
| 0.636349
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,924
|
audiomonitor.cpp
|
olive-editor_olive/app/widget/audiomonitor/audiomonitor.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "audiomonitor.h"
#include <QApplication>
#include <QDebug>
#include <QPainter>
#include "audio/audiomanager.h"
#include "common/decibel.h"
#include "common/qtutils.h"
namespace olive {
const int kDecibelStep = 6;
const int kDecibelMinimum = -198; // Must be divisible by kDecibelStep for infinity to appear
const int kMaximumSmoothness = 8;
QVector<AudioMonitor*> AudioMonitor::instances_;
AudioMonitor::AudioMonitor(QWidget *parent) :
QOpenGLWidget(parent),
waveform_(nullptr),
cached_channels_(0)
{
instances_.append(this);
values_.resize(kMaximumSmoothness);
this->setMinimumWidth(this->fontMetrics().height());
}
AudioMonitor::~AudioMonitor()
{
instances_.removeOne(this);
}
void AudioMonitor::SetParams(const AudioParams ¶ms)
{
if (params_ != params) {
params_ = params;
for (int i=0;i<values_.size();i++) {
values_[i].resize(params_.channel_count());
values_[i].fill(0);
}
peaked_.resize(params_.channel_count());
peaked_.fill(false);
update();
}
}
void AudioMonitor::Stop()
{
waveform_ = nullptr;
// We don't stop the update loop here so that the monitor can show a smooth fade out. The update
// loop will stop itself since file_ and waveform_ are null.
}
void AudioMonitor::PushSampleBuffer(const SampleBuffer &d)
{
if (!params_.channel_count()) {
return;
}
QVector<double> v(params_.channel_count(), 0);
AudioVisualWaveform::Sample summed = AudioVisualWaveform::SumSamples(d, 0, d.sample_count());
AudioVisualWaveformSampleToInternalValues(summed, v);
// Fill values because they get averaged out for smoothing
values_.fill(v);
SetUpdateLoop(true);
}
void AudioMonitor::StartWaveform(const AudioWaveformCache *waveform, const rational &start, int playback_speed)
{
Stop();
waveform_length_ = waveform->length();
if (start >= waveform_length_) {
return;
}
waveform_ = waveform;
waveform_time_ = start;
playback_speed_ = playback_speed;
last_time_ = QDateTime::currentMSecsSinceEpoch();
SetUpdateLoop(true);
}
void AudioMonitor::SetUpdateLoop(bool e)
{
if (e) {
connect(this, &AudioMonitor::frameSwapped, this, static_cast<void(AudioMonitor::*)()>(&AudioMonitor::update));
update();
} else {
disconnect(this, &AudioMonitor::frameSwapped, this, static_cast<void(AudioMonitor::*)()>(&AudioMonitor::update));
}
}
void AudioMonitor::paintGL()
{
QPainter p(this);
QPalette palette = qApp->palette();
QRect geometry(0, 0, width(), height());
p.fillRect(geometry, palette.window().color());
if (!params_.channel_count()) {
return;
}
QFont f = p.font();
f.setPointSizeF(f.pointSizeF() * 0.75);
p.setFont(f);
QFontMetrics fm = p.fontMetrics();
int font_height = fm.height();
bool horizontal = this->width() > this->height();
int minimum_width = this->fontMetrics().height() * 3;
// Determine rect where the main meter will go
QRect full_meter_rect = geometry;
// Create rect where decibel markings will go on the side
QRect db_labels_rect;
bool draw_text;
// Width of each channel in the meter
int peaks_pos;
int channel_size;
int db_line_length = fm.horizontalAdvance(QStringLiteral("-"));
int db_width = QtUtils::QFontMetricsWidth(p.fontMetrics(), "-00 ");
if (horizontal) {
// Insert peaks area
full_meter_rect.adjust(0, 0, -font_height, 0);
draw_text = (height() >= minimum_width);
// Derive dB label rect
if (draw_text) {
// Insert meter rect
full_meter_rect.adjust(db_width/2, 0, 0, -font_height);
db_labels_rect = full_meter_rect;
db_labels_rect.setTop(db_labels_rect.bottom());
db_labels_rect.setHeight(font_height + db_line_length);
}
// Divide height by channel count
channel_size = full_meter_rect.height() / params_.channel_count();
// Set peaks Y to right-most
peaks_pos = full_meter_rect.right();
} else {
// Insert peaks rect
full_meter_rect.adjust(0, font_height, 0, 0);
draw_text = (width() >= minimum_width);
// Derive dB label rect
if (draw_text) {
int db_width_and_line = db_width + db_line_length;
// Insert meter rect
full_meter_rect.adjust(db_width_and_line, 0, 0, -font_height/2);
db_labels_rect = full_meter_rect;
db_labels_rect.setX(0);
db_labels_rect.setWidth(db_width_and_line);
}
// Divide width by channel count
channel_size = full_meter_rect.width() / params_.channel_count();
// Set peaks Y to very top
peaks_pos = 0;
}
if (cached_background_.size() != size()
|| cached_channels_ != params_.channel_count()) {
cached_channels_ = params_.channel_count();
// Generate new background
cached_background_ = QPixmap(size());
cached_background_.fill(Qt::transparent);
QPainter cached_painter(&cached_background_);
if (draw_text) {
cached_painter.setFont(f);
// Draw decibel markings
QRect last_db_marking_rect;
cached_painter.setPen(palette.text().color());
for (int i=0;i>=kDecibelMinimum;i-=kDecibelStep) {
QString db_label;
qreal log_val;
if (i == kDecibelMinimum) {
db_label = QStringLiteral("-∞ ");
log_val = 0;
} else {
db_label = QStringLiteral("%1 ").arg(i);
log_val = Decibel::toLogarithmic(i);
}
QLine db_line;
QRect db_marking_rect;
bool overlaps_infinity = false;
if (horizontal) {
int x = db_labels_rect.x() + qRound(log_val * db_labels_rect.width());
db_marking_rect = QRect(x - db_width/2, db_labels_rect.top() + db_line_length, db_width, db_labels_rect.height() - db_line_length);
db_line = QLine(x, db_labels_rect.top(), x, db_labels_rect.top() + db_line_length);
overlaps_infinity = db_marking_rect.left() < db_labels_rect.left() + db_width/2;
} else {
int y = db_labels_rect.y() + db_labels_rect.height() - qRound(log_val * db_labels_rect.height());
db_marking_rect = QRect(db_labels_rect.x(), y - font_height/2, db_labels_rect.width() - db_line_length, font_height);
db_line = QLine(db_marking_rect.right()+1, y, db_labels_rect.width(), y);
overlaps_infinity = db_marking_rect.bottom() >= db_labels_rect.bottom()-font_height;
}
if (overlaps_infinity && i == kDecibelMinimum) {
overlaps_infinity = false;
}
// Prevent any dB markings overlapping
if (i == 0 || (!db_marking_rect.intersects(last_db_marking_rect) && !overlaps_infinity)) {
cached_painter.drawText(db_marking_rect, Qt::AlignCenter, db_label);
cached_painter.drawLine(db_line);
last_db_marking_rect = db_marking_rect;
}
}
}
{
// Draw bars
QLinearGradient g;
if (horizontal) {
g.setStart(full_meter_rect.topRight());
g.setFinalStop(full_meter_rect.topLeft());
} else {
g.setStart(full_meter_rect.topLeft());
g.setFinalStop(full_meter_rect.bottomLeft());
}
g.setStops({
QGradientStop(0.0, Qt::red),
QGradientStop(0.25, Qt::yellow),
QGradientStop(1.0, Qt::green)
});
cached_painter.setPen(Qt::black);
for (int i=0;i<params_.channel_count();i++) {
QRect peaks_rect, meter_rect;
if (horizontal) {
int channel_y = full_meter_rect.y() + channel_size * i;
peaks_rect = QRect(peaks_pos, channel_y, font_height, channel_size);
meter_rect = full_meter_rect;
meter_rect.setY(channel_y);
meter_rect.setHeight(channel_size);
} else {
int channel_x = full_meter_rect.x() + channel_size * i;
peaks_rect = QRect(channel_x, peaks_pos, channel_size, font_height);
meter_rect = full_meter_rect;
meter_rect.setX(channel_x);
meter_rect.setWidth(channel_size);
}
// Draw peak rects
cached_painter.setBrush(Qt::red);
cached_painter.drawRect(peaks_rect);
// Draw gradient meter
cached_painter.setBrush(g);
cached_painter.drawRect(meter_rect);
}
}
}
p.drawPixmap(0, 0, cached_background_);
QVector<double> v(params_.channel_count(), 0);
if (IsPlaying()) {
// Determines how many milliseconds have passed since last update
qint64 current_time = QDateTime::currentMSecsSinceEpoch();
qint64 delta_time = current_time - last_time_;
int abs_speed = qAbs(playback_speed_);
// Multiply by speed if the speed is not 1
if (abs_speed != 1) {
delta_time *= abs_speed;
}
if (waveform_) {
UpdateValuesFromWaveform(v, delta_time);
if (waveform_time_ >= waveform_length_) {
Stop();
}
}
last_time_ = current_time;
}
PushValue(v);
QVector<double> vals = GetAverages();
p.setBrush(QColor(0, 0, 0, 128));
p.setPen(Qt::NoPen);
bool all_zeroes = true;
for (int i=0;i<params_.channel_count();i++) {
// Validate value and whether it peaked
double vol = vals.at(i);
if (vol > 1.0) {
peaked_[i] = true;
}
if (all_zeroes && !qIsNull(vol)) {
all_zeroes = false;
}
// Convert val to logarithmic scale
vol = Decibel::LinearToLogarithmic(vol);
QRect peaks_rect, meter_rect;
if (horizontal) {
int channel_y = full_meter_rect.y() + channel_size * i;
peaks_rect = QRect(peaks_pos, channel_y, font_height, channel_size);
meter_rect = full_meter_rect;
meter_rect.setY(channel_y);
meter_rect.setHeight(channel_size);
meter_rect.adjust(qRound(meter_rect.width() * vol), 0, 0, 0);
} else {
int channel_x = full_meter_rect.x() + channel_size * i;
peaks_rect = QRect(channel_x, peaks_pos, channel_size, font_height);
meter_rect = full_meter_rect;
meter_rect.setX(channel_x);
meter_rect.setWidth(channel_size);
meter_rect.adjust(0, 0, 0, -qRound(meter_rect.height() * vol));
}
p.drawRect(meter_rect);
if (!peaked_.at(i)) {
p.drawRect(peaks_rect);
}
}
if (all_zeroes && !IsPlaying()) {
// Optimize by disabling the update loop
SetUpdateLoop(false);
}
}
void AudioMonitor::mousePressEvent(QMouseEvent *)
{
peaked_.fill(false);
update();
}
void AudioMonitor::UpdateValuesFromWaveform(QVector<double> &v, qint64 delta_time)
{
// Delta time is provided in milliseconds, so we convert to seconds in rational
rational length(delta_time, 1000);
AudioVisualWaveform::Sample sum = waveform_->GetSummaryFromTime(waveform_time_, length);
AudioVisualWaveformSampleToInternalValues(sum, v);
waveform_time_ += length;
}
void AudioMonitor::AudioVisualWaveformSampleToInternalValues(const AudioVisualWaveform::Sample &in, QVector<double> &out)
{
for (size_t i=0; i<in.size(); i++) {
float max = qMax(qAbs(in.at(i).min), qAbs(in.at(i).max));
int output_index = i%out.size();
if (max > out.at(output_index)) {
out[output_index] = max;
}
}
}
void AudioMonitor::PushValue(const QVector<double> &v)
{
int lim = values_.size()-1;
for (int i=0; i<lim; i++) {
values_[i] = values_[i+1];
}
values_[lim] = v;
}
void AudioMonitor::BytesToSampleSummary(const QByteArray &b, QVector<double> &v)
{
const float* samples = reinterpret_cast<const float*>(b.constData());
int nb_samples = b.size() / sizeof(float);
for (int i=0;i<nb_samples;i++) {
int channel = i % params_.channel_count();
float abs_sample = samples[i];
if (abs_sample > v.at(channel)) {
v.replace(channel, abs_sample);
}
}
}
QVector<double> AudioMonitor::GetAverages() const
{
QVector<double> v(params_.channel_count(), 0);
for (int i=0;i<values_.size();i++) {
for (int j=0;j<v.size();j++) {
v[j] += values_.at(i).at(j);
}
}
for (int i=0;i<v.size();i++) {
v[i] /= static_cast<double>(values_.size());
}
return v;
}
}
| 12,736
|
C++
|
.cpp
| 357
| 30.333333
| 141
| 0.653391
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,925
|
pixelsampler.cpp
|
olive-editor_olive/app/widget/pixelsampler/pixelsampler.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "pixelsampler.h"
#include <QVBoxLayout>
namespace olive {
PixelSamplerWidget::PixelSamplerWidget(QWidget *parent) :
QGroupBox(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
box_ = new ColorPreviewBox();
QFontMetrics fm = fontMetrics();
int box_sz = fm.height() * 2;
box_->setFixedSize(box_sz, box_sz);
layout->addWidget(box_);
label_ = new QLabel();
layout->addWidget(label_);
setTitle(tr("Color"));
UpdateLabelInternal();
}
void PixelSamplerWidget::SetValues(const Color &color)
{
color_ = color;
UpdateLabelInternal();
}
void PixelSamplerWidget::UpdateLabelInternal()
{
box_->SetColor(color_);
label_->setText(tr("<html>"
"<font color='#FF8080'>R: %1 (%5)</font><br>"
"<font color='#80FF80'>G: %2 (%6)</font><br>"
"<font color='#8080FF'>B: %3 (%7)</font><br>"
"A: %4 (%8)"
"</html>").arg(QString::number(color_.red()),
QString::number(color_.green()),
QString::number(color_.blue()),
QString::number(color_.alpha()),
QString::number(int(color_.red()*255.0)),
QString::number(int(color_.green()*255.0)),
QString::number(int(color_.blue()*255.0)),
QString::number(int(color_.alpha()*255.0))));
}
ManagedPixelSamplerWidget::ManagedPixelSamplerWidget(QWidget *parent) :
QWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
display_view_ = new PixelSamplerWidget();
display_view_->setTitle(tr("Display"));
layout->addWidget(display_view_);
reference_view_ = new PixelSamplerWidget();
reference_view_->setTitle(tr("Reference"));
layout->addWidget(reference_view_);
}
void ManagedPixelSamplerWidget::SetValues(const Color &reference, const Color &display)
{
reference_view_->SetValues(reference);
display_view_->SetValues(display);
}
}
| 2,834
|
C++
|
.cpp
| 71
| 32.521127
| 87
| 0.637491
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,926
|
histogram.cpp
|
olive-editor_olive/app/widget/scope/histogram/histogram.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "histogram.h"
#include <QPainter>
#include <QtMath>
#include <QVector2D>
#include "common/qtutils.h"
#include "node/node.h"
namespace olive {
#define super ScopeBase
HistogramScope::HistogramScope(QWidget* parent) :
super(parent)
{
}
void HistogramScope::OnInit()
{
super::OnInit();
ShaderCode secondary_code(FileFunctions::ReadFileAsString(":/shaders/rgbhistogram_secondary.frag"),
FileFunctions::ReadFileAsString(":/shaders/rgbhistogram.vert"));
pipeline_secondary_ = renderer()->CreateNativeShader(secondary_code);
}
void HistogramScope::OnDestroy()
{
pipeline_secondary_.clear();
texture_row_sums_ = nullptr;
super::OnDestroy();
}
ShaderCode HistogramScope::GenerateShaderCode()
{
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/rgbhistogram.frag"),
FileFunctions::ReadFileAsString(":/shaders/default.vert"));
}
void HistogramScope::DrawScope(TexturePtr managed_tex, QVariant pipeline)
{
float histogram_scale = 0.80f;
// This value is eyeballed for usefulness. Until we have a geometry
// shader approach, it is impossible to normalize against a peak
// sum of image values.
float histogram_base = 2.5f;
float histogram_power = 1.0f / histogram_base;
ShaderJob shader_job;
shader_job.Insert(QStringLiteral("viewport"), NodeValue(NodeValue::kVec2, QVector2D(width(), height())));
shader_job.Insert(QStringLiteral("histogram_scale"), NodeValue(NodeValue::kFloat, histogram_scale));
shader_job.Insert(QStringLiteral("histogram_power"), NodeValue(NodeValue::kFloat, histogram_power));
if (!texture_row_sums_
|| texture_row_sums_->width() != this->width()
|| texture_row_sums_->height() != this->height()) {
texture_row_sums_ = renderer()->CreateTexture(VideoParams(width(), height(),
managed_tex->format(),
managed_tex->channel_count()));
}
// Draw managed texture to a sums texture
shader_job.Insert(QStringLiteral("ove_maintex"), NodeValue(NodeValue::kTexture, QVariant::fromValue(managed_tex)));
renderer()->BlitToTexture(pipeline, shader_job, texture_row_sums_.get());
// Draw sums into a histogram
shader_job.Insert(QStringLiteral("ove_maintex"), NodeValue(NodeValue::kTexture, QVariant::fromValue(texture_row_sums_)));
renderer()->Blit(pipeline_secondary_, shader_job, texture_row_sums_->params());
// Draw line overlays
QPainter p(paint_device());
QFont font = p.font();
font.setPixelSize(10);
QFontMetrics font_metrics = QFontMetrics(font);
QString label;
std::vector<float> histogram_increments = {
0.00,
0.25,
0.50,
1.0
};
int histogram_steps = histogram_increments.size();
QVector<QLine> histogram_lines(histogram_steps + 1);
int font_x_offset = 0;
int font_y_offset = font_metrics.capHeight() / 2.0f;
p.setCompositionMode(QPainter::CompositionMode_Plus);
p.setPen(QColor(0.0, 0.6 * 255.0, 0.0));
p.setFont(font);
float histogram_dim_x = ceil((width() - 1.0) * histogram_scale);
float histogram_dim_y = ceil((height() - 1.0) * histogram_scale);
float histogram_start_dim_x =
((width() - 1.0) - histogram_dim_x) / 2.0f;
float histogram_start_dim_y =
((height() - 1.0) - histogram_dim_y) / 2.0f;
float histogram_end_dim_x = (width() - 1.0) - histogram_start_dim_x;
// for (int i=0; i <= histogram_steps; i++) {
for(std::vector<float>::iterator it = histogram_increments.begin();
it != histogram_increments.end(); it++) {
histogram_lines[it - histogram_increments.begin()].setLine(
histogram_start_dim_x,
(histogram_dim_y * pow(1.0 - *it, histogram_base)) +
histogram_start_dim_y,
histogram_end_dim_x,
(histogram_dim_y * pow(1.0 - *it, histogram_base)) +
histogram_start_dim_y);
label = QString::number(
*it * 100, 'f', 1) + "%";
font_x_offset = QtUtils::QFontMetricsWidth(font_metrics, label) + 4;
p.drawText(
histogram_start_dim_x - font_x_offset,
(histogram_dim_y * pow(1.0 - *it, histogram_base)) +
histogram_start_dim_y + font_y_offset, label);
}
p.drawLines(histogram_lines);
}
}
| 4,991
|
C++
|
.cpp
| 116
| 37.784483
| 123
| 0.686275
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,927
|
scopebase.cpp
|
olive-editor_olive/app/widget/scope/scopebase/scopebase.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "scopebase.h"
#include "config/config.h"
namespace olive {
#define super ManagedDisplayWidget
ScopeBase::ScopeBase(QWidget* parent) :
super(parent),
texture_(nullptr),
managed_tex_up_to_date_(false)
{
EnableDefaultContextMenu();
}
void ScopeBase::SetBuffer(TexturePtr frame)
{
texture_ = frame;
managed_tex_up_to_date_ = false;
update();
}
void ScopeBase::showEvent(QShowEvent* e)
{
super::showEvent(e);
}
void ScopeBase::DrawScope(TexturePtr managed_tex, QVariant pipeline)
{
ShaderJob job;
job.Insert(QStringLiteral("ove_maintex"), NodeValue(NodeValue::kTexture, QVariant::fromValue(managed_tex)));
renderer()->Blit(pipeline, job, GetViewportParams());
}
void ScopeBase::OnInit()
{
super::OnInit();
pipeline_ = renderer()->CreateNativeShader(GenerateShaderCode());
}
void ScopeBase::OnPaint()
{
// Clear display surface
renderer()->ClearDestination();
if (texture_) {
// Convert reference frame to display space
if (!managed_tex_ || !managed_tex_up_to_date_
|| managed_tex_->params() != texture_->params()) {
managed_tex_ = renderer()->CreateTexture(texture_->params());
ColorTransformJob job;
job.SetColorProcessor(color_service());
job.SetInputTexture(texture_);
job.SetInputAlphaAssociation(kAlphaNone);
renderer()->BlitColorManaged(job, managed_tex_.get());
}
DrawScope(managed_tex_, pipeline_);
}
}
void ScopeBase::OnDestroy()
{
managed_tex_ = nullptr;
texture_ = nullptr;
pipeline_.clear();
super::OnDestroy();
}
}
| 2,265
|
C++
|
.cpp
| 72
| 28.361111
| 110
| 0.73524
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,928
|
waveform.cpp
|
olive-editor_olive/app/widget/scope/waveform/waveform.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "waveform.h"
#include <QPainter>
#include <QtMath>
#include <QDebug>
#include <QVector2D>
#include <QVector3D>
#include "common/qtutils.h"
#include "config/config.h"
#include "node/node.h"
namespace olive {
#define super ScopeBase
WaveformScope::WaveformScope(QWidget* parent) :
super(parent)
{
}
ShaderCode WaveformScope::GenerateShaderCode()
{
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/rgbwaveform.frag"),
FileFunctions::ReadFileAsString(":/shaders/rgbwaveform.vert"));
}
void WaveformScope::DrawScope(TexturePtr managed_tex, QVariant pipeline)
{
float waveform_scale = 0.80f;
// Draw waveform through shader
ShaderJob job;
// Set viewport size
job.Insert(QStringLiteral("viewport"),
NodeValue(NodeValue::kVec2, QVector2D(width(), height())));
// Set luma coefficients
double luma_coeffs[3] = {0.0f, 0.0f, 0.0f};
color_manager()->GetDefaultLumaCoefs(luma_coeffs);
job.Insert(QStringLiteral("luma_coeffs"),
NodeValue(NodeValue::kVec3, QVector3D(luma_coeffs[0], luma_coeffs[1], luma_coeffs[2])));
// Scale of the waveform relative to the viewport surface.
job.Insert(QStringLiteral("waveform_scale"),
NodeValue(NodeValue::kFloat, waveform_scale));
// Insert source texture
job.Insert(QStringLiteral("ove_maintex"),
NodeValue(NodeValue::kTexture, QVariant::fromValue(managed_tex)));
renderer()->Blit(pipeline, job, GetViewportParams());
float waveform_dim_x = ceil((width() - 1.0) * waveform_scale);
float waveform_dim_y = ceil((height() - 1.0) * waveform_scale);
float waveform_start_dim_x =
((width() - 1.0) - waveform_dim_x) / 2.0f;
float waveform_start_dim_y =
((height() - 1.0) - waveform_dim_y) / 2.0f;
float waveform_end_dim_x = (width() - 1.0) - waveform_start_dim_x;
// Draw line overlays
QPainter p(paint_device());
QFont font;
font.setPixelSize(10);
QFontMetrics font_metrics = QFontMetrics(font);
QString label;
float ire_increment = 0.1f;
int ire_steps = qRound(1.0 / ire_increment);
QVector<QLine> ire_lines(ire_steps + 1);
int font_x_offset = 0;
int font_y_offset = font_metrics.capHeight() / 2.0f;
p.setCompositionMode(QPainter::CompositionMode_Plus);
p.setPen(QColor(0.0, 0.6 * 255.0, 0.0));
p.setFont(font);
for (int i=0; i <= ire_steps; i++) {
ire_lines[i].setLine(
waveform_start_dim_x,
(waveform_dim_y * (i * ire_increment)) + waveform_start_dim_y,
waveform_end_dim_x,
(waveform_dim_y * (i * ire_increment)) + waveform_start_dim_y);
label = QString::number(1.0 - (i * ire_increment), 'f', 1);
font_x_offset = QtUtils::QFontMetricsWidth(font_metrics, label) + 4;
p.drawText(
waveform_start_dim_x - font_x_offset,
(waveform_dim_y * (i * ire_increment)) + waveform_start_dim_y + font_y_offset,
label);
}
p.drawLines(ire_lines);
}
}
| 3,678
|
C++
|
.cpp
| 91
| 35.912088
| 106
| 0.695334
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,929
|
bezierwidget.cpp
|
olive-editor_olive/app/widget/bezier/bezierwidget.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "bezierwidget.h"
#include <QGridLayout>
#include <QGroupBox>
namespace olive {
BezierWidget::BezierWidget(QWidget *parent) :
QWidget{parent}
{
QGridLayout *layout = new QGridLayout(this);
int row = 0;
layout->addWidget(new QLabel(tr("Center:")), row, 0);
x_slider_ = new FloatSlider();
connect(x_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
layout->addWidget(x_slider_, row, 1);
y_slider_ = new FloatSlider();
connect(y_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
layout->addWidget(y_slider_, row, 2);
row++;
QGroupBox *bezier_group = new QGroupBox(tr("Bezier"));
layout->addWidget(bezier_group, row, 0, 1, 3);
QGridLayout *bezier_layout = new QGridLayout(bezier_group);
row = 0;
bezier_layout->addWidget(new QLabel(tr("In:")), row, 0);
cp1_x_slider_ = new FloatSlider();
connect(cp1_x_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
bezier_layout->addWidget(cp1_x_slider_, row, 1);
cp1_y_slider_ = new FloatSlider();
connect(cp1_y_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
bezier_layout->addWidget(cp1_y_slider_, row, 2);
row++;
bezier_layout->addWidget(new QLabel(tr("Out:")), row, 0);
cp2_x_slider_ = new FloatSlider();
connect(cp2_x_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
bezier_layout->addWidget(cp2_x_slider_, row, 1);
cp2_y_slider_ = new FloatSlider();
connect(cp2_y_slider_, &FloatSlider::ValueChanged, this, &BezierWidget::ValueChanged);
bezier_layout->addWidget(cp2_y_slider_, row, 2);
}
Bezier BezierWidget::GetValue() const
{
Bezier b;
b.set_x(x_slider_->GetValue());
b.set_y(y_slider_->GetValue());
b.set_cp1_x(cp1_x_slider_->GetValue());
b.set_cp1_y(cp1_y_slider_->GetValue());
b.set_cp2_x(cp2_x_slider_->GetValue());
b.set_cp2_y(cp2_y_slider_->GetValue());
return b;
}
void BezierWidget::SetValue(const Bezier &b)
{
x_slider_->SetValue(b.x());
y_slider_->SetValue(b.y());
cp1_x_slider_->SetValue(b.cp1_x());
cp1_y_slider_->SetValue(b.cp1_y());
cp2_x_slider_->SetValue(b.cp2_x());
cp2_y_slider_->SetValue(b.cp2_y());
}
}
| 2,914
|
C++
|
.cpp
| 72
| 37.513889
| 88
| 0.718095
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,930
|
keyframeviewundo.cpp
|
olive-editor_olive/app/widget/keyframeview/keyframeviewundo.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "keyframeviewundo.h"
#include "node/node.h"
#include "node/project/sequence/sequence.h"
namespace olive {
KeyframeSetTypeCommand::KeyframeSetTypeCommand(NodeKeyframe* key, NodeKeyframe::Type type) :
key_(key),
old_type_(key->type()),
new_type_(type)
{
}
Project *KeyframeSetTypeCommand::GetRelevantProject() const
{
return key_->parent()->project();
}
void KeyframeSetTypeCommand::redo()
{
key_->set_type(new_type_);
}
void KeyframeSetTypeCommand::undo()
{
key_->set_type(old_type_);
}
KeyframeSetBezierControlPoint::KeyframeSetBezierControlPoint(NodeKeyframe* key, NodeKeyframe::BezierType mode, const QPointF& point) :
key_(key),
mode_(mode),
old_point_(key->bezier_control(mode_)),
new_point_(point)
{
}
KeyframeSetBezierControlPoint::KeyframeSetBezierControlPoint(NodeKeyframe* key, NodeKeyframe::BezierType mode, const QPointF &new_point, const QPointF &old_point) :
key_(key),
mode_(mode),
old_point_(old_point),
new_point_(new_point)
{
}
Project *KeyframeSetBezierControlPoint::GetRelevantProject() const
{
return key_->parent()->project();
}
void KeyframeSetBezierControlPoint::redo()
{
key_->set_bezier_control(mode_, new_point_);
}
void KeyframeSetBezierControlPoint::undo()
{
key_->set_bezier_control(mode_, old_point_);
}
}
| 2,003
|
C++
|
.cpp
| 63
| 29.587302
| 164
| 0.766909
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.