id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
19,948
|
LcdWidget.cpp
|
LMMS_lmms/src/gui/widgets/LcdWidget.cpp
|
/*
* LcdWidget.cpp - a widget for displaying numbers in LCD style
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008 Paul Giblock <pgllama/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QStyleOptionFrame>
#include <QPainter>
#include "LcdWidget.h"
#include "DeprecationHelper.h"
#include "embed.h"
#include "FontHelper.h"
namespace lmms::gui
{
LcdWidget::LcdWidget(QWidget* parent, const QString& name, bool leadingZero) :
LcdWidget(1, parent, name, leadingZero)
{
}
LcdWidget::LcdWidget(int numDigits, QWidget* parent, const QString& name, bool leadingZero) :
LcdWidget(numDigits, QString("19green"), parent, name, leadingZero)
{
}
LcdWidget::LcdWidget(int numDigits, const QString& style, QWidget* parent, const QString& name, bool leadingZero) :
QWidget( parent ),
m_label(),
m_textColor( 255, 255, 255 ),
m_textShadowColor( 64, 64, 64 ),
m_numDigits(numDigits),
m_seamlessLeft(false),
m_seamlessRight(false),
m_leadingZero(leadingZero)
{
initUi( name, style );
}
void LcdWidget::setValue(int value)
{
QString s = m_textForValue[value];
if (s.isEmpty())
{
s = QString::number(value);
if (m_leadingZero)
{
s = s.rightJustified(m_numDigits, '0');
}
}
if (m_display != s)
{
m_display = s;
update();
}
}
void LcdWidget::setValue(float value)
{
if (-1 < value && value < 0)
{
QString s = QString::number(static_cast<int>(value));
s.prepend('-');
if (m_display != s)
{
m_display = s;
update();
}
}
else
{
setValue(static_cast<int>(value));
}
}
QColor LcdWidget::textColor() const
{
return m_textColor;
}
void LcdWidget::setTextColor( const QColor & c )
{
m_textColor = c;
}
QColor LcdWidget::textShadowColor() const
{
return m_textShadowColor;
}
void LcdWidget::setTextShadowColor( const QColor & c )
{
m_textShadowColor = c;
}
void LcdWidget::paintEvent( QPaintEvent* )
{
QPainter p( this );
QSize cellSize( m_cellWidth, m_cellHeight );
QRect cellRect( 0, 0, m_cellWidth, m_cellHeight );
int margin = 1; // QStyle::PM_DefaultFrameWidth;
//int lcdWidth = m_cellWidth * m_numDigits + (margin*m_marginWidth)*2;
// p.translate( width() / 2 - lcdWidth / 2, 0 );
p.save();
// Don't skip any space and don't draw margin on the left side in seamless mode
if (m_seamlessLeft)
{
p.translate(0, margin);
}
else
{
p.translate(margin, margin);
// Left Margin
p.drawPixmap(cellRect, m_lcdPixmap,
QRect(QPoint(charsPerPixmap * m_cellWidth, isEnabled() ? 0 : m_cellHeight), cellSize));
p.translate(m_marginWidth, 0);
}
// Padding
for( int i=0; i < m_numDigits - m_display.length(); i++ )
{
p.drawPixmap(cellRect, m_lcdPixmap, QRect(QPoint(10 * m_cellWidth, isEnabled() ? 0 : m_cellHeight), cellSize));
p.translate( m_cellWidth, 0 );
}
// Digits
for (const auto& digit : m_display)
{
int val = digit.digitValue();
if( val < 0 )
{
if (digit == '-') val = 11;
else
val = 10;
}
p.drawPixmap(cellRect, m_lcdPixmap, QRect(QPoint(val * m_cellWidth, isEnabled() ? 0 : m_cellHeight), cellSize));
p.translate( m_cellWidth, 0 );
}
// Right Margin
p.drawPixmap(QRect(0, 0, m_seamlessRight ? 0 : m_marginWidth - 1, m_cellHeight), m_lcdPixmap,
QRect(charsPerPixmap * m_cellWidth, isEnabled() ? 0 : m_cellHeight, m_cellWidth / 2, m_cellHeight));
p.restore();
// Border
// When either the left or right edge is seamless, the border drawing must be done
// by the encapsulating class (usually LcdFloatSpinBox).
if (!m_seamlessLeft && !m_seamlessRight)
{
QStyleOptionFrame opt;
opt.initFrom(this);
opt.state = QStyle::State_Sunken;
opt.rect = QRect(0, 0, m_cellWidth * m_numDigits + (margin + m_marginWidth) * 2 - 1,
m_cellHeight + (margin * 2));
style()->drawPrimitive(QStyle::PE_Frame, &opt, &p, this);
}
p.resetTransform();
// Label
if( !m_label.isEmpty() )
{
p.setFont(adjustedToPixelSize(p.font(), DEFAULT_FONT_SIZE));
p.setPen( textShadowColor() );
p.drawText(width() / 2 -
horizontalAdvance(p.fontMetrics(), m_label) / 2 + 1,
height(), m_label);
p.setPen( textColor() );
p.drawText(width() / 2 -
horizontalAdvance(p.fontMetrics(), m_label) / 2,
height() - 1, m_label);
}
}
void LcdWidget::setLabel( const QString& label )
{
m_label = label;
updateSize();
}
void LcdWidget::setMarginWidth( int width )
{
m_marginWidth = width;
updateSize();
}
void LcdWidget::updateSize()
{
const int marginX1 = m_seamlessLeft ? 0 : 1 + m_marginWidth;
const int marginX2 = m_seamlessRight ? 0 : 1 + m_marginWidth;
const int marginY = 1;
if (m_label.isEmpty())
{
setFixedSize(
m_cellWidth * m_numDigits + marginX1 + marginX2,
m_cellHeight + (2 * marginY)
);
}
else
{
setFixedSize(
qMax<int>(
m_cellWidth * m_numDigits + marginX1 + marginX2,
horizontalAdvance(QFontMetrics(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE)), m_label)
),
m_cellHeight + (2 * marginY) + 9
);
}
update();
}
void LcdWidget::initUi(const QString& name , const QString& style)
{
setEnabled( true );
setWindowTitle( name );
// We should make a factory for these or something.
//m_lcdPixmap = embed::getIconPixmap(QString("lcd_" + style).toUtf8().constData());
//m_lcdPixmap = embed::getIconPixmap("lcd_19green"); // TODO!!
m_lcdPixmap = embed::getIconPixmap(QString("lcd_" + style).toUtf8().constData());
m_cellWidth = m_lcdPixmap.size().width() / LcdWidget::charsPerPixmap;
m_cellHeight = m_lcdPixmap.size().height() / 2;
m_marginWidth = m_cellWidth / 2;
updateSize();
}
} // namespace lmms::gui
| 6,360
|
C++
|
.cpp
| 222
| 26.135135
| 115
| 0.702787
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,949
|
TempoSyncBarModelEditor.cpp
|
LMMS_lmms/src/gui/widgets/TempoSyncBarModelEditor.cpp
|
/*
* TempoSyncBarModelEditor.cpp - adds bpm to ms conversion for the bar editor class
*
* Copyright (c) 2005-2007 Danny McRae <khjklujn/at/yahoo.com>
* Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2023 Michael Gregorius
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QMdiArea>
#include "TempoSyncBarModelEditor.h"
#include "Engine.h"
#include "CaptionMenu.h"
#include "embed.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "MeterDialog.h"
#include "Song.h"
#include "SubWindow.h"
namespace lmms::gui
{
TempoSyncBarModelEditor::TempoSyncBarModelEditor(QString text, FloatModel * floatModel, QWidget * parent) :
BarModelEditor(text, floatModel, parent),
m_tempoSyncIcon(embed::getIconPixmap("tempo_sync")),
m_tempoSyncDescription(tr("Tempo Sync")),
m_custom(nullptr)
{
modelChanged();
}
TempoSyncBarModelEditor::~TempoSyncBarModelEditor()
{
if(m_custom)
{
delete m_custom->parentWidget();
}
}
void TempoSyncBarModelEditor::modelChanged()
{
TempoSyncKnobModel * tempoSyncModel = model();
if(tempoSyncModel == nullptr)
{
qWarning("no TempoSyncKnobModel has been set!");
}
if(m_custom != nullptr)
{
m_custom->setModel(&tempoSyncModel->getCustomMeterModel());
}
connect(tempoSyncModel, &TempoSyncKnobModel::syncModeChanged, this, &TempoSyncBarModelEditor::updateDescAndIcon);
connect(this, SIGNAL(sliderMoved(float)), tempoSyncModel, SLOT(disableSync()));
updateDescAndIcon();
}
void TempoSyncBarModelEditor::contextMenuEvent(QContextMenuEvent *)
{
mouseReleaseEvent(nullptr);
TempoSyncKnobModel * tempoSyncModel = model();
CaptionMenu contextMenu(tempoSyncModel->displayName(), this);
addDefaultActions(&contextMenu);
contextMenu.addSeparator();
float limit = 60000.0f / (Engine::getSong()->getTempo() * tempoSyncModel->scale());
QMenu * syncMenu = contextMenu.addMenu(m_tempoSyncIcon, m_tempoSyncDescription);
float const maxValue = tempoSyncModel->maxValue();
if(limit / 8.0f <= maxValue)
{
connect(syncMenu, SIGNAL(triggered(QAction*)), tempoSyncModel, SLOT(setTempoSync(QAction*)));
syncMenu->addAction(embed::getIconPixmap("note_none"),
tr("No Sync"))->setData((int) TempoSyncKnobModel::SyncMode::None);
if(limit / 0.125f <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_double_whole"),
tr("Eight beats"))->setData((int) TempoSyncKnobModel::SyncMode::DoubleWholeNote);
}
if(limit / 0.25f <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_whole"),
tr("Whole note"))->setData((int) TempoSyncKnobModel::SyncMode::WholeNote);
}
if(limit / 0.5f <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_half"),
tr("Half note"))->setData((int) TempoSyncKnobModel::SyncMode::HalfNote);
}
if(limit <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_quarter"),
tr("Quarter note"))->setData((int) TempoSyncKnobModel::SyncMode::QuarterNote);
}
if(limit / 2.0f <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_eighth"),
tr("8th note"))->setData((int) TempoSyncKnobModel::SyncMode::EighthNote);
}
if(limit / 4.0f <= maxValue)
{
syncMenu->addAction(embed::getIconPixmap("note_sixteenth"),
tr("16th note"))->setData((int) TempoSyncKnobModel::SyncMode::SixteenthNote);
}
syncMenu->addAction(embed::getIconPixmap("note_thirtysecond"),
tr("32nd note"))->setData((int) TempoSyncKnobModel::SyncMode::ThirtysecondNote);
syncMenu->addAction(embed::getIconPixmap("dont_know"),
tr("Custom..."), this, SLOT(showCustom()))->setData((int) TempoSyncKnobModel::SyncMode::Custom);
contextMenu.addSeparator();
}
contextMenu.exec(QCursor::pos());
delete syncMenu;
}
void TempoSyncBarModelEditor::updateDescAndIcon()
{
updateTextDescription();
if(m_custom != nullptr && model()->syncMode() != TempoSyncKnobModel::SyncMode::Custom)
{
m_custom->parentWidget()->hide();
}
updateIcon();
emit syncDescriptionChanged(m_tempoSyncDescription);
emit syncIconChanged();
}
const QString & TempoSyncBarModelEditor::syncDescription()
{
return m_tempoSyncDescription;
}
void TempoSyncBarModelEditor::setSyncDescription(const QString & new_description)
{
m_tempoSyncDescription = new_description;
emit syncDescriptionChanged(new_description);
}
const QPixmap & TempoSyncBarModelEditor::syncIcon()
{
return m_tempoSyncIcon;
}
void TempoSyncBarModelEditor::setSyncIcon(const QPixmap & new_icon)
{
m_tempoSyncIcon = new_icon;
emit syncIconChanged();
}
void TempoSyncBarModelEditor::showCustom()
{
if(m_custom == nullptr)
{
m_custom = new MeterDialog(getGUI()->mainWindow()->workspace());
QMdiSubWindow * subWindow = getGUI()->mainWindow()->addWindowedWidget(m_custom);
Qt::WindowFlags flags = subWindow->windowFlags();
flags &= ~Qt::WindowMaximizeButtonHint;
subWindow->setWindowFlags(flags);
subWindow->setFixedSize(subWindow->size());
m_custom->setWindowTitle("Meter");
m_custom->setModel(&model()->getCustomMeterModel());
}
m_custom->parentWidget()->show();
model()->setTempoSync(TempoSyncKnobModel::SyncMode::Custom);
}
void TempoSyncBarModelEditor::updateTextDescription()
{
TempoSyncKnobModel * tempoSyncModel = model();
auto const syncMode = tempoSyncModel->syncMode();
switch(syncMode)
{
case TempoSyncKnobModel::SyncMode::None:
m_tempoSyncDescription = tr("Tempo Sync");
break;
case TempoSyncKnobModel::SyncMode::Custom:
m_tempoSyncDescription = tr("Custom ") +
"(" +
QString::number(tempoSyncModel->getCustomMeterModel().numeratorModel().value()) +
"/" +
QString::number(tempoSyncModel->getCustomMeterModel().denominatorModel().value()) +
")";
break;
case TempoSyncKnobModel::SyncMode::DoubleWholeNote:
m_tempoSyncDescription = tr("Synced to Eight Beats");
break;
case TempoSyncKnobModel::SyncMode::WholeNote:
m_tempoSyncDescription = tr("Synced to Whole Note");
break;
case TempoSyncKnobModel::SyncMode::HalfNote:
m_tempoSyncDescription = tr("Synced to Half Note");
break;
case TempoSyncKnobModel::SyncMode::QuarterNote:
m_tempoSyncDescription = tr("Synced to Quarter Note");
break;
case TempoSyncKnobModel::SyncMode::EighthNote:
m_tempoSyncDescription = tr("Synced to 8th Note");
break;
case TempoSyncKnobModel::SyncMode::SixteenthNote:
m_tempoSyncDescription = tr("Synced to 16th Note");
break;
case TempoSyncKnobModel::SyncMode::ThirtysecondNote:
m_tempoSyncDescription = tr("Synced to 32nd Note");
break;
default: ;
}
}
void TempoSyncBarModelEditor::updateIcon()
{
switch(model()->syncMode())
{
case TempoSyncKnobModel::SyncMode::None:
m_tempoSyncIcon = embed::getIconPixmap("tempo_sync");
break;
case TempoSyncKnobModel::SyncMode::Custom:
m_tempoSyncIcon = embed::getIconPixmap("dont_know");
break;
case TempoSyncKnobModel::SyncMode::DoubleWholeNote:
m_tempoSyncIcon = embed::getIconPixmap("note_double_whole");
break;
case TempoSyncKnobModel::SyncMode::WholeNote:
m_tempoSyncIcon = embed::getIconPixmap("note_whole");
break;
case TempoSyncKnobModel::SyncMode::HalfNote:
m_tempoSyncIcon = embed::getIconPixmap("note_half");
break;
case TempoSyncKnobModel::SyncMode::QuarterNote:
m_tempoSyncIcon = embed::getIconPixmap("note_quarter");
break;
case TempoSyncKnobModel::SyncMode::EighthNote:
m_tempoSyncIcon = embed::getIconPixmap("note_eighth");
break;
case TempoSyncKnobModel::SyncMode::SixteenthNote:
m_tempoSyncIcon = embed::getIconPixmap("note_sixteenth");
break;
case TempoSyncKnobModel::SyncMode::ThirtysecondNote:
m_tempoSyncIcon = embed::getIconPixmap("note_thirtysecond");
break;
default:
qWarning("TempoSyncKnob::calculateTempoSyncTime:"
"invalid TempoSyncMode");
break;
}
}
} // namespace lmms::gui
| 8,565
|
C++
|
.cpp
| 245
| 32.167347
| 114
| 0.756505
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,950
|
BarModelEditor.cpp
|
LMMS_lmms/src/gui/widgets/BarModelEditor.cpp
|
#include <BarModelEditor.h>
#include <QPainter>
#include <QStyle>
namespace lmms::gui
{
BarModelEditor::BarModelEditor(QString text, FloatModel * floatModel, QWidget * parent) :
FloatModelEditorBase(DirectionOfManipulation::Horizontal, parent),
m_text(text),
m_backgroundBrush(palette().base()),
m_barBrush(palette().button()),
m_textColor(palette().text().color())
{
setModel(floatModel);
}
QSizePolicy BarModelEditor::sizePolicy() const
{
return QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
}
QSize BarModelEditor::minimumSizeHint() const
{
auto const fm = fontMetrics();
return QSize(50, fm.height() + 6);
}
QSize BarModelEditor::sizeHint() const
{
return minimumSizeHint();
}
QBrush const & BarModelEditor::getBackgroundBrush() const
{
return m_backgroundBrush;
}
void BarModelEditor::setBackgroundBrush(QBrush const & backgroundBrush)
{
m_backgroundBrush = backgroundBrush;
}
QBrush const & BarModelEditor::getBarBrush() const
{
return m_barBrush;
}
void BarModelEditor::setBarBrush(QBrush const & barBrush)
{
m_barBrush = barBrush;
}
QColor const & BarModelEditor::getTextColor() const
{
return m_textColor;
}
void BarModelEditor::setTextColor(QColor const & textColor)
{
m_textColor = textColor;
}
void BarModelEditor::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
auto const * mod = model();
auto const minValue = mod->minValue();
auto const maxValue = mod->maxValue();
auto const range = maxValue - minValue;
QRect const r = rect();
QPainter painter(this);
// Paint the base rectangle into which the bar and the text go
QBrush const & backgroundBrush = getBackgroundBrush();
painter.setPen(backgroundBrush.color());
painter.setBrush(backgroundBrush);
painter.drawRect(r);
// Paint the bar
// Compute the percentage as:
// min + x * (max - min) = v <=> x = (v - min) / (max - min)
auto const percentage = range == 0 ? 1. : (model()->inverseScaledValue(model()->value()) - minValue) / range;
int const margin = 3;
QMargins const margins(margin, margin, margin, margin);
QRect const valueRect = r.marginsRemoved(margins);
QBrush const & barBrush = getBarBrush();
painter.setPen(barBrush.color());
painter.setBrush(barBrush);
QPoint const startPoint = valueRect.topLeft();
QPoint endPoint = valueRect.bottomRight();
endPoint.setX(startPoint.x() + percentage * (endPoint.x() - startPoint.x()));
painter.drawRect(QRect(startPoint, endPoint));
// Draw the text into the value rectangle but move it slightly to the right
QRect const textRect = valueRect.marginsRemoved(QMargins(3, 0, 0, 0));
// Elide the text if needed
auto const fm = fontMetrics();
QString const elidedText = fm.elidedText(m_text, Qt::ElideRight, textRect.width());
// Now draw the text
painter.setPen(getTextColor());
painter.drawText(textRect, elidedText);
}
} // namespace lmms::gui
| 2,861
|
C++
|
.cpp
| 89
| 30.269663
| 110
| 0.760569
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,951
|
ComboBox.cpp
|
LMMS_lmms/src/gui/widgets/ComboBox.cpp
|
/*
* ComboBox.cpp - implementation of LMMS combobox
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008-2009 Paul Giblock <pgib/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ComboBox.h"
#include <QMouseEvent>
#include <QPainter>
#include <QStyleOptionFrame>
#include <QScreen>
#include "CaptionMenu.h"
#include "FontHelper.h"
#define QT_SUPPORTS_WIDGET_SCREEN (QT_VERSION >= QT_VERSION_CHECK(5,14,0))
#if !QT_SUPPORTS_WIDGET_SCREEN
#include <QApplication>
#include <QDesktopWidget>
#endif
namespace lmms::gui
{
const int CB_ARROW_BTN_WIDTH = 18;
ComboBox::ComboBox( QWidget * _parent, const QString & _name ) :
QWidget( _parent ),
IntModelView( new ComboBoxModel( nullptr, QString(), true ), this ),
m_menu( this ),
m_pressed( false )
{
setFixedHeight( ComboBox::DEFAULT_HEIGHT );
setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE));
connect( &m_menu, SIGNAL(triggered(QAction*)),
this, SLOT(setItem(QAction*)));
setWindowTitle( _name );
doConnections();
}
void ComboBox::selectNext()
{
model()->setInitValue( model()->value() + 1 );
}
void ComboBox::selectPrevious()
{
model()->setInitValue( model()->value() - 1 );
}
void ComboBox::contextMenuEvent( QContextMenuEvent * event )
{
if( model() == nullptr || event->x() <= width() - CB_ARROW_BTN_WIDTH )
{
QWidget::contextMenuEvent( event );
return;
}
CaptionMenu contextMenu( model()->displayName() );
addDefaultActions( &contextMenu );
contextMenu.exec( QCursor::pos() );
}
void ComboBox::mousePressEvent( QMouseEvent* event )
{
if( model() == nullptr )
{
return;
}
if( event->button() == Qt::LeftButton && ! ( event->modifiers() & Qt::ControlModifier ) )
{
if( event->x() > width() - CB_ARROW_BTN_WIDTH )
{
m_pressed = true;
update();
m_menu.clear();
for( int i = 0; i < model()->size(); ++i )
{
QAction * a = m_menu.addAction( model()->itemPixmap( i ) ? model()->itemPixmap( i )->pixmap() : QPixmap(),
model()->itemText( i ) );
a->setData( i );
}
QPoint gpos = mapToGlobal(QPoint(0, height()));
#if (QT_SUPPORTS_WIDGET_SCREEN)
bool const menuCanBeFullyShown = screen()->geometry().contains(QRect(gpos, m_menu.sizeHint()));
#else
bool const menuCanBeFullyShown = gpos.y() + m_menu.sizeHint().height() < qApp->desktop()->height();
#endif
if (menuCanBeFullyShown)
{
m_menu.exec(gpos);
}
else
{
m_menu.exec(mapToGlobal(QPoint(width(), 0)));
}
m_pressed = false;
update();
}
else if( event->button() == Qt::LeftButton )
{
selectNext();
update();
}
}
else if( event->button() == Qt::RightButton )
{
selectPrevious();
update();
}
else
{
IntModelView::mousePressEvent( event );
}
}
void ComboBox::paintEvent( QPaintEvent * _pe )
{
QPainter p( this );
p.fillRect(2, 2, width() - 2, height() - 4, m_background);
QColor shadow = palette().shadow().color();
QColor highlight = palette().highlight().color();
shadow.setAlpha( 124 );
highlight.setAlpha( 124 );
// button-separator
p.setPen( shadow );
p.drawLine( width() - CB_ARROW_BTN_WIDTH - 1, 1, width() - CB_ARROW_BTN_WIDTH - 1, height() - 3 );
p.setPen( highlight );
p.drawLine( width() - CB_ARROW_BTN_WIDTH, 1, width() - CB_ARROW_BTN_WIDTH, height() - 3 );
// Border
QStyleOptionFrame opt;
opt.initFrom( this );
opt.state = QStyle::StateFlag::State_None;
style()->drawPrimitive( QStyle::PE_Frame, &opt, &p, this );
auto arrow = m_pressed ? m_arrowSelected : m_arrow;
p.drawPixmap(width() - CB_ARROW_BTN_WIDTH + 3, 4, arrow);
if( model() && model()->size() > 0 )
{
p.setFont( font() );
p.setClipRect( QRect( 4, 2, width() - CB_ARROW_BTN_WIDTH - 8, height() - 2 ) );
QPixmap pm = model()->currentData() ? model()->currentData()->pixmap() : QPixmap();
int tx = 5;
if( !pm.isNull() )
{
if( pm.height() > 16 )
{
pm = pm.scaledToHeight( 16, Qt::SmoothTransformation );
}
p.drawPixmap( tx, 3, pm );
tx += pm.width() + 3;
}
const int y = ( height()+p.fontMetrics().height() ) /2;
p.setPen( QColor( 64, 64, 64 ) );
p.drawText( tx+1, y-3, model()->currentText() );
p.setPen( QColor( 224, 224, 224 ) );
p.drawText( tx, y-4, model()->currentText() );
}
}
void ComboBox::wheelEvent( QWheelEvent* event )
{
if( model() )
{
const int direction = (event->angleDelta().y() < 0 ? 1 : -1) * (event->inverted() ? -1 : 1);
model()->setInitValue(model()->value() + direction);
update();
event->accept();
}
}
void ComboBox::setItem( QAction* item )
{
if( model() )
{
model()->setInitValue( item->data().toInt() );
}
}
} // namespace lmms::gui
| 5,450
|
C++
|
.cpp
| 183
| 27.054645
| 110
| 0.668267
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,952
|
Fader.cpp
|
LMMS_lmms/src/gui/widgets/Fader.cpp
|
/*
* Fader.cpp - fader-widget used in mixer - partly taken from Hydrogen
*
* Copyright (c) 2008-2012 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
/*
* Hydrogen
* Copyright(c) 2002-2008 by Alex >Comix< Cominu [comix@users.sourceforge.net]
*
* http://www.hydrogen-music.org
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "Fader.h"
#include <QInputDialog>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include "lmms_math.h"
#include "embed.h"
#include "CaptionMenu.h"
#include "ConfigManager.h"
#include "SimpleTextFloat.h"
namespace lmms::gui
{
SimpleTextFloat* Fader::s_textFloat = nullptr;
Fader::Fader(FloatModel* model, const QString& name, QWidget* parent) :
QWidget(parent),
FloatModelView(model, this)
{
if (s_textFloat == nullptr)
{
s_textFloat = new SimpleTextFloat;
}
setWindowTitle(name);
setAttribute(Qt::WA_OpaquePaintEvent, false);
// For now resize the widget to the size of the previous background image "fader_background.png" as it was found in the classic and default theme
constexpr QSize minimumSize(23, 116);
setMinimumSize(minimumSize);
resize(minimumSize);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
setModel(model);
setHintText("Volume:", "%");
m_conversionFactor = 100.0;
}
Fader::Fader(FloatModel* model, const QString& name, QWidget* parent, const QPixmap& knob) :
Fader(model, name, parent)
{
m_knob = knob;
}
void Fader::contextMenuEvent(QContextMenuEvent* ev)
{
CaptionMenu contextMenu(windowTitle());
addDefaultActions(&contextMenu);
contextMenu.exec(QCursor::pos());
ev->accept();
}
void Fader::mouseMoveEvent(QMouseEvent* mouseEvent)
{
if (m_moveStartPoint >= 0)
{
int dy = m_moveStartPoint - mouseEvent->globalY();
float delta = dy * (model()->maxValue() - model()->minValue()) / (float)(height() - (m_knob).height());
const auto step = model()->step<float>();
float newValue = static_cast<float>(static_cast<int>((m_startValue + delta) / step + 0.5)) * step;
model()->setValue(newValue);
updateTextFloat();
}
}
void Fader::mousePressEvent(QMouseEvent* mouseEvent)
{
if (mouseEvent->button() == Qt::LeftButton &&
!(mouseEvent->modifiers() & Qt::ControlModifier))
{
AutomatableModel* thisModel = model();
if (thisModel)
{
thisModel->addJournalCheckPoint();
thisModel->saveJournallingState(false);
}
if (mouseEvent->y() >= knobPosY() - (m_knob).height() && mouseEvent->y() < knobPosY())
{
updateTextFloat();
s_textFloat->show();
m_moveStartPoint = mouseEvent->globalY();
m_startValue = model()->value();
mouseEvent->accept();
}
else
{
m_moveStartPoint = -1;
}
}
else
{
AutomatableModelView::mousePressEvent(mouseEvent);
}
}
void Fader::mouseDoubleClickEvent(QMouseEvent* mouseEvent)
{
bool ok;
// TODO: dbFS handling
auto minv = model()->minValue() * m_conversionFactor;
auto maxv = model()->maxValue() * m_conversionFactor;
float enteredValue = QInputDialog::getDouble(this, tr("Set value"),
tr("Please enter a new value between %1 and %2:").arg(minv).arg(maxv),
model()->getRoundedValue() * m_conversionFactor, minv, maxv, model()->getDigitCount(), &ok);
if (ok)
{
model()->setValue(enteredValue / m_conversionFactor);
}
}
void Fader::mouseReleaseEvent(QMouseEvent* mouseEvent)
{
if (mouseEvent && mouseEvent->button() == Qt::LeftButton)
{
AutomatableModel* thisModel = model();
if (thisModel)
{
thisModel->restoreJournallingState();
}
}
s_textFloat->hide();
}
void Fader::wheelEvent (QWheelEvent* ev)
{
ev->accept();
const int direction = (ev->angleDelta().y() > 0 ? 1 : -1) * (ev->inverted() ? -1 : 1);
model()->incValue(direction);
updateTextFloat();
s_textFloat->setVisibilityTimeOut(1000);
}
///
/// Set peak value (0.0 .. 1.0)
///
void Fader::setPeak(float fPeak, float& targetPeak, float& persistentPeak, QElapsedTimer& lastPeakTimer)
{
if (targetPeak != fPeak)
{
targetPeak = fPeak;
if (targetPeak >= persistentPeak)
{
persistentPeak = targetPeak;
lastPeakTimer.restart();
emit peakChanged(persistentPeak);
}
update();
}
if (persistentPeak > 0 && lastPeakTimer.elapsed() > 1500)
{
persistentPeak = qMax<float>(0, persistentPeak-0.05);
emit peakChanged(persistentPeak);
update();
}
}
void Fader::setPeak_L(float fPeak)
{
setPeak(fPeak, m_fPeakValue_L, m_persistentPeak_L, m_lastPeakTimer_L);
}
void Fader::setPeak_R(float fPeak)
{
setPeak(fPeak, m_fPeakValue_R, m_persistentPeak_R, m_lastPeakTimer_R);
}
// update tooltip showing value and adjust position while changing fader value
void Fader::updateTextFloat()
{
if (ConfigManager::inst()->value("app", "displaydbfs").toInt() && m_conversionFactor == 100.0)
{
QString label(tr("Volume: %1 dBFS"));
auto const modelValue = model()->value();
if (modelValue <= 0.)
{
s_textFloat->setText(label.arg("-∞"));
}
else
{
s_textFloat->setText(label.arg(ampToDbfs(modelValue), 3, 'f', 2));
}
}
else
{
s_textFloat->setText(m_description + " " + QString("%1 ").arg(model()->value() * m_conversionFactor) + " " + m_unit);
}
s_textFloat->moveGlobal(this, QPoint(width() + 2, knobPosY() - s_textFloat->height() / 2));
}
void Fader::paintEvent(QPaintEvent* ev)
{
QPainter painter(this);
// Draw the levels with peaks
paintLevels(ev, painter, !m_levelsDisplayedInDBFS);
// Draw the knob
painter.drawPixmap((width() - m_knob.width()) / 2, knobPosY() - m_knob.height(), m_knob);
}
void Fader::paintLevels(QPaintEvent* ev, QPainter& painter, bool linear)
{
const auto mapper = linear
? +[](float value) -> float { return value; }
: +[](float value) -> float { return ampToDbfs(qMax(0.0001f, value)); };
const float mappedMinPeak = mapper(m_fMinPeak);
const float mappedMaxPeak = mapper(m_fMaxPeak);
const float mappedPeakL = mapper(m_fPeakValue_L);
const float mappedPeakR = mapper(m_fPeakValue_R);
const float mappedPersistentPeakL = mapper(m_persistentPeak_L);
const float mappedPersistentPeakR = mapper(m_persistentPeak_R);
const float mappedUnity = mapper(1.f);
painter.save();
const QRect baseRect = rect();
const int height = baseRect.height();
const int margin = 1;
const int distanceBetweenMeters = 2;
const int numberOfMeters = 2;
// Compute the width of a single meter by removing the margins and the space between meters
const int leftAndRightMargin = 2 * margin;
const int pixelsBetweenAllMeters = distanceBetweenMeters * (numberOfMeters - 1);
const int remainingPixelsForMeters = baseRect.width() - leftAndRightMargin - pixelsBetweenAllMeters;
const int meterWidth = remainingPixelsForMeters / numberOfMeters;
QRect leftMeterOutlineRect(margin, margin, meterWidth, height - 2 * margin);
QRect rightMeterOutlineRect(baseRect.width() - margin - meterWidth, margin, meterWidth, height - 2 * margin);
QMargins removedMargins(1, 1, 1, 1);
QRect leftMeterRect = leftMeterOutlineRect.marginsRemoved(removedMargins);
QRect rightMeterRect = rightMeterOutlineRect.marginsRemoved(removedMargins);
QPainterPath path;
qreal radius = 2;
path.addRoundedRect(leftMeterOutlineRect, radius, radius);
path.addRoundedRect(rightMeterOutlineRect, radius, radius);
painter.fillPath(path, Qt::black);
// Now clip everything to the paths of the meters
painter.setClipPath(path);
// This linear map performs the following mapping:
// Value (dbFS or linear) -> window coordinates of the widget
// It is for example used to determine the height of peaks, markers and to define the gradient for the levels
const LinearMap<float> valuesToWindowCoordinates(mappedMaxPeak, leftMeterRect.y(), mappedMinPeak, leftMeterRect.y() + leftMeterRect.height());
// This lambda takes a value (in dbFS or linear) and a rectangle and computes a rectangle
// that represent the value within the rectangle. It is for example used to compute the unity indicators.
const auto computeLevelMarkerRect = [&valuesToWindowCoordinates](const QRect& rect, float peak) -> QRect
{
return QRect(rect.x(), valuesToWindowCoordinates.map(peak), rect.width(), 1);
};
// This lambda takes a peak value (in dbFS or linear) and a rectangle and computes a rectangle
// that represent the peak value within the rectangle. It's used to compute the peak indicators
// which "dance" on top of the level meters.
const auto computePeakRect = [&valuesToWindowCoordinates](const QRect& rect, float peak) -> QRect
{
return QRect(rect.x(), valuesToWindowCoordinates.map(peak), rect.width(), 1);
};
// This lambda takes a peak value (in dbFS or linear) and a rectangle and returns an adjusted copy of the
// rectangle that represents the peak value. It is used to compute the level meters themselves.
const auto computeLevelRect = [&valuesToWindowCoordinates](const QRect& rect, float peak) -> QRect
{
QRect result(rect);
result.setTop(valuesToWindowCoordinates.map(peak));
return result;
};
// Draw left and right level markers for the unity lines (0 dbFS, 1.0 amplitude)
if (getRenderUnityLine())
{
const auto unityRectL = computeLevelMarkerRect(leftMeterRect, mappedUnity);
painter.fillRect(unityRectL, m_unityMarker);
const auto unityRectR = computeLevelMarkerRect(rightMeterRect, mappedUnity);
painter.fillRect(unityRectR, m_unityMarker);
}
// These values define where the gradient changes values, i.e. the ranges
// for clipping, warning and ok.
// Please ensure that "clip starts" is the maximum value and that "ok ends"
// is the minimum value and that all other values lie inbetween. Otherwise
// there will be warnings when the gradient is defined.
const float mappedClipStarts = mapper(dbfsToAmp(0.f));
const float mappedWarnEnd = mapper(dbfsToAmp(-0.01f));
const float mappedWarnStart = mapper(dbfsToAmp(-6.f));
const float mappedOkEnd = mapper(dbfsToAmp(-12.f));
// Prepare the gradient for the meters
//
// The idea is the following. We want to be able to render arbitrary ranges of min and max values.
// Therefore we first compute the start and end point of the gradient in window coordinates.
// The gradient is assumed to start with the clip color and to end with the ok color with warning values in between.
// We know the min and max peaks that map to a rectangle where we draw the levels. We can use the values of the min and max peaks
// as well as the Y-coordinates of the rectangle to compute a map which will give us the coordinates of the value where the clipping
// starts and where the ok area end. These coordinates are used to initialize the gradient. Please note that the gradient might thus
// extend the rectangle into which we paint.
float clipStartYCoord = valuesToWindowCoordinates.map(mappedClipStarts);
float okEndYCoord = valuesToWindowCoordinates.map(mappedOkEnd);
QLinearGradient linearGrad(0, clipStartYCoord, 0, okEndYCoord);
// We already know for the gradient that the clip color will be at 0 and that the ok color is at 1.
// What's left to do is to map the inbetween values into the interval [0,1].
const LinearMap<float> mapBetweenClipAndOk(mappedClipStarts, 0.f, mappedOkEnd, 1.f);
linearGrad.setColorAt(0, m_peakClip);
linearGrad.setColorAt(mapBetweenClipAndOk.map(mappedWarnEnd), m_peakWarn);
linearGrad.setColorAt(mapBetweenClipAndOk.map(mappedWarnStart), m_peakWarn);
linearGrad.setColorAt(1, m_peakOk);
// Draw left levels
if (mappedPeakL > mappedMinPeak)
{
QPainterPath leftMeterPath;
leftMeterPath.addRoundedRect(computeLevelRect(leftMeterRect, mappedPeakL), radius, radius);
painter.fillPath(leftMeterPath, linearGrad);
}
// Draw left peaks
if (mappedPersistentPeakL > mappedMinPeak)
{
const auto peakRectL = computePeakRect(leftMeterRect, mappedPersistentPeakL);
painter.fillRect(peakRectL, linearGrad);
}
// Draw right levels
if (mappedPeakR > mappedMinPeak)
{
QPainterPath rightMeterPath;
rightMeterPath.addRoundedRect(computeLevelRect(rightMeterRect, mappedPeakR), radius, radius);
painter.fillPath(rightMeterPath, linearGrad);
}
// Draw right peaks
if (mappedPersistentPeakR > mappedMinPeak)
{
const auto peakRectR = computePeakRect(rightMeterRect, mappedPersistentPeakR);
painter.fillRect(peakRectR, linearGrad);
}
painter.restore();
}
} // namespace lmms::gui
| 13,714
|
C++
|
.cpp
| 349
| 36.928367
| 146
| 0.753427
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,953
|
MeterDialog.cpp
|
LMMS_lmms/src/gui/widgets/MeterDialog.cpp
|
/*
* MeterDialog.cpp - dialog for entering meter settings
*
* Copyright (c) 2008-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include "MeterDialog.h"
#include "MeterModel.h"
#include "LcdSpinBox.h"
namespace lmms::gui
{
MeterDialog::MeterDialog( QWidget * _parent, bool _simple ) :
QWidget( _parent ),
ModelView( nullptr, this )
{
auto vlayout = new QVBoxLayout(this);
vlayout->setSpacing( 0 );
vlayout->setContentsMargins(0, 0, 0, 0);
auto num = new QWidget(this);
auto num_layout = new QHBoxLayout(num);
num_layout->setSpacing( 0 );
num_layout->setContentsMargins(0, 0, 0, 0);
m_numerator = new LcdSpinBox( 2, num, tr( "Meter Numerator" ) );
m_numerator->setToolTip(tr("Meter numerator"));
num_layout->addWidget( m_numerator );
if( !_simple )
{
auto num_label = new QLabel(tr("Meter Numerator"), num);
QFont f = num_label->font();
num_layout->addSpacing( 5 );
num_layout->addWidget( num_label );
}
num_layout->addStretch();
auto den = new QWidget(this);
auto den_layout = new QHBoxLayout(den);
den_layout->setSpacing( 0 );
den_layout->setContentsMargins(0, 0, 0, 0);
m_denominator = new LcdSpinBox( 2, den, tr( "Meter Denominator" ) );
m_denominator->setToolTip(tr("Meter denominator"));
if( _simple )
{
m_denominator->setLabel( tr( "TIME SIG" ) );
}
den_layout->addWidget( m_denominator );
if( !_simple )
{
auto den_label = new QLabel(tr("Meter Denominator"), den);
QFont f = den_label->font();
den_layout->addSpacing( 5 );
den_layout->addWidget( den_label );
}
den_layout->addStretch();
vlayout->addSpacing( _simple ? 1 : 3 );
vlayout->addWidget( num );
vlayout->addSpacing( 2 );
vlayout->addWidget( den );
vlayout->addStretch();
}
void MeterDialog::modelChanged()
{
auto mm = castModel<MeterModel>();
m_numerator->setModel( &mm->numeratorModel() );
m_denominator->setModel( &mm->denominatorModel() );
}
} // namespace lmms::gui
| 2,851
|
C++
|
.cpp
| 86
| 30.930233
| 77
| 0.721066
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,954
|
PeakIndicator.cpp
|
LMMS_lmms/src/gui/widgets/PeakIndicator.cpp
|
/*
* PeakIndicator.cpp - Peak indicator widget
*
* Copyright (c) 2024- Michael Gregorius
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PeakIndicator.h"
#include "lmms_math.h"
#include <QBoxLayout>
#include <QMouseEvent>
namespace lmms::gui
{
PeakIndicator::PeakIndicator(QWidget* parent) :
QLabel(parent),
m_peak(0.f)
{
setAlignment(Qt::AlignCenter);
updatePeakDisplay();
}
void PeakIndicator::resetPeakToMinusInf()
{
m_peak = 0;
updatePeakDisplay();
}
void PeakIndicator::updatePeak(float peak)
{
if (peak > m_peak)
{
m_peak = peak;
updatePeakDisplay();
}
}
void PeakIndicator::mousePressEvent(QMouseEvent* e)
{
if (e->buttons() & Qt::LeftButton)
{
resetPeakToMinusInf();
}
}
void PeakIndicator::updatePeakDisplay()
{
// Treat everything below -144 dbFS as -inf. Otherwise some residual signals show up
// in the form of very small dbFS values, e.g. -857.1 dbFS.
// TODO Make the threshold configurable in the settings?
if (m_peak <= dbfsToAmp(-144.))
{
setText(tr("-inf"));
}
else
{
auto dbfs = ampToDbfs(m_peak);
setText(QString::number(dbfs, 'f', 1));
}
}
} // namespace lmms::gui
| 1,891
|
C++
|
.cpp
| 72
| 24.333333
| 85
| 0.740454
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,955
|
SimpleTextFloat.cpp
|
LMMS_lmms/src/gui/widgets/SimpleTextFloat.cpp
|
/*
* TextFloat.cpp - class textFloat, a floating text-label
*
* Copyright (c) LMMS team
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SimpleTextFloat.h"
#include <QTimer>
#include <QStyleOption>
#include <QHBoxLayout>
#include <QLabel>
#include "GuiApplication.h"
#include "MainWindow.h"
namespace lmms::gui
{
SimpleTextFloat::SimpleTextFloat() :
QWidget(getGUI()->mainWindow(), Qt::ToolTip)
{
QHBoxLayout * layout = new QHBoxLayout(this);
layout->setMargin(3);
setLayout(layout);
m_textLabel = new QLabel(this);
layout->addWidget(m_textLabel);
m_showTimer = new QTimer(this);
m_showTimer->setSingleShot(true);
QObject::connect(m_showTimer, &QTimer::timeout, this, &SimpleTextFloat::show);
m_hideTimer = new QTimer(this);
m_hideTimer->setSingleShot(true);
QObject::connect(m_hideTimer, &QTimer::timeout, this, &SimpleTextFloat::hide);
}
void SimpleTextFloat::setText(const QString & text)
{
m_textLabel->setText(text);
}
void SimpleTextFloat::showWithDelay(int msecBeforeDisplay, int msecDisplayTime)
{
if (msecBeforeDisplay != 0)
{
m_showTimer->start(msecBeforeDisplay);
}
else
{
show();
}
if (msecDisplayTime != 0)
{
m_hideTimer->start(msecBeforeDisplay + msecDisplayTime);
}
}
void SimpleTextFloat::hide()
{
m_showTimer->stop();
m_hideTimer->stop();
QWidget::hide();
}
void SimpleTextFloat::setVisibilityTimeOut(int msecs)
{
QTimer::singleShot(msecs, this, SLOT(hide()));
show();
}
} // namespace lmms::gui
| 2,219
|
C++
|
.cpp
| 78
| 26.551282
| 79
| 0.754468
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,956
|
LedCheckBox.cpp
|
LMMS_lmms/src/gui/widgets/LedCheckBox.cpp
|
/*
* LedCheckBox.cpp - class LedCheckBox, an improved QCheckBox
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LedCheckBox.h"
#include <QFontMetrics>
#include <QPainter>
#include <array>
#include "DeprecationHelper.h"
#include "embed.h"
#include "FontHelper.h"
namespace lmms::gui
{
static const auto names = std::array<QString, 3>
{
"led_yellow", "led_green", "led_red"
} ;
LedCheckBox::LedCheckBox( const QString & _text, QWidget * _parent,
const QString & _name, LedColor _color, bool legacyMode ) :
AutomatableButton( _parent, _name ),
m_text( _text ),
m_legacyMode(legacyMode)
{
initUi( _color );
}
LedCheckBox::LedCheckBox( QWidget * _parent,
const QString & _name, LedColor _color, bool legacyMode ) :
LedCheckBox( QString(), _parent, _name, _color, legacyMode )
{
}
void LedCheckBox::setText( const QString &s )
{
m_text = s;
onTextUpdated();
}
void LedCheckBox::paintEvent( QPaintEvent * pe )
{
if (!m_legacyMode)
{
paintNonLegacy(pe);
}
else
{
paintLegacy(pe);
}
}
void LedCheckBox::initUi( LedColor _color )
{
setCheckable( true );
m_ledOnPixmap = embed::getIconPixmap(names[static_cast<std::size_t>(_color)].toUtf8().constData());
m_ledOffPixmap = embed::getIconPixmap("led_off");
if (m_legacyMode){ setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE)); }
setText( m_text );
}
void LedCheckBox::onTextUpdated()
{
QFontMetrics const fm = fontMetrics();
int const width = m_ledOffPixmap.width() + 5 + horizontalAdvance(fm, text());
int const height = m_legacyMode ? m_ledOffPixmap.height() : qMax(m_ledOffPixmap.height(), fm.height());
setFixedSize(width, height);
}
void LedCheckBox::paintLegacy(QPaintEvent * pe)
{
QPainter p( this );
p.setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE));
p.drawPixmap(0, 0, model()->value() ? m_ledOnPixmap : m_ledOffPixmap);
p.setPen( QColor( 64, 64, 64 ) );
p.drawText(m_ledOffPixmap.width() + 4, 11, text());
p.setPen( QColor( 255, 255, 255 ) );
p.drawText(m_ledOffPixmap.width() + 3, 10, text());
}
void LedCheckBox::paintNonLegacy(QPaintEvent * pe)
{
QPainter p(this);
auto drawnPixmap = model()->value() ? m_ledOnPixmap : m_ledOffPixmap;
p.drawPixmap(0, rect().height() / 2 - drawnPixmap.height() / 2, drawnPixmap);
QRect r = rect();
r -= QMargins(m_ledOffPixmap.width() + 5, 0, 0, 0);
p.drawText(r, text());
}
} // namespace lmms::gui
| 3,224
|
C++
|
.cpp
| 100
| 30.13
| 104
| 0.724619
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,957
|
AutomatableButton.cpp
|
LMMS_lmms/src/gui/widgets/AutomatableButton.cpp
|
/*
* AutomatableButton.cpp - implementation of class automatableButton and
* automatableButtonGroup
*
* Copyright (c) 2006-2011 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AutomatableButton.h"
#include <QMouseEvent>
#include "CaptionMenu.h"
#include "StringPairDrag.h"
namespace lmms::gui
{
AutomatableButton::AutomatableButton( QWidget * _parent,
const QString & _name ) :
QPushButton( _parent ),
BoolModelView( new BoolModel( false, nullptr, _name, true ), this ),
m_group( nullptr )
{
setWindowTitle( _name );
doConnections();
setFocusPolicy( Qt::NoFocus );
}
AutomatableButton::~AutomatableButton()
{
if( m_group != nullptr )
{
m_group->removeButton( this );
}
}
void AutomatableButton::modelChanged()
{
if( QPushButton::isChecked() != model()->value() )
{
QPushButton::setChecked( model()->value() );
}
}
void AutomatableButton::update()
{
if( QPushButton::isChecked() != model()->value() )
{
QPushButton::setChecked( model()->value() );
}
QPushButton::update();
}
void AutomatableButton::contextMenuEvent( QContextMenuEvent * _me )
{
// for the case, the user clicked right while pressing left mouse-
// button, the context-menu appears while mouse-cursor is still hidden
// and it isn't shown again until user does something which causes
// an QApplication::restoreOverrideCursor()-call...
mouseReleaseEvent( nullptr );
if ( m_group != nullptr )
{
CaptionMenu contextMenu( m_group->model()->displayName() );
m_group->addDefaultActions( &contextMenu );
contextMenu.exec( QCursor::pos() );
}
else
{
CaptionMenu contextMenu( model()->displayName() );
addDefaultActions( &contextMenu );
contextMenu.exec( QCursor::pos() );
}
}
void AutomatableButton::mousePressEvent( QMouseEvent * _me )
{
if( _me->button() == Qt::LeftButton &&
! ( _me->modifiers() & Qt::ControlModifier ) )
{
// User simply clicked, toggle if needed
if( isCheckable() )
{
toggle();
}
_me->accept();
}
else
{
// Ctrl-clicked, need to prepare drag-drop
if( m_group )
{
// A group, we must get process it instead
auto groupView = (AutomatableModelView*)m_group;
new StringPairDrag( "automatable_model",
QString::number( groupView->modelUntyped()->id() ),
QPixmap(), widget() );
// TODO: ^^ Maybe use a predefined icon instead of the button they happened to select
_me->accept();
}
else
{
// Otherwise, drag the standalone button
AutomatableModelView::mousePressEvent( _me );
QPushButton::mousePressEvent( _me );
}
}
}
void AutomatableButton::mouseReleaseEvent( QMouseEvent * _me )
{
if( _me && _me->button() == Qt::LeftButton )
{
emit clicked();
}
}
void AutomatableButton::toggle()
{
if( isCheckable() && m_group != nullptr )
{
if( model()->value() == false )
{
m_group->activateButton( this );
}
}
else
{
model()->setValue( !model()->value() );
}
}
automatableButtonGroup::automatableButtonGroup( QWidget * _parent,
const QString & _name ) :
QWidget( _parent ),
IntModelView( new IntModel( 0, 0, 0, nullptr, _name, true ), this )
{
hide();
setWindowTitle( _name );
}
automatableButtonGroup::~automatableButtonGroup()
{
for (const auto& button : m_buttons)
{
button->m_group = nullptr;
}
}
void automatableButtonGroup::addButton( AutomatableButton * _btn )
{
_btn->m_group = this;
_btn->setCheckable( true );
_btn->model()->setValue( false );
// disable journalling as we're recording changes of states of
// button-group members on our own
_btn->model()->setJournalling( false );
m_buttons.push_back( _btn );
model()->setRange( 0, m_buttons.size() - 1 );
updateButtons();
}
void automatableButtonGroup::removeButton( AutomatableButton * _btn )
{
m_buttons.erase( std::find( m_buttons.begin(), m_buttons.end(), _btn ) );
_btn->m_group = nullptr;
}
void automatableButtonGroup::activateButton( AutomatableButton * _btn )
{
if( _btn != m_buttons[model()->value()] &&
m_buttons.indexOf( _btn ) != -1 )
{
model()->setValue( m_buttons.indexOf( _btn ) );
for( AutomatableButton * btn : m_buttons )
{
btn->update();
}
}
}
void automatableButtonGroup::modelChanged()
{
connect( model(), SIGNAL(dataChanged()),
this, SLOT(updateButtons()));
IntModelView::modelChanged();
updateButtons();
}
void automatableButtonGroup::updateButtons()
{
model()->setRange( 0, m_buttons.size() - 1 );
int i = 0;
for( AutomatableButton * btn : m_buttons )
{
btn->model()->setValue( i == model()->value() );
++i;
}
}
} // namespace lmms::gui
| 5,405
|
C++
|
.cpp
| 198
| 24.757576
| 88
| 0.700876
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,958
|
TabBar.cpp
|
LMMS_lmms/src/gui/widgets/TabBar.cpp
|
/*
* TabBar.cpp - implementation of tab-bar
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TabBar.h"
#include "TabButton.h"
namespace lmms::gui
{
TabBar::TabBar( QWidget * _parent, QBoxLayout::Direction _dir ) :
QWidget( _parent ),
m_layout( new QBoxLayout( _dir, this ) ),
m_exclusive( false )
{
m_layout->setContentsMargins(8, 8, 8, 8);
m_layout->setSpacing( 0 );
setLayout( m_layout );
}
TabButton * TabBar::addTab( QWidget * _w, const QString & _text, int _id,
bool _add_stretch, bool _text_is_tooltip, bool fixWidgetToParentSize )
{
// already tab with id?
if( m_tabs.contains( _id ) )
{
// then remove it
removeTab( _id );
}
QString caption = ( _text_is_tooltip ) ? QString( "" ) : _text;
// create tab-button
auto b = new TabButton(caption, _id, this);
connect( b, SIGNAL(clicked(int)), this, SLOT(tabClicked(int)));
b->setIconSize( QSize( 48, 48 ) );
b->setFixedSize( 64, 64 );
b->show();
if( _text_is_tooltip )
{
b->setToolTip(_text);
}
// small workaround, because QBoxLayout::addWidget(...) doesn't
// work properly, so we first have to remove all tabs from the
// layout and them add them in the correct order
QMap<int, QPair<TabButton *, QWidget *> >::iterator it;
for( it = m_tabs.begin(); it != m_tabs.end(); ++it )
{
m_layout->removeWidget( it.value().first );
}
m_tabs.insert( _id, qMakePair( b, _w ) );
for( it = m_tabs.begin(); it != m_tabs.end(); ++it )
{
m_layout->addWidget( it.value().first );
}
if( _add_stretch )
{
m_layout->addStretch();
}
if (fixWidgetToParentSize)
{
// we assume, parent-widget is a widget acting as widget-stack so all
// widgets have the same size and only the one on the top is visible
_w->setFixedSize( _w->parentWidget()->size() );
}
return( b );
}
void TabBar::removeTab( int _id )
{
// find tab-button and delete it
if( m_tabs.find( _id ) != m_tabs.end() )
{
delete m_tabs[_id].first;
m_tabs.erase( m_tabs.find( _id ) );
}
}
void TabBar::setActiveTab( int _id )
{
setTabState( _id, true );
hideAll( _id );
if( allHidden() )
{
emit allWidgetsHidden();
}
else
{
emit widgetShown();
}
}
int TabBar::activeTab()
{
QMap<int, QPair<TabButton *, QWidget *> >::iterator it;
for( it = m_tabs.begin(); it != m_tabs.end(); ++it )
{
if( tabState( it.key() ) == true )
{
return( it.key() );
}
}
return( -1 );
}
bool TabBar::tabState( int _id )
{
if( m_tabs.find( _id ) == m_tabs.end() )
{
return( false );
}
return( m_tabs[_id].first->isChecked() );
}
void TabBar::setTabState( int _id, bool _checked )
{
if( m_tabs.find( _id ) != m_tabs.end() )
{
m_tabs[_id].first->setChecked( _checked );
}
}
void TabBar::hideAll( int _exception )
{
QMap<int, QPair<TabButton *, QWidget *> >::iterator it;
for( it = m_tabs.begin(); it != m_tabs.end(); ++it )
{
if( it.key() != _exception )
{
setTabState( it.key(), false );
}
it.value().second->hide();
}
if( m_tabs.find( _exception ) != m_tabs.end() )
{
if( tabState( _exception ) )
{
m_tabs[_exception].second->show();
}
else
{
m_tabs[_exception].second->hide();
}
}
}
void TabBar::tabClicked( int _id )
{
if( m_exclusive == true && activeTab() == -1 )
{
setActiveTab( _id );
}
else
{
bool all_hidden_before = allHidden();
// disable tabbar-buttons except the one clicked
hideAll( _id );
bool now_hidden = allHidden();
if( all_hidden_before == true && now_hidden == false )
{
emit widgetShown();
}
else if( all_hidden_before == false && now_hidden == true )
{
emit allWidgetsHidden();
}
}
}
bool TabBar::allHidden()
{
QMap<int, QPair<TabButton *, QWidget *> >::iterator it;
for( it = m_tabs.begin(); it != m_tabs.end(); ++it )
{
if( !it.value().second->isHidden() )
{
return( false );
}
}
return( true );
}
} // namespace lmms::gui
| 4,684
|
C++
|
.cpp
| 188
| 22.542553
| 77
| 0.655506
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,959
|
FloatModelEditorBase.cpp
|
LMMS_lmms/src/gui/widgets/FloatModelEditorBase.cpp
|
/*
* FloatModelEditorBase.cpp - Base editor for float models
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2023 Michael Gregorius
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "FloatModelEditorBase.h"
#include <QApplication>
#include <QInputDialog>
#include <QPainter>
#ifndef __USE_XOPEN
#define __USE_XOPEN
#endif
#include "lmms_math.h"
#include "CaptionMenu.h"
#include "ControllerConnection.h"
#include "GuiApplication.h"
#include "LocaleHelper.h"
#include "MainWindow.h"
#include "ProjectJournal.h"
#include "SimpleTextFloat.h"
#include "StringPairDrag.h"
namespace lmms::gui
{
SimpleTextFloat * FloatModelEditorBase::s_textFloat = nullptr;
FloatModelEditorBase::FloatModelEditorBase(DirectionOfManipulation directionOfManipulation, QWidget * parent, const QString & name) :
QWidget(parent),
FloatModelView(new FloatModel(0, 0, 0, 1, nullptr, name, true), this),
m_volumeKnob(false),
m_volumeRatio(100.0, 0.0, 1000000.0),
m_buttonPressed(false),
m_directionOfManipulation(directionOfManipulation)
{
initUi(name);
}
void FloatModelEditorBase::initUi(const QString & name)
{
if (s_textFloat == nullptr)
{
s_textFloat = new SimpleTextFloat;
}
setWindowTitle(name);
setFocusPolicy(Qt::ClickFocus);
doConnections();
}
void FloatModelEditorBase::showTextFloat(int msecBeforeDisplay, int msecDisplayTime)
{
s_textFloat->setText(displayValue());
s_textFloat->moveGlobal(this, QPoint(width() + 2, 0));
s_textFloat->showWithDelay(msecBeforeDisplay, msecDisplayTime);
}
float FloatModelEditorBase::getValue(const QPoint & p)
{
// Find out which direction/coordinate is relevant for this control
int const coordinate = m_directionOfManipulation == DirectionOfManipulation::Vertical ? p.y() : -p.x();
// knob value increase is linear to mouse movement
float value = .4f * coordinate;
// if shift pressed we want slower movement
if (getGUI()->mainWindow()->isShiftPressed())
{
value /= 4.0f;
value = qBound(-4.0f, value, 4.0f);
}
return value * pageSize();
}
void FloatModelEditorBase::contextMenuEvent(QContextMenuEvent *)
{
// for the case, the user clicked right while pressing left mouse-
// button, the context-menu appears while mouse-cursor is still hidden
// and it isn't shown again until user does something which causes
// an QApplication::restoreOverrideCursor()-call...
mouseReleaseEvent(nullptr);
CaptionMenu contextMenu(model()->displayName(), this);
addDefaultActions(&contextMenu);
contextMenu.addAction(QPixmap(),
model()->isScaleLogarithmic() ? tr("Set linear") : tr("Set logarithmic"),
this, SLOT(toggleScale()));
contextMenu.addSeparator();
contextMenu.exec(QCursor::pos());
}
void FloatModelEditorBase::toggleScale()
{
model()->setScaleLogarithmic(! model()->isScaleLogarithmic());
update();
}
void FloatModelEditorBase::dragEnterEvent(QDragEnterEvent * dee)
{
StringPairDrag::processDragEnterEvent(dee, "float_value,"
"automatable_model");
}
void FloatModelEditorBase::dropEvent(QDropEvent * de)
{
QString type = StringPairDrag::decodeKey(de);
QString val = StringPairDrag::decodeValue(de);
if (type == "float_value")
{
model()->setValue(LocaleHelper::toFloat(val));
de->accept();
}
else if (type == "automatable_model")
{
auto mod = dynamic_cast<AutomatableModel*>(Engine::projectJournal()->journallingObject(val.toInt()));
if (mod != nullptr)
{
AutomatableModel::linkModels(model(), mod);
mod->setValue(model()->value());
}
}
}
void FloatModelEditorBase::mousePressEvent(QMouseEvent * me)
{
if (me->button() == Qt::LeftButton &&
! (me->modifiers() & Qt::ControlModifier) &&
! (me->modifiers() & Qt::ShiftModifier))
{
AutomatableModel *thisModel = model();
if (thisModel)
{
thisModel->addJournalCheckPoint();
thisModel->saveJournallingState(false);
}
const QPoint & p = me->pos();
m_lastMousePos = p;
m_leftOver = 0.0f;
emit sliderPressed();
showTextFloat(0, 0);
s_textFloat->setText(displayValue());
s_textFloat->moveGlobal(this,
QPoint(width() + 2, 0));
s_textFloat->show();
m_buttonPressed = true;
}
else if (me->button() == Qt::LeftButton &&
(me->modifiers() & Qt::ShiftModifier))
{
new StringPairDrag("float_value",
QString::number(model()->value()),
QPixmap(), this);
}
else
{
FloatModelView::mousePressEvent(me);
}
}
void FloatModelEditorBase::mouseMoveEvent(QMouseEvent * me)
{
if (m_buttonPressed && me->pos() != m_lastMousePos)
{
// knob position is changed depending on last mouse position
setPosition(me->pos() - m_lastMousePos);
emit sliderMoved(model()->value());
// original position for next time is current position
m_lastMousePos = me->pos();
}
s_textFloat->setText(displayValue());
s_textFloat->show();
}
void FloatModelEditorBase::mouseReleaseEvent(QMouseEvent* event)
{
if (event && event->button() == Qt::LeftButton)
{
AutomatableModel *thisModel = model();
if (thisModel)
{
thisModel->restoreJournallingState();
}
}
m_buttonPressed = false;
emit sliderReleased();
QApplication::restoreOverrideCursor();
s_textFloat->hide();
}
void FloatModelEditorBase::enterEvent(QEvent *event)
{
showTextFloat(700, 2000);
}
void FloatModelEditorBase::leaveEvent(QEvent *event)
{
s_textFloat->hide();
}
void FloatModelEditorBase::focusOutEvent(QFocusEvent * fe)
{
// make sure we don't loose mouse release event
mouseReleaseEvent(nullptr);
QWidget::focusOutEvent(fe);
}
void FloatModelEditorBase::mouseDoubleClickEvent(QMouseEvent *)
{
enterValue();
}
void FloatModelEditorBase::paintEvent(QPaintEvent *)
{
QPainter p(this);
QColor const foreground(3, 94, 97);
auto const * mod = model();
auto const minValue = mod->minValue();
auto const maxValue = mod->maxValue();
auto const range = maxValue - minValue;
// Compute the percentage
// min + x * (max - min) = v <=> x = (v - min) / (max - min)
auto const percentage = range == 0 ? 1. : (mod->value() - minValue) / range;
QRect r = rect();
p.setPen(foreground);
p.setBrush(foreground);
p.drawRect(QRect(r.topLeft(), QPoint(r.width() * percentage, r.height())));
}
void FloatModelEditorBase::wheelEvent(QWheelEvent * we)
{
we->accept();
const int deltaY = we->angleDelta().y();
float direction = deltaY > 0 ? 1 : -1;
auto * m = model();
float const step = m->step<float>();
float const range = m->range();
// This is the default number of steps or mouse wheel events that it takes to sweep
// from the lowest value to the highest value.
// It might be modified if the user presses modifier keys. See below.
float numberOfStepsForFullSweep = 100.;
auto const modKeys = we->modifiers();
if (modKeys == Qt::ShiftModifier)
{
// The shift is intended to go through the values in very coarse steps as in:
// "Shift into overdrive"
numberOfStepsForFullSweep = 10;
}
else if (modKeys == Qt::ControlModifier)
{
// The control key gives more control, i.e. it enables more fine-grained adjustments
numberOfStepsForFullSweep = 1000;
}
else if (modKeys == Qt::AltModifier)
{
// The alt key enables even finer adjustments
numberOfStepsForFullSweep = 2000;
// It seems that on some systems pressing Alt with mess with the directions,
// i.e. scrolling the mouse wheel is interpreted as pressing the mouse wheel
// left and right. Account for this quirk.
if (deltaY == 0)
{
int const deltaX = we->angleDelta().x();
if (deltaX != 0)
{
direction = deltaX > 0 ? 1 : -1;
}
}
}
// Handle "natural" scrolling, which is common on trackpads and touch devices
if (we->inverted()) {
direction = -direction;
}
// Compute the number of steps but make sure that we always do at least one step
const float stepMult = std::max(range / numberOfStepsForFullSweep / step, 1.f);
const int inc = direction * stepMult;
model()->incValue(inc);
s_textFloat->setText(displayValue());
s_textFloat->moveGlobal(this, QPoint(width() + 2, 0));
s_textFloat->setVisibilityTimeOut(1000);
emit sliderMoved(model()->value());
}
void FloatModelEditorBase::setPosition(const QPoint & p)
{
const float value = getValue(p) + m_leftOver;
const auto step = model()->step<float>();
const float oldValue = model()->value();
if (model()->isScaleLogarithmic()) // logarithmic code
{
const float pos = model()->minValue() < 0
? oldValue / qMax(qAbs(model()->maxValue()), qAbs(model()->minValue()))
: (oldValue - model()->minValue()) / model()->range();
const float ratio = 0.1f + qAbs(pos) * 15.f;
float newValue = value * ratio;
if (qAbs(newValue) >= step)
{
float roundedValue = qRound((oldValue - value) / step) * step;
model()->setValue(roundedValue);
m_leftOver = 0.0f;
}
else
{
m_leftOver = value;
}
}
else // linear code
{
if (qAbs(value) >= step)
{
float roundedValue = qRound((oldValue - value) / step) * step;
model()->setValue(roundedValue);
m_leftOver = 0.0f;
}
else
{
m_leftOver = value;
}
}
}
void FloatModelEditorBase::enterValue()
{
bool ok;
float new_val;
if (isVolumeKnob() &&
ConfigManager::inst()->value("app", "displaydbfs").toInt())
{
auto const initalValue = model()->getRoundedValue() / 100.0;
auto const initialDbValue = initalValue > 0. ? ampToDbfs(initalValue) : -96;
new_val = QInputDialog::getDouble(
this, tr("Set value"),
tr("Please enter a new value between "
"-96.0 dBFS and 6.0 dBFS:"),
initialDbValue, -96.0, 6.0, model()->getDigitCount(), &ok);
if (new_val <= -96.0)
{
new_val = 0.0f;
}
else
{
new_val = dbfsToAmp(new_val) * 100.0;
}
}
else
{
new_val = QInputDialog::getDouble(
this, tr("Set value"),
tr("Please enter a new value between "
"%1 and %2:").
arg(model()->minValue()).
arg(model()->maxValue()),
model()->getRoundedValue(),
model()->minValue(),
model()->maxValue(), model()->getDigitCount(), &ok);
}
if (ok)
{
model()->setValue(new_val);
}
}
void FloatModelEditorBase::friendlyUpdate()
{
if (model() && (model()->controllerConnection() == nullptr ||
model()->controllerConnection()->getController()->frequentUpdates() == false ||
Controller::runningFrames() % (256*4) == 0))
{
update();
}
}
QString FloatModelEditorBase::displayValue() const
{
if (isVolumeKnob() &&
ConfigManager::inst()->value("app", "displaydbfs").toInt())
{
auto const valueToVolumeRatio = model()->getRoundedValue() / volumeRatio();
return m_description.trimmed() + (
valueToVolumeRatio == 0.
? QString(" -∞ dBFS")
: QString(" %1 dBFS").arg(ampToDbfs(valueToVolumeRatio), 3, 'f', 2)
);
}
return m_description.trimmed() + QString(" %1").
arg(model()->getRoundedValue()) + m_unit;
}
void FloatModelEditorBase::doConnections()
{
if (model() != nullptr)
{
QObject::connect(model(), SIGNAL(dataChanged()),
this, SLOT(friendlyUpdate()));
QObject::connect(model(), SIGNAL(propertiesChanged()),
this, SLOT(update()));
}
}
} // namespace lmms::gui
| 11,763
|
C++
|
.cpp
| 389
| 27.676093
| 133
| 0.714387
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,960
|
CustomTextKnob.cpp
|
LMMS_lmms/src/gui/widgets/CustomTextKnob.cpp
|
/*
* CustomTextKnob.cpp
*
* Copyright (c) 2020 Ibuki Sugiyama <main/at/fuwa.dev>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "CustomTextKnob.h"
namespace lmms::gui
{
CustomTextKnob::CustomTextKnob( KnobType _knob_num, QWidget * _parent, const QString & _name, const QString & _value_text ) :
Knob( _knob_num, _parent, _name ),
m_value_text( _value_text ) {}
CustomTextKnob::CustomTextKnob( QWidget * _parent, const QString & _name, const QString & _value_text ) : //!< default ctor
Knob( _parent, _name ),
m_value_text( _value_text ) {}
QString CustomTextKnob::displayValue() const
{
return m_description.trimmed() + m_value_text;
}
} // namespace lmms::gui
| 1,433
|
C++
|
.cpp
| 37
| 36.783784
| 125
| 0.737032
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,961
|
CPULoadWidget.cpp
|
LMMS_lmms/src/gui/widgets/CPULoadWidget.cpp
|
/*
* CPULoadWidget.cpp - widget for displaying CPU-load (partly based on
* Hydrogen's CPU-load-widget)
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <algorithm>
#include <QPainter>
#include "AudioEngine.h"
#include "CPULoadWidget.h"
#include "embed.h"
#include "Engine.h"
namespace lmms::gui
{
CPULoadWidget::CPULoadWidget( QWidget * _parent ) :
QWidget( _parent ),
m_currentLoad( 0 ),
m_temp(),
m_background( embed::getIconPixmap( "cpuload_bg" ) ),
m_leds( embed::getIconPixmap( "cpuload_leds" ) ),
m_changed( true ),
m_updateTimer()
{
setAttribute( Qt::WA_OpaquePaintEvent, true );
setFixedSize( m_background.width(), m_background.height() );
m_temp = QPixmap( width(), height() );
connect( &m_updateTimer, SIGNAL(timeout()),
this, SLOT(updateCpuLoad()));
m_updateTimer.start( 100 ); // update cpu-load at 10 fps
}
void CPULoadWidget::paintEvent( QPaintEvent * )
{
if( m_changed == true )
{
m_changed = false;
m_temp.fill( QColor(0,0,0,0) );
QPainter p( &m_temp );
p.drawPixmap( 0, 0, m_background );
// Normally the CPU load indicator moves smoothly, with 1 pixel resolution. However, some themes may want to
// draw discrete elements (like LEDs), so the stepSize property can be used to specify a larger step size.
int w = (m_leds.width() * std::min(m_currentLoad, 100) / (stepSize() * 100)) * stepSize();
if( w > 0 )
{
p.drawPixmap( 23, 3, m_leds, 0, 0, w,
m_leds.height() );
}
}
QPainter p( this );
p.drawPixmap( 0, 0, m_temp );
}
void CPULoadWidget::updateCpuLoad()
{
// Additional display smoothing for the main load-value. Stronger averaging
// cannot be used directly in the profiler: cpuLoad() must react fast enough
// to be useful as overload indicator in AudioEngine::criticalXRuns().
const int new_load = (m_currentLoad + Engine::audioEngine()->cpuLoad()) / 2;
if (new_load != m_currentLoad)
{
auto engine = Engine::audioEngine();
setToolTip(
tr("DSP total: %1%").arg(new_load) + "\n"
+ tr(" - Notes and setup: %1%").arg(engine->detailLoad(AudioEngineProfiler::DetailType::NoteSetup)) + "\n"
+ tr(" - Instruments: %1%").arg(engine->detailLoad(AudioEngineProfiler::DetailType::Instruments)) + "\n"
+ tr(" - Effects: %1%").arg(engine->detailLoad(AudioEngineProfiler::DetailType::Effects)) + "\n"
+ tr(" - Mixing: %1%").arg(engine->detailLoad(AudioEngineProfiler::DetailType::Mixing))
);
m_currentLoad = new_load;
m_changed = true;
update();
}
}
} // namespace lmms::gui
| 3,361
|
C++
|
.cpp
| 90
| 34.8
| 110
| 0.702653
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,962
|
TimeDisplayWidget.cpp
|
LMMS_lmms/src/gui/widgets/TimeDisplayWidget.cpp
|
/*
* TimeDisplayWidget.cpp - widget for displaying current playback time
*
* Copyright (c) 2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QMouseEvent>
#include "TimeDisplayWidget.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "Engine.h"
#include "Song.h"
namespace lmms::gui
{
TimeDisplayWidget::TimeDisplayWidget() :
QWidget(),
m_displayMode( DisplayMode::MinutesSeconds ),
m_spinBoxesLayout( this ),
m_majorLCD( 4, this ),
m_minorLCD( 2, this ),
m_milliSecondsLCD( 3, this )
{
m_spinBoxesLayout.setSpacing( 0 );
m_spinBoxesLayout.setContentsMargins(0, 0, 0, 0);
m_spinBoxesLayout.addWidget( &m_majorLCD );
m_spinBoxesLayout.addWidget( &m_minorLCD );
m_spinBoxesLayout.addWidget( &m_milliSecondsLCD );
setMaximumHeight( 32 );
setToolTip(tr("Time units"));
// update labels of LCD spinboxes
setDisplayMode( m_displayMode );
connect( getGUI()->mainWindow(), SIGNAL(periodicUpdate()),
this, SLOT(updateTime()));
}
void TimeDisplayWidget::setDisplayMode( DisplayMode displayMode )
{
m_displayMode = displayMode;
switch( m_displayMode )
{
case DisplayMode::MinutesSeconds:
m_majorLCD.setLabel( tr( "MIN" ) );
m_minorLCD.setLabel( tr( "SEC" ) );
m_milliSecondsLCD.setLabel( tr( "MSEC" ) );
break;
case DisplayMode::BarsTicks:
m_majorLCD.setLabel( tr( "BAR" ) );
m_minorLCD.setLabel( tr( "BEAT" ) );
m_milliSecondsLCD.setLabel( tr( "TICK" ) );
break;
default: break;
}
}
void TimeDisplayWidget::updateTime()
{
Song* s = Engine::getSong();
switch( m_displayMode )
{
case DisplayMode::MinutesSeconds:
{
int msec = s->getMilliseconds();
m_majorLCD.setValue(msec / 60000);
m_minorLCD.setValue((msec / 1000) % 60);
m_milliSecondsLCD.setValue(msec % 1000);
break;
}
case DisplayMode::BarsTicks:
{
int tick = s->getPlayPos().getTicks();
m_majorLCD.setValue((int)(tick / s->ticksPerBar()) + 1);
m_minorLCD.setValue((tick % s->ticksPerBar()) /
(s->ticksPerBar() / s->getTimeSigModel().getNumerator() ) +1);
m_milliSecondsLCD.setValue((tick % s->ticksPerBar()) %
(s->ticksPerBar() / s->getTimeSigModel().getNumerator()));
break;
}
default:
break;
}
}
void TimeDisplayWidget::mousePressEvent( QMouseEvent* mouseEvent )
{
if( mouseEvent->button() == Qt::LeftButton )
{
if( m_displayMode == DisplayMode::MinutesSeconds )
{
setDisplayMode( DisplayMode::BarsTicks );
}
else
{
setDisplayMode( DisplayMode::MinutesSeconds );
}
}
}
} // namespace lmms::gui
| 3,329
|
C++
|
.cpp
| 111
| 27.324324
| 72
| 0.720901
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,963
|
LcdFloatSpinBox.cpp
|
LMMS_lmms/src/gui/widgets/LcdFloatSpinBox.cpp
|
/*
* LcdFloatSpinBox.cpp - class LcdFloatSpinBox (LcdSpinBox for floats)
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008 Paul Giblock <pgllama/at/gmail.com>
* Copyright (c) 2020 Martin Pavelek <he29.HS/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LcdFloatSpinBox.h"
#include <cmath>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QStyleOptionFrame>
#include <QVBoxLayout>
#include "CaptionMenu.h"
#include "DeprecationHelper.h"
#include "embed.h"
#include "GuiApplication.h"
#include "FontHelper.h"
#include "MainWindow.h"
namespace lmms::gui
{
LcdFloatSpinBox::LcdFloatSpinBox(int numWhole, int numFrac, const QString& name, QWidget* parent) :
QWidget(parent),
FloatModelView(new FloatModel(0, 0, 0, 0, nullptr, name, true), this),
m_wholeDisplay(numWhole, parent, name, false),
m_fractionDisplay(numFrac, parent, name, true),
m_mouseMoving(false),
m_intStep(false),
m_origMousePos(),
m_displayOffset(0)
{
layoutSetup();
}
LcdFloatSpinBox::LcdFloatSpinBox(int numWhole, int numFrac, const QString& style, const QString& name, QWidget* parent) :
QWidget(parent),
FloatModelView(new FloatModel(0, 0, 0, 0, nullptr, name, true), this),
m_wholeDisplay(numWhole, style, parent, name, false),
m_fractionDisplay(numFrac, style, parent, name, true),
m_mouseMoving(false),
m_intStep(false),
m_origMousePos(),
m_displayOffset(0)
{
layoutSetup(style);
}
void LcdFloatSpinBox::layoutSetup(const QString &style)
{
// Assemble the LCD parts
auto lcdLayout = new QHBoxLayout();
m_wholeDisplay.setSeamless(false, true);
m_fractionDisplay.setSeamless(true, false);
lcdLayout->addWidget(&m_wholeDisplay);
auto dotLabel = new QLabel("", this);
QPixmap dotPixmap(embed::getIconPixmap(QString("lcd_" + style + "_dot").toUtf8().constData()));
dotLabel->setPixmap(dotPixmap.copy(0, 0, dotPixmap.size().width(), dotPixmap.size().height() / 2));
lcdLayout->addWidget(dotLabel);
lcdLayout->addWidget(&m_fractionDisplay);
lcdLayout->setContentsMargins(0, 0, 0, 0);
lcdLayout->setSpacing(0);
// Add space for label
auto outerLayout = new QVBoxLayout();
outerLayout->addLayout(lcdLayout);
outerLayout->addSpacing(9);
outerLayout->setContentsMargins(0, 0, 0, 0);
outerLayout->setSizeConstraint(QLayout::SetFixedSize);
this->setLayout(outerLayout);
this->setFixedHeight(32);
}
void LcdFloatSpinBox::update()
{
const int digitValue = std::pow(10.f, m_fractionDisplay.numDigits());
float value = model()->value();
int fraction = std::abs(std::round((value - static_cast<int>(value)) * digitValue));
if (fraction == digitValue)
{
value += std::copysign(1, value);
fraction = 0;
}
m_wholeDisplay.setValue(value);
m_fractionDisplay.setValue(fraction);
QWidget::update();
}
void LcdFloatSpinBox::contextMenuEvent(QContextMenuEvent* event)
{
CaptionMenu contextMenu(model()->displayName());
addDefaultActions(&contextMenu);
contextMenu.exec(QCursor::pos());
}
void LcdFloatSpinBox::mousePressEvent(QMouseEvent* event)
{
// switch between integer and fractional step based on cursor position
m_intStep = event->x() < m_wholeDisplay.width();
if (event->button() == Qt::LeftButton &&
!(event->modifiers() & Qt::ControlModifier) &&
event->y() < m_wholeDisplay.cellHeight() + 2)
{
m_mouseMoving = true;
m_origMousePos = event->globalPos();
AutomatableModel *thisModel = model();
if (thisModel)
{
thisModel->addJournalCheckPoint();
thisModel->saveJournallingState(false);
}
}
else
{
FloatModelView::mousePressEvent(event);
}
}
void LcdFloatSpinBox::mouseMoveEvent(QMouseEvent* event)
{
if (m_mouseMoving)
{
int dy = event->globalY() - m_origMousePos.y();
if (getGUI()->mainWindow()->isShiftPressed()) { dy = qBound(-4, dy/4, 4); }
if (dy > 1 || dy < -1)
{
model()->setValue(model()->value() - dy / 2 * getStep());
emit manualChange();
m_origMousePos = event->globalPos();
}
}
}
void LcdFloatSpinBox::mouseReleaseEvent(QMouseEvent*)
{
if (m_mouseMoving)
{
model()->restoreJournallingState();
m_mouseMoving = false;
}
}
void LcdFloatSpinBox::wheelEvent(QWheelEvent *event)
{
// switch between integer and fractional step based on cursor position
if (position(event).x() < m_wholeDisplay.width()) { m_intStep = true; }
else { m_intStep = false; }
event->accept();
model()->setValue(model()->value() + ((event->angleDelta().y() > 0) ? 1 : -1) * getStep());
emit manualChange();
}
void LcdFloatSpinBox::mouseDoubleClickEvent(QMouseEvent *)
{
enterValue();
}
void LcdFloatSpinBox::enterValue()
{
bool ok;
float newVal;
newVal = QInputDialog::getDouble(
this, tr("Set value"),
tr("Please enter a new value between %1 and %2:").
arg(model()->minValue()).
arg(model()->maxValue()),
model()->value(),
model()->minValue(),
model()->maxValue(),
m_fractionDisplay.numDigits(), &ok);
if (ok)
{
model()->setValue(newVal);
}
}
float LcdFloatSpinBox::getStep() const
{
if (m_intStep) { return 1; }
else { return model()->step<float>(); }
}
void LcdFloatSpinBox::paintEvent(QPaintEvent*)
{
QPainter p(this);
// Border
QStyleOptionFrame opt;
opt.initFrom(this);
opt.state = QStyle::State_Sunken;
opt.rect = QRect(0, 0, width() - 1, m_wholeDisplay.height());
style()->drawPrimitive(QStyle::PE_Frame, &opt, &p, this);
// Label
if (!m_label.isEmpty())
{
p.setFont(adjustedToPixelSize(p.font(), DEFAULT_FONT_SIZE));
p.setPen(m_wholeDisplay.textShadowColor());
p.drawText(width() / 2 - p.fontMetrics().boundingRect(m_label).width() / 2 + 1, height(), m_label);
p.setPen(m_wholeDisplay.textColor());
p.drawText(width() / 2 - p.fontMetrics().boundingRect(m_label).width() / 2, height() - 1, m_label);
}
}
} // namespace lmms::gui
| 6,607
|
C++
|
.cpp
| 210
| 29.271429
| 121
| 0.729291
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,964
|
ToolButton.cpp
|
LMMS_lmms/src/gui/widgets/ToolButton.cpp
|
/*
* ToolButton.cpp - implementation of LMMS-tool-button for common (cool) look
*
* Copyright (c) 2005-2006 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ToolButton.h"
namespace lmms::gui
{
ToolButton::ToolButton( const QPixmap & _pixmap, const QString & _tooltip,
QObject * _receiver, const char * _slot,
QWidget * _parent ) :
QToolButton( _parent )
{
setAutoFillBackground( false );
if( _receiver != nullptr && _slot != nullptr )
{
connect( this, SIGNAL(clicked()), _receiver, _slot );
}
setToolTip(_tooltip);
setIcon( _pixmap );
}
} // namespace lmms::gui
| 1,395
|
C++
|
.cpp
| 40
| 32.725
| 77
| 0.734224
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,965
|
LcdSpinBox.cpp
|
LMMS_lmms/src/gui/widgets/LcdSpinBox.cpp
|
/*
* LcdSpinBox.cpp - class LcdSpinBox, an improved QLCDNumber
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008 Paul Giblock <pgllama/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <cmath>
#include <QMouseEvent>
#include <QInputDialog>
#include "LcdSpinBox.h"
#include "CaptionMenu.h"
namespace lmms::gui
{
LcdSpinBox::LcdSpinBox( int numDigits, QWidget* parent, const QString& name ) :
LcdWidget( numDigits, parent, name ),
IntModelView( new IntModel( 0, 0, 0, nullptr, name, true ), this ),
m_remainder( 0.f ),
m_mouseMoving( false ),
m_lastMousePos(),
m_displayOffset( 0 )
{
}
LcdSpinBox::LcdSpinBox( int numDigits, const QString& style, QWidget* parent, const QString& name ) :
LcdWidget( numDigits, style, parent, name ),
IntModelView( new IntModel( 0, 0, 0, nullptr, name, true ), this ),
m_remainder( 0.f ),
m_mouseMoving( false ),
m_lastMousePos(),
m_displayOffset( 0 )
{
}
void LcdSpinBox::update()
{
setValue( model()->value() + m_displayOffset );
QWidget::update();
}
void LcdSpinBox::contextMenuEvent(QContextMenuEvent* event)
{
CaptionMenu contextMenu(model()->displayName());
addDefaultActions(&contextMenu);
contextMenu.exec(QCursor::pos());
}
void LcdSpinBox::mousePressEvent( QMouseEvent* event )
{
if( event->button() == Qt::LeftButton &&
! ( event->modifiers() & Qt::ControlModifier ) &&
event->y() < cellHeight() + 2 )
{
m_mouseMoving = true;
m_lastMousePos = event->globalPos();
AutomatableModel *thisModel = model();
if( thisModel )
{
thisModel->addJournalCheckPoint();
thisModel->saveJournallingState( false );
}
}
else
{
IntModelView::mousePressEvent( event );
}
}
void LcdSpinBox::mouseMoveEvent( QMouseEvent* event )
{
if( m_mouseMoving )
{
int dy = event->globalY() - m_lastMousePos.y();
if( dy )
{
auto fdy = static_cast<float>(dy);
if( event->modifiers() & Qt::ShiftModifier ) {
fdy = qBound( -4.f, fdy/4.f, 4.f );
}
float floatValNotRounded =
model()->value() + m_remainder - fdy / 2.f * model()->step<int>();
float floatValRounded = roundf( floatValNotRounded );
m_remainder = floatValNotRounded - floatValRounded;
model()->setValue( floatValRounded );
emit manualChange();
m_lastMousePos = event->globalPos();
}
}
}
void LcdSpinBox::mouseReleaseEvent(QMouseEvent*)
{
if (m_mouseMoving)
{
model()->restoreJournallingState();
m_mouseMoving = false;
}
}
void LcdSpinBox::wheelEvent(QWheelEvent * we)
{
we->accept();
const int direction = (we->angleDelta().y() > 0 ? 1 : -1) * (we->inverted() ? -1 : 1);
model()->setValue(model()->value() + direction * model()->step<int>());
emit manualChange();
}
void LcdSpinBox::mouseDoubleClickEvent( QMouseEvent * )
{
enterValue();
}
void LcdSpinBox::enterValue()
{
bool ok;
int new_val;
new_val = QInputDialog::getInt(
this, tr( "Set value" ),
tr( "Please enter a new value between %1 and %2:" ).
arg( model()->minValue() ).
arg( model()->maxValue() ),
model()->value(),
model()->minValue(),
model()->maxValue(),
model()->step<int>(), &ok );
if( ok )
{
model()->setValue( new_val );
}
}
} // namespace lmms::gui
| 3,984
|
C++
|
.cpp
| 139
| 26.215827
| 101
| 0.701681
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,966
|
GroupBox.cpp
|
LMMS_lmms/src/gui/widgets/GroupBox.cpp
|
/*
* GroupBox.cpp - groupbox for LMMS
*
* Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QMouseEvent>
#include <QPainter>
#ifndef __USE_XOPEN
#define __USE_XOPEN
#endif
#include "GroupBox.h"
#include "embed.h"
#include "FontHelper.h"
namespace lmms::gui
{
GroupBox::GroupBox( const QString & _caption, QWidget * _parent ) :
QWidget( _parent ),
BoolModelView( nullptr, this ),
m_caption( _caption ),
m_titleBarHeight( 11 )
{
m_led = new PixmapButton( this, _caption );
m_led->setCheckable( true );
m_led->move( 3, 0 );
m_led->setActiveGraphic( embed::getIconPixmap( "led_green" ) );
m_led->setInactiveGraphic( embed::getIconPixmap( "led_off" ) );
setModel( new BoolModel( false, nullptr, _caption, true ) );
setAutoFillBackground( true );
unsetCursor();
}
GroupBox::~GroupBox()
{
delete m_led;
}
void GroupBox::modelChanged()
{
m_led->setModel( model() );
}
bool GroupBox::ledButtonShown() const
{
return m_led->isVisible();
}
void GroupBox::setLedButtonShown(bool value)
{
m_led->setVisible(value);
}
void GroupBox::mousePressEvent( QMouseEvent * _me )
{
if (ledButtonShown() && _me->y() > 1 && _me->y() < 13 && _me->button() == Qt::LeftButton)
{
model()->setValue(!model()->value());
}
}
void GroupBox::paintEvent( QPaintEvent * pe )
{
QPainter p( this );
// Draw background
p.fillRect( 0, 0, width() - 1, height() - 1, p.background() );
// outer rect
p.setPen( p.background().color().darker( 150 ) );
p.drawRect( 0, 0, width() - 1, height() - 1 );
// draw line below titlebar
p.fillRect( 1, 1, width() - 2, m_titleBarHeight + 1, p.background().color().darker( 150 ) );
// draw text
p.setPen( palette().color( QPalette::Active, QPalette::Text ) );
p.setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE));
int const captionX = ledButtonShown() ? 22 : 6;
p.drawText(captionX, m_titleBarHeight, m_caption);
}
} // namespace lmms::gui
| 2,736
|
C++
|
.cpp
| 88
| 29.079545
| 93
| 0.710516
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,967
|
TabWidget.cpp
|
LMMS_lmms/src/gui/widgets/TabWidget.cpp
|
/*
* TabWidget.cpp - tabwidget for LMMS
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TabWidget.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QToolTip>
#include <QWheelEvent>
#include "DeprecationHelper.h"
#include "embed.h"
#include "FontHelper.h"
namespace lmms::gui
{
TabWidget::TabWidget(const QString& caption, QWidget* parent, bool usePixmap,
bool resizable) :
QWidget(parent),
m_resizable(resizable),
m_activeTab(0),
m_caption(caption),
m_usePixmap(usePixmap),
m_tabText(0, 0, 0),
m_tabTitleText(0, 0, 0),
m_tabSelected(0, 0, 0),
m_tabTextSelected(0, 0, 0),
m_tabBackground(0, 0, 0),
m_tabBorder(0, 0, 0)
{
// Create taller tabbar when it's to display artwork tabs
m_tabbarHeight = usePixmap ? GRAPHIC_TAB_HEIGHT : TEXT_TAB_HEIGHT;
m_tabheight = caption.isEmpty() ? m_tabbarHeight - 3 : m_tabbarHeight - 4;
setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE));
setAutoFillBackground(true);
QColor bg_color = QApplication::palette().color(QPalette::Active, QPalette::Window).darker(132);
QPalette pal = palette();
pal.setColor(QPalette::Window, bg_color);
setPalette(pal);
}
void TabWidget::addTab(QWidget* w, const QString& name, const char* pixmap, int idx)
{
// Append tab when position is not given
if (idx < 0/* || m_widgets.contains(idx) == true*/)
{
while(m_widgets.contains(++idx) == true)
{
}
}
// Tab's width when it is a text tab. This isn't correct for artwork tabs, but it's fixed later during the PaintEvent
int tab_width = horizontalAdvance(fontMetrics(), name) + 10;
// Register new tab
widgetDesc d = {w, pixmap, name, tab_width};
m_widgets[idx] = d;
// Position tab's window
if (!m_resizable)
{
w->setFixedSize(width() - 4, height() - m_tabbarHeight);
}
w->move(2, m_tabbarHeight - 1);
w->hide();
// Show tab's window if it's active
if (m_widgets.contains(m_activeTab))
{
// make sure new tab doesn't overlap current widget
m_widgets[m_activeTab].w->show();
m_widgets[m_activeTab].w->raise();
}
}
void TabWidget::setActiveTab(int idx)
{
if (m_widgets.contains(idx))
{
int old_active = m_activeTab;
m_activeTab = idx;
m_widgets[m_activeTab].w->raise();
m_widgets[m_activeTab].w->show();
if (old_active != idx && m_widgets.contains(old_active))
{
m_widgets[old_active].w->hide();
}
update();
}
}
// Return the index of the tab at position "pos"
int TabWidget::findTabAtPos(const QPoint* pos)
{
if (pos->y() > 1 && pos->y() < m_tabbarHeight - 1)
{
int cx = ((m_caption == "") ? 4 : 14) + horizontalAdvance(fontMetrics(), m_caption);
for (widgetStack::iterator it = m_widgets.begin(); it != m_widgets.end(); ++it)
{
int const currentWidgetWidth = it->nwidth;
if (pos->x() >= cx && pos->x() <= cx + currentWidgetWidth)
{
return(it.key());
}
cx += currentWidgetWidth;
}
}
// Haven't found any tab at position "pos"
return(-1);
}
// Overload the QWidget::event handler to display tooltips (from https://doc.qt.io/qt-4.8/qt-widgets-tooltips-example.html)
bool TabWidget::event(QEvent* event)
{
if (event->type() == QEvent::ToolTip)
{
auto helpEvent = static_cast<QHelpEvent*>(event);
int idx = findTabAtPos(& helpEvent->pos());
if (idx != -1)
{
// Display tab's tooltip
QToolTip::showText(helpEvent->globalPos(), m_widgets[idx].name);
}
else
{
// The tooltip event doesn't relate to any tab, let's ignore it
QToolTip::hideText();
event->ignore();
}
return true;
}
// not a Tooltip event, let's propagate it to the other event handlers
return QWidget::event(event);
}
// Activate tab when clicked
void TabWidget::mousePressEvent(QMouseEvent* me)
{
// Find index of tab that has been clicked
QPoint pos = me->pos();
int idx = findTabAtPos(&pos);
// When found, activate tab that has been clicked
if (idx != -1)
{
setActiveTab(idx);
update();
return;
}
}
void TabWidget::resizeEvent(QResizeEvent*)
{
if (!m_resizable)
{
for (const auto& widget : m_widgets)
{
widget.w->setFixedSize(width() - 4, height() - m_tabbarHeight);
}
}
}
void TabWidget::paintEvent(QPaintEvent* pe)
{
QPainter p(this);
p.setFont(adjustedToPixelSize(font(), DEFAULT_FONT_SIZE));
// Draw background
QBrush bg_color = p.background();
p.fillRect(0, 0, width() - 1, height() - 1, bg_color);
// Draw external borders
p.setPen(tabBorder());
p.drawRect(0, 0, width() - 1, height() - 1);
// Draw tabs' bar background
p.fillRect(1, 1, width() - 2, m_tabheight + 2, tabBackground());
// Draw title, if any
if (!m_caption.isEmpty())
{
p.setPen(tabTitleText());
p.drawText(5, 11, m_caption);
}
// Calculate the tabs' x (tabs are painted next to the caption)
int tab_x_offset = m_caption.isEmpty() ? 4 : 14 + horizontalAdvance(fontMetrics(), m_caption);
// Compute tabs' width depending on the number of tabs (only applicable for artwork tabs)
widgetStack::iterator first = m_widgets.begin();
widgetStack::iterator last = m_widgets.end();
int tab_width = width();
if (first != last)
{
tab_width = (width() - tab_x_offset) / std::distance(first, last);
}
// Draw all tabs
p.setPen(tabText());
for (widgetStack::iterator it = first ; it != last ; ++it)
{
auto & currentWidgetDesc = *it;
// Draw a text tab or a artwork tab.
if (m_usePixmap)
{
// Fixes tab's width, because original size is only correct for text tabs
currentWidgetDesc.nwidth = tab_width;
// Get artwork
QPixmap artwork(embed::getIconPixmap(currentWidgetDesc.pixmap));
// Highlight active tab
if (it.key() == m_activeTab)
{
p.fillRect(tab_x_offset, 0, currentWidgetDesc.nwidth, m_tabbarHeight - 1, tabSelected());
}
// Draw artwork
p.drawPixmap(tab_x_offset + (currentWidgetDesc.nwidth - artwork.width()) / 2, 1, artwork);
}
else
{
// Highlight tab when active
if (it.key() == m_activeTab)
{
p.fillRect(tab_x_offset, 2, currentWidgetDesc.nwidth - 6, m_tabbarHeight - 4, tabSelected());
p.setPen(tabTextSelected());
p.drawText(tab_x_offset + 3, m_tabheight + 1, currentWidgetDesc.name);
}
else
{
// Draw text
p.setPen(tabText());
p.drawText(tab_x_offset + 3, m_tabheight + 1, currentWidgetDesc.name);
}
}
// Next tab's horizontal position
tab_x_offset += currentWidgetDesc.nwidth;
}
}
// Switch between tabs with mouse wheel
void TabWidget::wheelEvent(QWheelEvent* we)
{
if (position(we).y() > m_tabheight)
{
return;
}
we->accept();
int dir = (we->angleDelta().y() < 0) ? 1 : -1;
int tab = m_activeTab;
while(tab > -1 && static_cast<int>(tab) < m_widgets.count())
{
tab += dir;
if (m_widgets.contains(tab))
{
break;
}
}
setActiveTab(tab);
}
// Let parent widgets know how much space this tab widget needs
QSize TabWidget::minimumSizeHint() const
{
if (m_resizable)
{
int maxWidth = 0, maxHeight = 0;
for (const auto& widget : m_widgets)
{
maxWidth = std::max(maxWidth, widget.w->minimumSizeHint().width());
maxHeight = std::max(maxHeight, widget.w->minimumSizeHint().height());
}
// "-1" :
// in "addTab", under "Position tab's window", the widget is
// moved up by 1 pixel
return QSize(maxWidth + 4, maxHeight + m_tabbarHeight - 1);
}
else { return QWidget::minimumSizeHint(); }
}
QSize TabWidget::sizeHint() const
{
if (m_resizable)
{
int maxWidth = 0, maxHeight = 0;
for (const auto& widget : m_widgets)
{
maxWidth = std::max(maxWidth, widget.w->sizeHint().width());
maxHeight = std::max(maxHeight, widget.w->sizeHint().height());
}
// "-1" :
// in "addTab", under "Position tab's window", the widget is
// moved up by 1 pixel
return QSize(maxWidth + 4, maxHeight + m_tabbarHeight - 1);
}
else { return QWidget::sizeHint(); }
}
// Return the color to be used to draw a TabWidget's title text (if any)
QColor TabWidget::tabTitleText() const
{
return m_tabTitleText;
}
// Set the color to be used to draw a TabWidget's title text (if any)
void TabWidget::setTabTitleText(const QColor& c)
{
m_tabTitleText = c;
}
// Return the color to be used to draw a TabWidget's text (if any)
QColor TabWidget::tabText() const
{
return m_tabText;
}
// Set the color to be used to draw a TabWidget's text (if any)
void TabWidget::setTabText(const QColor& c)
{
m_tabText = c;
}
// Return the color to be used to highlight a TabWidget'selected tab (if any)
QColor TabWidget::tabSelected() const
{
return m_tabSelected;
}
// Set the color to be used to highlight a TabWidget'selected tab (if any)
void TabWidget::setTabSelected(const QColor& c)
{
m_tabSelected = c;
}
// Return the text color of the selected tab
QColor TabWidget::tabTextSelected() const
{
return m_tabTextSelected;
}
// Set the text color of the selected tab
void TabWidget::setTabTextSelected(const QColor& c)
{
m_tabTextSelected = c;
}
// Return the color to be used for the TabWidget's background
QColor TabWidget::tabBackground() const
{
return m_tabBackground;
}
// Set the color to be used for the TabWidget's background
void TabWidget::setTabBackground(const QColor& c)
{
m_tabBackground = c;
}
// Return the color to be used for the TabWidget's borders
QColor TabWidget::tabBorder() const
{
return m_tabBorder;
}
// Set the color to be used for the TabWidget's borders
void TabWidget::setTabBorder(const QColor& c)
{
m_tabBorder = c;
}
} // namespace lmms::gui
| 10,211
|
C++
|
.cpp
| 352
| 26.573864
| 123
| 0.702927
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,968
|
Graph.cpp
|
LMMS_lmms/src/gui/widgets/Graph.cpp
|
/*
* Graph.cpp - a QT widget for displaying and manipulating waveforms
*
* Copyright (c) 2006-2007 Andreas Brandmaier <andy/at/brandmaier/dot/de>
* 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QPainter>
#include "Graph.h"
#include "SampleLoader.h"
#include "StringPairDrag.h"
#include "SampleBuffer.h"
#include "Oscillator.h"
namespace lmms
{
namespace gui
{
Graph::Graph( QWidget * _parent, Style _style, int _width,
int _height ) :
QWidget( _parent ),
/* TODO: size, background? */
ModelView( new graphModel( -1.0, 1.0, 128, nullptr, true ), this ),
m_graphStyle( _style )
{
m_mouseDown = false;
m_graphColor = QColor( 0xFF, 0xAA, 0x00 );
resize( _width, _height );
setAcceptDrops( true );
setCursor( Qt::CrossCursor );
auto gModel = castModel<graphModel>();
QObject::connect( gModel, SIGNAL(samplesChanged(int,int)),
this, SLOT(updateGraph(int,int)));
QObject::connect( gModel, SIGNAL(lengthChanged()),
this, SLOT(updateGraph()));
}
void Graph::setForeground( const QPixmap &_pixmap )
{
m_foreground = _pixmap;
}
void Graph::setGraphColor( QColor _graphcol )
{
m_graphColor = _graphcol;
}
/*
void graph::loadSampleFromFile( const QString & _filename )
{
int i;
// zero sample_shape
for( i = 0; i < sampleLength; i++ )
{
samplePointer[i] = 0;
}
// load user shape
sampleBuffer buffer( _filename );
// copy buffer data
int trimSize = fmin( size(), static_cast<int>(buffer.frames()) );
for( i = 0; i < trimSize; i++ )
{
samplePointer[i] = (float)*buffer.data()[i];
}
}
*/
void Graph::mouseMoveEvent ( QMouseEvent * _me )
{
// get position
int x = _me->x();
int y = _me->y();
/* static bool skip = false;
if( skip )
{
skip = false;
return;
}
*/
// avoid mouse leaps
int diff = x - m_lastCursorX;
/* if( diff >= 1 )
{
x = qMin( width() - 3, m_lastCursorX + 1 );
}
else if( diff <= -1 )
{
x = qMax( 2, m_lastCursorX - 1 );
}*/
x = qMax( 2, qMin( x, width()-3 ) );
y = qMax( 2, qMin( y, height()-3 ) );
drawLineAt( x, y, m_lastCursorX );
// update mouse
if( diff != 0 )
{
m_lastCursorX = x;
QPoint pt = mapToGlobal( QPoint( x, y ) );
QCursor::setPos( pt.x(), pt.y() );
}
// skip = true;
}
void Graph::mousePressEvent( QMouseEvent * _me )
{
if( _me->button() == Qt::LeftButton )
{
if ( !( _me->modifiers() & Qt::ShiftModifier ) )
{
// get position
int x = _me->x();
int y = _me->y();
changeSampleAt( x, y );
// toggle mouse state
m_mouseDown = true;
setCursor( Qt::BlankCursor );
m_lastCursorX = x;
}
else
{
//when shift-clicking, draw a line from last position to current
//position
int x = _me->x();
int y = _me->y();
drawLineAt( x, y, m_lastCursorX );
m_mouseDown = true;
setCursor( Qt::BlankCursor );
m_lastCursorX = x;
}
}
}
void Graph::drawLineAt( int _x, int _y, int _lastx )
{
float minVal = model()->minValue();
float maxVal = model()->maxValue();
if ( width() <= 4 )
{
return;
}
float xscale = static_cast<float>( model()->length() ) /
( width()-4 );
//consider border
_x -= 2;
_y -= 2;
_lastx -= 2;
_lastx = qMax( 0, qMin( _lastx, width()-5 ) );
float range = minVal - maxVal;
float val = ( _y*range/( height()-5 ) ) + maxVal;
int sample_begin, sample_end;
float lastval;
float val_begin, val_end;
if (_lastx > _x)
{
sample_begin = (int)((_x) * xscale);
sample_end = (int)ceil((_lastx+1) * xscale);
lastval = model() -> m_samples[ (int)( sample_end - 1 ) ];
val_begin = val;
val_end = lastval;
}
else
{
sample_begin = (int)(_lastx * xscale);
sample_end = (int)ceil((_x+1) * xscale);
lastval = model() -> m_samples[ (int)( sample_begin ) ];
val_begin = lastval;
val_end = val;
}
// calculate line drawing variables
int linelen = sample_end - sample_begin;
if (linelen == 1)
{
val_begin = val;
}
//int xstep = _x > _lastx ? -1 : 1;
float ystep = ( val_end - val_begin ) / linelen;
// draw a line
for ( int i = 0 ; i < linelen; i++ )
{
model()->drawSampleAt( sample_begin + i , val_begin + ((i ) * ystep));
}
// We've changed [sample_end, sample_begin)
// However, samplesChanged expects two end points
model()->samplesChanged(sample_begin, sample_end - 1);
}
void Graph::changeSampleAt( int _x, int _y )
{
float minVal = model()->minValue();
float maxVal = model()->maxValue();
if ( width() <= 4 )
{
return;
}
float xscale = static_cast<float>( model()->length() ) /
( width()-4 );
// consider border of background image
_x -= 2;
_y -= 2;
// subtract max from min because Qt's Y-axis is backwards
float range = minVal - maxVal;
float val = ( _y*range/( height()-5 ) ) + maxVal;
model()->setSampleAt( (int)( _x*xscale ), val );
}
void Graph::mouseReleaseEvent( QMouseEvent * _me )
{
if( _me->button() == Qt::LeftButton )
{
// toggle mouse state
m_mouseDown = false;
setCursor( Qt::CrossCursor );
update();
emit drawn();
}
}
void Graph::paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setPen( QPen( m_graphColor, 1 ) );
QColor gcol = QColor( m_graphColor.red(), m_graphColor.green(), m_graphColor.blue(), 100 );
QVector<float> * samps = &(model()->m_samples);
int length = model()->length();
const float maxVal = model()->maxValue();
const float minVal = model()->minValue();
float xscale = (float)( width()-4 ) / length;
float yscale = (float)( height()-4 ) / ( minVal - maxVal );
// Max index, more useful below
length--;
switch( m_graphStyle )
{
case Style::Linear:
p.setRenderHints( QPainter::Antialiasing, true );
for( int i=0; i < length; i++ )
{
// Needs to be rewritten
p.drawLine(
2+static_cast<int>(i*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
2+static_cast<int>((i+1)*xscale),
2+static_cast<int>( ( (*samps)[i+1] - maxVal ) * yscale )
);
}
// Draw last segment wrapped around
p.drawLine(2+static_cast<int>(length*xscale),
2+static_cast<int>( ( (*samps)[length] - maxVal ) * yscale ),
width()-3,
2+static_cast<int>( ( (*samps)[0] - maxVal ) * yscale ) );
p.setRenderHints( QPainter::Antialiasing, false );
break;
case Style::Nearest:
for( int i=0; i < length; i++ )
{
p.drawLine(2+static_cast<int>(i*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
2+static_cast<int>((i+1)*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale )
);
p.drawLine(2+static_cast<int>((i+1)*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
2+static_cast<int>((i+1)*xscale),
2+static_cast<int>( ( (*samps)[i+1] - maxVal ) * yscale )
);
}
p.drawLine(2+static_cast<int>(length*xscale),
2+static_cast<int>( ( (*samps)[length] - maxVal ) * yscale ),
width()-3,
2+static_cast<int>( ( (*samps)[length] - maxVal ) * yscale ) );
break;
case Style::LinearNonCyclic:
p.setRenderHints( QPainter::Antialiasing, true );
for( int i=0; i < length; i++ )
{
// Needs to be rewritten
p.drawLine(
2+static_cast<int>(i*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
2+static_cast<int>((i+1)*xscale),
2+static_cast<int>( ( (*samps)[i+1] - maxVal ) * yscale )
);
}
// Do not draw last segment wrapped around - hence, "non-cyclic"
p.setRenderHints( QPainter::Antialiasing, false );
break;
case Style::Bar:
for( int i=0; i <= length; i++ )
{
p.fillRect( 2+static_cast<int>( i*xscale ),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
qMax( static_cast<int>(xscale) - 1, 1 ),
qMax( static_cast<int>( ( minVal - maxVal ) * yscale ) - static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ), 1 ),
gcol );
p.setPen( QPen( m_graphColor, 1.0 ) );
p.drawLine( 2+static_cast<int>(i*xscale),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale ),
qMax( static_cast<int>(i*xscale) + static_cast<int>(xscale), 2+static_cast<int>(i*xscale) ),
2+static_cast<int>( ( (*samps)[i] - maxVal ) * yscale )
);
}
break;
default:
break;
}
// draw Pointer
if( m_mouseDown )
{
QPoint cursor = mapFromGlobal( QCursor::pos() );
p.setPen( QColor( 0x70, 0x7C, 0x91 ) );
p.drawLine( 2, cursor.y(), width()-2, cursor.y() );
p.drawLine( cursor.x(), 2, cursor.x(), height()-2 );
}
p.drawPixmap( 0, 0, m_foreground );
}
void Graph::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString value = StringPairDrag::decodeValue( _de );
if( type == "samplefile" )
{
// TODO: call setWaveToUser
// loadSampleFromFile( value );
_de->accept();
}
}
void Graph::dragEnterEvent( QDragEnterEvent * _dee )
{
if( StringPairDrag::processDragEnterEvent( _dee,
QString( "samplefile" ) ) == false )
{
_dee->ignore();
}
}
void Graph::modelChanged()
{
auto gModel = castModel<graphModel>();
QObject::connect( gModel, SIGNAL(samplesChanged(int,int)),
this, SLOT(updateGraph(int,int)));
QObject::connect( gModel, SIGNAL(lengthChanged()),
this, SLOT(updateGraph()));
}
void Graph::updateGraph( int _startPos, int _endPos )
{
// Can optimize by only drawing changed position
update();
}
void Graph::updateGraph()
{
updateGraph( 0, model()->length() - 1 );
}
} // namespace gui
graphModel::graphModel( float _min, float _max, int _length,
Model* _parent, bool _default_constructed, float _step ) :
Model( _parent, tr( "Graph" ), _default_constructed ),
m_samples( _length ),
m_length( _length ),
m_minValue( _min ),
m_maxValue( _max ),
m_step( _step )
{
}
void graphModel::setRange( float _min, float _max )
{
if( _min != m_minValue || _max != m_maxValue )
{
m_minValue = _min;
m_maxValue = _max;
if( !m_samples.isEmpty() )
{
// Trim existing values
for( int i=0; i < length(); i++ )
{
m_samples[i] = fmaxf( _min, fminf( m_samples[i], _max ) );
}
}
emit rangeChanged();
}
}
void graphModel::setLength( int _length )
{
if( _length != m_length )
{
m_length = _length;
if( m_samples.size() < m_length )
{
m_samples.resize( m_length );
}
emit lengthChanged();
}
}
void graphModel::setSampleAt( int x, float val )
{
drawSampleAt( x, val );
emit samplesChanged( x, x );
}
void graphModel::setSamples( const float * _samples )
{
std::copy( _samples, _samples + length(), m_samples.begin());
emit samplesChanged( 0, length()-1 );
}
void graphModel::setWaveToSine()
{
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::sinSample(
i / static_cast<float>( length() ) );
}
emit samplesChanged( 0, length() - 1 );
};
void graphModel::setWaveToTriangle()
{
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::triangleSample(
i / static_cast<float>( length() ) );
}
emit samplesChanged( 0, length() - 1 );
};
void graphModel::setWaveToSaw()
{
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::sawSample(
i / static_cast<float>( length() ) );
}
emit samplesChanged( 0, length() - 1 );
};
void graphModel::setWaveToSquare()
{
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::squareSample(
i / static_cast<float>( length() ) );
}
emit samplesChanged( 0, length() - 1 );
};
void graphModel::setWaveToNoise()
{
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::noiseSample(
i / static_cast<float>( length() ) );
}
emit samplesChanged( 0, length() - 1 );
};
QString graphModel::setWaveToUser()
{
QString fileName = gui::SampleLoader::openWaveformFile();
if( fileName.isEmpty() == false )
{
auto sampleBuffer = gui::SampleLoader::createBufferFromFile(fileName);
for( int i = 0; i < length(); i++ )
{
m_samples[i] = Oscillator::userWaveSample(sampleBuffer.get(), i / static_cast<float>(length()));
}
}
emit samplesChanged( 0, length() - 1 );
return fileName;
};
void graphModel::smooth()
{
// store values in temporary array
QVector<float> temp = m_samples;
// Smoothing
m_samples[0] = ( temp[length()-1] + ( temp[0] * 2 ) + temp[1] ) * 0.25f;
for ( int i=1; i < ( length()-1 ); i++ )
{
m_samples[i] = ( temp[i-1] + ( temp[i] * 2 ) + temp[i+1] ) * 0.25f;
}
m_samples[length()-1] = ( temp[length()-2] + ( temp[length()-1] * 2 ) + temp[0] ) * 0.25f;
emit samplesChanged(0, length()-1);
}
void graphModel::smoothNonCyclic()
{
// store values in temporary array
QVector<float> temp = m_samples;
// Smoothing
//m_samples[0] = ( ( temp[0] * 3 ) + temp[1] ) * 0.25f;
for ( int i=1; i < ( length()-1 ); i++ )
{
m_samples[i] = ( temp[i-1] + ( temp[i] * 2 ) + temp[i+1] ) * 0.25f;
}
//m_samples[length()-1] = ( temp[length()-2] + ( temp[length()-1] * 3 ) ) * 0.25f;
emit samplesChanged(0, length()-1);
}
void graphModel::convolve(const float *convolution,
const int convolutionLength, const int centerOffset)
{
// store values in temporary array
QVector<float> temp = m_samples;
const int graphLength = length();
// make a cyclic convolution
for ( int i = 0; i < graphLength; i++ )
{
float sum = 0.0f;
for ( int j = 0; j < convolutionLength; j++ )
{
sum += convolution[j] * temp[( i + j ) % graphLength];
}
m_samples[( i + centerOffset ) % graphLength] = sum;
}
emit samplesChanged(0, graphLength - 1);
}
void graphModel::normalize()
{
float max = 0.0001f;
float avg = 0.0f;
// first correct dc offset by normalizing to average
for( int i = 0; i < length(); i++ )
avg += m_samples[i];
avg /= length();
for( int i = 0; i < length(); i++ )
m_samples[i] -= avg;
// then maximize
for( int i = 0; i < length(); i++ )
max = qMax( max, qAbs( m_samples[i] ) );
for( int i = 0; i < length(); i++ )
m_samples[i] = qBound( m_minValue, m_samples[i] / max, m_maxValue );
// signal changes if any
if( max != 1.0f || avg != 0.0f )
emit samplesChanged( 0, length()-1 );
}
void graphModel::invert()
{
const float range = m_maxValue - m_minValue;
for( int i = 0; i < length(); i++ )
m_samples[i] = m_minValue + ( range - ( m_samples[i] - m_minValue ) );
emit samplesChanged( 0, length()-1 );
}
void graphModel::shiftPhase( int _deg )
{
// calculate offset in samples
const int offset = ( _deg * length() ) / 360; //multiply first because integers
// store values in temporary array
QVector<float> temp = m_samples;
// shift phase
for( int i = 0; i < length(); i++ )
{
int o = ( i + offset ) % length();
while( o < 0 ) o += length();
m_samples[i] = temp[o];
}
emit samplesChanged( 0, length()-1 );
}
void graphModel::clear()
{
const int graph_length = length();
for( int i = 0; i < graph_length; i++ )
m_samples[i] = 0;
emit samplesChanged( 0, graph_length - 1 );
}
// Clear any part of the graph that isn't displayed
void graphModel::clearInvisible()
{
const int graph_length = length();
const int full_graph_length = m_samples.size();
for( int i = graph_length; i < full_graph_length; i++ )
m_samples[i] = 0;
emit samplesChanged( graph_length, full_graph_length - 1 );
}
void graphModel::drawSampleAt( int x, float val )
{
//snap to the grid
val -= ( m_step != 0.0 ) ? fmod( val, m_step ) * m_step : 0;
// boundary crop
x = qMax( 0, qMin( length()-1, x ) );
val = qMax( minValue(), qMin( maxValue(), val ) );
// change sample shape
m_samples[x] = val;
}
} // namespace lmms
| 16,159
|
C++
|
.cpp
| 577
| 25.253033
| 123
| 0.631412
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,969
|
TextFloat.cpp
|
LMMS_lmms/src/gui/widgets/TextFloat.cpp
|
/*
* TextFloat.cpp - class textFloat, a floating text-label
*
* Copyright (c) 2005-2010 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TextFloat.h"
#include <QTimer>
#include <QPainter>
#include <QStyleOption>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include "GuiApplication.h"
#include "MainWindow.h"
namespace lmms::gui
{
TextFloat::TextFloat() :
TextFloat("", "", QPixmap())
{
}
TextFloat::TextFloat(const QString & title, const QString & text, const QPixmap & pixmap) :
QWidget(getGUI()->mainWindow(), Qt::ToolTip)
{
QHBoxLayout * mainLayout = new QHBoxLayout();
setLayout(mainLayout);
// Create the label that displays the pixmap
m_pixmapLabel = new QLabel(this);
mainLayout->addWidget(m_pixmapLabel);
// Create the widget that displays the title and the text
QWidget * titleAndTextWidget = new QWidget(this);
QVBoxLayout * titleAndTextLayout = new QVBoxLayout();
titleAndTextWidget->setLayout(titleAndTextLayout);
m_titleLabel = new QLabel(titleAndTextWidget);
m_titleLabel->setStyleSheet("font-weight: bold;");
titleAndTextLayout->addWidget(m_titleLabel);
m_textLabel = new QLabel(titleAndTextWidget);
titleAndTextLayout->addWidget(m_textLabel);
mainLayout->addWidget(titleAndTextWidget);
// Call the setters so that the hidden state is updated
setTitle(title);
setText(text);
setPixmap(pixmap);
}
void TextFloat::setTitle(const QString & title)
{
m_titleLabel->setText(title);
m_titleLabel->setHidden(title.isEmpty());
}
void TextFloat::setText(const QString & text)
{
m_textLabel->setText(text);
m_textLabel->setHidden(text.isEmpty());
}
void TextFloat::setPixmap(const QPixmap & pixmap)
{
m_pixmapLabel->setPixmap(pixmap);
m_pixmapLabel->setHidden(pixmap.isNull());
}
void TextFloat::setVisibilityTimeOut(int msecs)
{
QTimer::singleShot(msecs, this, SLOT(hide()));
show();
}
TextFloat * TextFloat::displayMessage(const QString & title,
const QString & msg,
const QPixmap & pixmap,
int timeout, QWidget * parent)
{
auto tf = new TextFloat(title, msg, pixmap);
// Show the widget so that the correct height is calculated in the code that follows
tf->show();
if(parent != nullptr)
{
tf->moveGlobal(parent, QPoint(parent->width() + 2, 0));
}
else
{
// If no parent is given move the window to the lower left area of the main window
QWidget * mw = getGUI()->mainWindow();
tf->moveGlobal(mw, QPoint(32, mw->height() - tf->height() - 8));
}
if (timeout > 0)
{
tf->setAttribute(Qt::WA_DeleteOnClose, true);
QTimer::singleShot(timeout, tf, SLOT(close()));
}
return tf;
}
void TextFloat::mousePressEvent(QMouseEvent *)
{
close();
}
} // namespace lmms::gui
| 3,486
|
C++
|
.cpp
| 111
| 29.36036
| 91
| 0.750224
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,970
|
MidiPortMenu.cpp
|
LMMS_lmms/src/gui/menus/MidiPortMenu.cpp
|
/*
* MidiPortMenu.cpp - a menu for subscribing a MidiPort to several external
* MIDI ports
*
* Copyright (c) 2008-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "MidiPortMenu.h"
namespace lmms::gui
{
MidiPortMenu::MidiPortMenu( MidiPort::Mode _mode ) :
ModelView( nullptr, this ),
m_mode( _mode )
{
connect( this, SIGNAL(triggered(QAction*)),
this, SLOT(activatedPort(QAction*)));
}
void MidiPortMenu::modelChanged()
{
auto mp = castModel<MidiPort>();
if( m_mode == MidiPort::Mode::Input )
{
connect( mp, SIGNAL(readablePortsChanged()),
this, SLOT(updateMenu()));
}
else if( m_mode == MidiPort::Mode::Output )
{
connect( mp, SIGNAL(writablePortsChanged()),
this, SLOT(updateMenu()));
}
updateMenu();
}
void MidiPortMenu::activatedPort( QAction * _item )
{
if( m_mode == MidiPort::Mode::Input )
{
castModel<MidiPort>()->subscribeReadablePort( _item->text(),
_item->isChecked() );
}
else if( m_mode == MidiPort::Mode::Output )
{
castModel<MidiPort>()->subscribeWritablePort( _item->text(),
_item->isChecked() );
}
}
void MidiPortMenu::updateMenu()
{
auto mp = castModel<MidiPort>();
const MidiPort::Map & map = ( m_mode == MidiPort::Mode::Input ) ?
mp->readablePorts() : mp->writablePorts();
clear();
for( MidiPort::Map::ConstIterator it = map.begin();
it != map.end(); ++it )
{
QAction * a = addAction( it.key() );
a->setCheckable( true );
a->setChecked( it.value() );
}
}
} // namespace lmms::gui
| 2,328
|
C++
|
.cpp
| 77
| 27.714286
| 77
| 0.697309
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,971
|
TemplatesMenu.cpp
|
LMMS_lmms/src/gui/menus/TemplatesMenu.cpp
|
#include "TemplatesMenu.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "Song.h"
#include "embed.h"
#include "GuiApplication.h"
#include "MainWindow.h"
namespace lmms::gui
{
TemplatesMenu::TemplatesMenu(QWidget *parent) :
QMenu(tr("New from template"), parent)
{
setIcon(embed::getIconPixmap("project_new"));
connect( this, SIGNAL(aboutToShow()), SLOT(fillTemplatesMenu()));
connect( this, SIGNAL(triggered(QAction*)),
SLOT(createNewProjectFromTemplate(QAction*)));
}
void TemplatesMenu::createNewProjectFromTemplate(QAction * _action)
{
if( getGUI()->mainWindow()->mayChangeProject(true) )
{
const QString& templateFilePath = _action->data().toString();
Engine::getSong()->createNewProjectFromTemplate(templateFilePath);
}
}
void TemplatesMenu::fillTemplatesMenu()
{
clear();
addTemplatesFromDir(ConfigManager::inst()->userTemplateDir());
addTemplatesFromDir(ConfigManager::inst()->factoryProjectsDir() + "templates");
}
void TemplatesMenu::addTemplatesFromDir( const QDir& dir ) {
QFileInfoList templates = dir.entryInfoList( QStringList( "*.mpt" ),
QDir::Files | QDir::Readable );
if (!templates.empty() && !actions().isEmpty())
{
addSeparator();
}
auto projectFileIcon = embed::getIconPixmap( "project_file" );
for(const QFileInfo& templateFile : templates)
{
auto action = addAction(projectFileIcon,
templateFile.completeBaseName().replace("&", "&&"));
action->setData(templateFile.absoluteFilePath());
#ifdef LMMS_BUILD_APPLE
action->setIconVisibleInMenu(false); // QTBUG-44565 workaround
action->setIconVisibleInMenu(true);
#endif
}
}
} // namespace lmms::gui
| 1,643
|
C++
|
.cpp
| 51
| 29.941176
| 80
| 0.761175
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,972
|
RecentProjectsMenu.cpp
|
LMMS_lmms/src/gui/menus/RecentProjectsMenu.cpp
|
#include "RecentProjectsMenu.h"
#include <QFileInfo>
#include "ConfigManager.h"
#include "Engine.h"
#include "Song.h"
#include "embed.h"
#include "GuiApplication.h"
#include "MainWindow.h"
namespace lmms::gui
{
RecentProjectsMenu::RecentProjectsMenu(QWidget *parent) :
QMenu(tr( "&Recently Opened Projects" ), parent)
{
setIcon(embed::getIconPixmap( "project_open_recent" ));
connect( this, SIGNAL(aboutToShow()),
this, SLOT(fillMenu()));
connect( this, SIGNAL(triggered(QAction*)),
this, SLOT(openProject(QAction*)));
}
void RecentProjectsMenu::fillMenu()
{
clear();
QStringList rup = ConfigManager::inst()->recentlyOpenedProjects();
auto projectFileIcon = embed::getIconPixmap( "project_file" );
// The file history goes 50 deep but we only show the 15
// most recent ones that we can open and omit .mpt files.
int shownInMenu = 0;
for(QString& fileName : rup)
{
QFileInfo recentFile(fileName);
if (!recentFile.exists() ||
fileName == ConfigManager::inst()->recoveryFile() )
{
continue;
}
if( recentFile.suffix().toLower() == "mpt" )
{
continue;
}
addAction(projectFileIcon, fileName.replace("&", "&&") );
#ifdef LMMS_BUILD_APPLE
actions().last()->setIconVisibleInMenu(false); // QTBUG-44565 workaround
actions().last()->setIconVisibleInMenu(true);
#endif
shownInMenu++;
if( shownInMenu >= 15 )
{
break;
}
}
}
void RecentProjectsMenu::openProject(QAction * _action )
{
auto mainWindow = getGUI()->mainWindow();
if (mainWindow->mayChangeProject(true))
{
const QString f = _action->text().replace("&&", "&");
mainWindow->setCursor( Qt::WaitCursor );
Engine::getSong()->loadProject( f );
mainWindow->setCursor( Qt::ArrowCursor );
}
}
} // namespace lmms::gui
| 1,752
|
C++
|
.cpp
| 63
| 25.31746
| 74
| 0.717026
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,973
|
AutomationTrackView.cpp
|
LMMS_lmms/src/gui/tracks/AutomationTrackView.cpp
|
/*
* AutomationTrackView.cpp
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AutomationTrackView.h"
#include "AutomationClip.h"
#include "AutomationTrack.h"
#include "embed.h"
#include "Engine.h"
#include "ProjectJournal.h"
#include "StringPairDrag.h"
#include "TrackContainerView.h"
#include "TrackLabelButton.h"
namespace lmms::gui
{
AutomationTrackView::AutomationTrackView( AutomationTrack * _at, TrackContainerView* tcv ) :
TrackView( _at, tcv )
{
setFixedHeight( 32 );
auto tlb = new TrackLabelButton(this, getTrackSettingsWidget());
tlb->setIcon(embed::getIconPixmap("automation_track"));
tlb->move(3, 1);
tlb->show();
setModel(_at);
}
void AutomationTrackView::dragEnterEvent( QDragEnterEvent * _dee )
{
StringPairDrag::processDragEnterEvent( _dee, "automatable_model" );
}
void AutomationTrackView::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString val = StringPairDrag::decodeValue( _de );
if( type == "automatable_model" )
{
auto mod = dynamic_cast<AutomatableModel*>(Engine::projectJournal()->journallingObject(val.toInt()));
if( mod != nullptr )
{
TimePos pos = TimePos( trackContainerView()->
currentPosition() +
( _de->pos().x() -
getTrackContentWidget()->x() ) *
TimePos::ticksPerBar() /
static_cast<int>( trackContainerView()->pixelsPerBar() ) )
.toAbsoluteBar();
if( pos.getTicks() < 0 )
{
pos.setTicks( 0 );
}
Clip * clip = getTrack()->createClip( pos );
auto autoClip = dynamic_cast<AutomationClip*>(clip);
autoClip->addObject( mod );
}
}
update();
}
} // namespace lmms::gui
| 2,555
|
C++
|
.cpp
| 77
| 30.571429
| 103
| 0.727679
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,974
|
PatternTrackView.cpp
|
LMMS_lmms/src/gui/tracks/PatternTrackView.cpp
|
/*
* PatternTrackView.cpp
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PatternTrackView.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "PatternEditor.h"
#include "PatternStore.h"
#include "PatternTrack.h"
#include "TrackLabelButton.h"
namespace lmms::gui
{
PatternTrackView::PatternTrackView(PatternTrack* pt, TrackContainerView* tcv) :
TrackView(pt, tcv),
m_patternTrack(pt)
{
setFixedHeight( 32 );
// drag'n'drop with pattern tracks only causes troubles (and makes no sense too), so disable it
setAcceptDrops( false );
m_trackLabel = new TrackLabelButton( this, getTrackSettingsWidget() );
m_trackLabel->setIcon( embed::getIconPixmap("pattern_track"));
m_trackLabel->move( 3, 1 );
m_trackLabel->show();
connect( m_trackLabel, SIGNAL(clicked(bool)),
this, SLOT(clickedTrackLabel()));
setModel(pt);
}
PatternTrackView::~PatternTrackView()
{
getGUI()->patternEditor()->m_editor->removeViewsForPattern(PatternTrack::s_infoMap[m_patternTrack]);
}
bool PatternTrackView::close()
{
getGUI()->patternEditor()->m_editor->removeViewsForPattern(PatternTrack::s_infoMap[m_patternTrack]);
return TrackView::close();
}
void PatternTrackView::clickedTrackLabel()
{
Engine::patternStore()->setCurrentPattern(m_patternTrack->patternIndex());
getGUI()->mainWindow()->togglePatternEditorWin(true);
}
} // namespace lmms::gui
| 2,225
|
C++
|
.cpp
| 63
| 33.349206
| 101
| 0.767507
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,975
|
TrackView.cpp
|
LMMS_lmms/src/gui/tracks/TrackView.cpp
|
/*
* TrackView.cpp - implementation of TrackView class
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackView.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QStyleOption>
#include <QtGlobal>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "DataFile.h"
#include "Engine.h"
#include "FadeButton.h"
#include "PixmapButton.h"
#include "StringPairDrag.h"
#include "Track.h"
#include "TrackGrip.h"
#include "TrackContainerView.h"
#include "ClipView.h"
namespace lmms::gui
{
/*! \brief Create a new track View.
*
* The track View is handles the actual display of the track, including
* displaying its various widgets and the track segments.
*
* \param track The track to display.
* \param tcv The track Container View for us to be displayed in.
* \todo Is my description of these properties correct?
*/
TrackView::TrackView( Track * track, TrackContainerView * tcv ) :
QWidget( tcv->contentWidget() ), /*!< The Track Container View's content widget. */
ModelView( nullptr, this ), /*!< The model view of this track */
m_track( track ), /*!< The track we're displaying */
m_trackContainerView( tcv ), /*!< The track Container View we're displayed in */
m_trackOperationsWidget( this ), /*!< Our trackOperationsWidget */
m_trackSettingsWidget( this ), /*!< Our trackSettingsWidget */
m_trackContentWidget( this ), /*!< Our trackContentWidget */
m_action( Action::None ) /*!< The action we're currently performing */
{
setAutoFillBackground( true );
QPalette pal;
pal.setColor( backgroundRole(), QColor( 32, 36, 40 ) );
setPalette( pal );
m_trackSettingsWidget.setAutoFillBackground( true );
auto layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing( 0 );
layout->addWidget( &m_trackOperationsWidget );
layout->addWidget( &m_trackSettingsWidget );
layout->addWidget( &m_trackContentWidget, 1 );
setFixedHeight( m_track->getHeight() );
resizeEvent( nullptr );
setAcceptDrops( true );
setAttribute( Qt::WA_DeleteOnClose, true );
connect( m_track, SIGNAL(destroyedTrack()), this, SLOT(close()));
connect( m_track,
SIGNAL(clipAdded(lmms::Clip*)),
this, SLOT(createClipView(lmms::Clip*)),
Qt::QueuedConnection );
connect( &m_track->m_mutedModel, SIGNAL(dataChanged()),
&m_trackContentWidget, SLOT(update()));
connect(&m_track->m_mutedModel, SIGNAL(dataChanged()),
this, SLOT(muteChanged()));
connect( &m_track->m_soloModel, SIGNAL(dataChanged()),
m_track, SLOT(toggleSolo()), Qt::DirectConnection );
auto trackGrip = m_trackOperationsWidget.getTrackGrip();
connect(trackGrip, &TrackGrip::grabbed, this, &TrackView::onTrackGripGrabbed);
connect(trackGrip, &TrackGrip::released, this, &TrackView::onTrackGripReleased);
// create views for already existing clips
for (const auto& clip : m_track->m_clips)
{
createClipView(clip);
}
m_trackContainerView->addTrackView( this );
}
/*! \brief Resize this track View.
*
* \param re the Resize Event to handle.
*/
void TrackView::resizeEvent( QResizeEvent * re )
{
if( ConfigManager::inst()->value( "ui",
"compacttrackbuttons" ).toInt() )
{
m_trackOperationsWidget.setFixedSize( TRACK_OP_WIDTH_COMPACT, height() - 1 );
m_trackSettingsWidget.setFixedSize( DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT, height() - 1 );
}
else
{
m_trackOperationsWidget.setFixedSize( TRACK_OP_WIDTH, height() - 1 );
m_trackSettingsWidget.setFixedSize( DEFAULT_SETTINGS_WIDGET_WIDTH, height() - 1 );
}
m_trackContentWidget.setFixedHeight( height() );
}
/*! \brief Update this track View and all its content objects.
*
*/
void TrackView::update()
{
m_trackContentWidget.update();
if( !m_trackContainerView->fixedClips() )
{
m_trackContentWidget.changePosition();
}
QWidget::update();
}
/*! \brief Create a menu for assigning/creating channels for this track.
*
*/
QMenu * TrackView::createMixerMenu(QString title, QString newMixerLabel)
{
Q_UNUSED(title)
Q_UNUSED(newMixerLabel)
return nullptr;
}
/*! \brief Close this track View.
*
*/
bool TrackView::close()
{
m_trackContainerView->removeTrackView( this );
return QWidget::close();
}
/*! \brief Register that the model of this track View has changed.
*
*/
void TrackView::modelChanged()
{
m_track = castModel<Track>();
Q_ASSERT( m_track != nullptr );
connect( m_track, SIGNAL(destroyedTrack()), this, SLOT(close()));
m_trackOperationsWidget.m_muteBtn->setModel( &m_track->m_mutedModel );
m_trackOperationsWidget.m_soloBtn->setModel( &m_track->m_soloModel );
ModelView::modelChanged();
setFixedHeight( m_track->getHeight() );
}
/*! \brief Start a drag event on this track View.
*
* \param dee the DragEnterEvent to start.
*/
void TrackView::dragEnterEvent( QDragEnterEvent * dee )
{
StringPairDrag::processDragEnterEvent( dee, "track_" +
QString::number( static_cast<int>(m_track->type()) ) );
}
/*! \brief Accept a drop event on this track View.
*
* We only accept drop events that are of the same type as this track.
* If so, we decode the data from the drop event by just feeding it
* back into the engine as a state.
*
* \param de the DropEvent to handle.
*/
void TrackView::dropEvent( QDropEvent * de )
{
QString type = StringPairDrag::decodeKey( de );
QString value = StringPairDrag::decodeValue( de );
if( type == ( "track_" + QString::number( static_cast<int>(m_track->type()) ) ) )
{
// value contains our XML-data so simply create a
// DataFile which does the rest for us...
DataFile dataFile( value.toUtf8() );
Engine::audioEngine()->requestChangeInModel();
m_track->restoreState( dataFile.content().firstChild().toElement() );
Engine::audioEngine()->doneChangeInModel();
de->accept();
}
}
/*! \brief Handle a mouse press event on this track View.
*
* If this track container supports rubber band selection, let the
* widget handle that and don't bother with any other handling.
*
* If the left mouse button is pressed, we handle two things. If
* SHIFT is pressed, then we resize vertically. Otherwise we start
* the process of moving this track to a new position.
*
* Otherwise we let the widget handle the mouse event as normal.
*
* \param me the MouseEvent to handle.
*/
void TrackView::mousePressEvent( QMouseEvent * me )
{
// If previously dragged too small, restore on shift-leftclick
if( height() < DEFAULT_TRACK_HEIGHT &&
me->modifiers() & Qt::ShiftModifier &&
me->button() == Qt::LeftButton )
{
setFixedHeight( DEFAULT_TRACK_HEIGHT );
m_track->setHeight( DEFAULT_TRACK_HEIGHT );
}
int widgetTotal = ConfigManager::inst()->value( "ui",
"compacttrackbuttons" ).toInt()==1 ?
DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT + TRACK_OP_WIDTH_COMPACT :
DEFAULT_SETTINGS_WIDGET_WIDTH + TRACK_OP_WIDTH;
if( m_trackContainerView->allowRubberband() == true && me->x() > widgetTotal )
{
QWidget::mousePressEvent( me );
}
else if( me->button() == Qt::LeftButton )
{
if( me->modifiers() & Qt::ShiftModifier )
{
m_action = Action::Resize;
QCursor::setPos( mapToGlobal( QPoint( me->x(),
height() ) ) );
QCursor c( Qt::SizeVerCursor);
QApplication::setOverrideCursor( c );
}
me->accept();
}
else
{
QWidget::mousePressEvent( me );
}
}
/*! \brief Handle a mouse move event on this track View.
*
* If this track container supports rubber band selection, let the
* widget handle that and don't bother with any other handling.
*
* Otherwise if we've started the move process (from mousePressEvent())
* then move ourselves into that position, reordering the track list
* with moveTrackViewUp() and moveTrackViewDown() to suit. We make a
* note of this in the undo journal in case the user wants to undo this
* move.
*
* Likewise if we've started a resize process, handle this too, making
* sure that we never go below the minimum track height.
*
* \param me the MouseEvent to handle.
*/
void TrackView::mouseMoveEvent( QMouseEvent * me )
{
int widgetTotal = ConfigManager::inst()->value( "ui",
"compacttrackbuttons" ).toInt()==1 ?
DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT + TRACK_OP_WIDTH_COMPACT :
DEFAULT_SETTINGS_WIDGET_WIDTH + TRACK_OP_WIDTH;
if( m_trackContainerView->allowRubberband() == true && me->x() > widgetTotal )
{
QWidget::mouseMoveEvent( me );
}
else if( m_action == Action::Move )
{
// look which track-widget the mouse-cursor is over
const int yPos =
m_trackContainerView->contentWidget()->mapFromGlobal( me->globalPos() ).y();
const TrackView * trackAtY = m_trackContainerView->trackViewAt( yPos );
// debug code
// qDebug( "y position %d", yPos );
// a track-widget not equal to ourself?
if( trackAtY != nullptr && trackAtY != this )
{
// then move us up/down there!
if( me->y() < 0 )
{
m_trackContainerView->moveTrackViewUp( this );
}
else
{
m_trackContainerView->moveTrackViewDown( this );
}
}
}
else if( m_action == Action::Resize )
{
resizeToHeight(me->y());
}
if( height() < DEFAULT_TRACK_HEIGHT )
{
setToolTip(m_track->m_name);
}
}
/*! \brief Handle a mouse release event on this track View.
*
* \param me the MouseEvent to handle.
*/
void TrackView::mouseReleaseEvent( QMouseEvent * me )
{
m_action = Action::None;
while( QApplication::overrideCursor() != nullptr )
{
QApplication::restoreOverrideCursor();
}
m_trackOperationsWidget.update();
QWidget::mouseReleaseEvent( me );
}
void TrackView::wheelEvent(QWheelEvent* we)
{
// Note: we add the values because one of them will be 0. If the alt modifier
// is pressed x is non-zero and otherwise y.
const int deltaY = we->angleDelta().x() + we->angleDelta().y();
int const direction = deltaY < 0 ? -1 : 1;
auto const modKeys = we->modifiers();
int stepSize = modKeys == (Qt::ControlModifier | Qt::AltModifier) ? 1 : modKeys == (Qt::ShiftModifier | Qt::AltModifier) ? 5 : 0;
if (stepSize != 0)
{
resizeToHeight(height() + stepSize * direction);
we->accept();
}
}
/*! \brief Repaint this track View.
*
* \param pe the PaintEvent to start.
*/
void TrackView::paintEvent( QPaintEvent * pe )
{
QStyleOption opt;
opt.initFrom( this );
QPainter p( this );
style()->drawPrimitive( QStyle::PE_Widget, &opt, &p, this );
}
/*! \brief Create a Clip View in this track View.
*
* \param clip the Clip to create the view for.
* \todo is this a good description for what this method does?
*/
void TrackView::createClipView( Clip * clip )
{
ClipView * tv = clip->createView( this );
if( clip->getSelectViewOnCreate() == true )
{
tv->setSelected( true );
}
clip->selectViewOnCreate( false );
}
void TrackView::muteChanged()
{
FadeButton * indicator = getActivityIndicator();
if (indicator) { setIndicatorMute(indicator, m_track->m_mutedModel.value()); }
}
void TrackView::onTrackGripGrabbed()
{
m_action = Action::Move;
}
void TrackView::onTrackGripReleased()
{
m_action = Action::None;
}
void TrackView::setIndicatorMute(FadeButton* indicator, bool muted)
{
QPalette::ColorRole role = muted ? QPalette::Highlight : QPalette::BrightText;
indicator->setActiveColor(QApplication::palette().color(QPalette::Active, role));
}
void TrackView::resizeToHeight(int h)
{
setFixedHeight(qMax<int>(h, MINIMAL_TRACK_HEIGHT));
m_trackContainerView->realignTracks();
m_track->setHeight(height());
}
} // namespace lmms::gui
| 12,318
|
C++
|
.cpp
| 374
| 30.620321
| 130
| 0.719001
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,976
|
InstrumentTrackView.cpp
|
LMMS_lmms/src/gui/tracks/InstrumentTrackView.cpp
|
/*
* InstrumentTrackView.cpp - implementation of InstrumentTrackView class
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "InstrumentTrackView.h"
#include <QAction>
#include <QApplication>
#include <QDragEnterEvent>
#include <QMdiArea>
#include <QMdiSubWindow>
#include <QMenu>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "FadeButton.h"
#include "Knob.h"
#include "MidiCCRackView.h"
#include "Mixer.h"
#include "MixerView.h"
#include "GuiApplication.h"
#include "Instrument.h"
#include "InstrumentTrackWindow.h"
#include "MainWindow.h"
#include "MidiClient.h"
#include "MidiPortMenu.h"
#include "TrackLabelButton.h"
namespace lmms::gui
{
InstrumentTrackView::InstrumentTrackView( InstrumentTrack * _it, TrackContainerView* tcv ) :
TrackView( _it, tcv ),
m_window( nullptr ),
m_lastPos( -1, -1 )
{
setAcceptDrops( true );
setFixedHeight( 32 );
m_tlb = new TrackLabelButton( this, getTrackSettingsWidget() );
m_tlb->setCheckable( true );
m_tlb->setIcon(determinePixmap(_it));
m_tlb->show();
connect( m_tlb, SIGNAL(toggled(bool)),
this, SLOT(toggleInstrumentWindow(bool)));
connect( _it, SIGNAL(nameChanged()),
m_tlb, SLOT(update()));
connect(ConfigManager::inst(), SIGNAL(valueChanged(QString,QString,QString)),
this, SLOT(handleConfigChange(QString,QString,QString)));
m_mixerChannelNumber = new MixerChannelLcdSpinBox(2, getTrackSettingsWidget(), tr("Mixer channel"), this);
m_mixerChannelNumber->show();
m_volumeKnob = new Knob( KnobType::Small17, getTrackSettingsWidget(),
tr( "Volume" ) );
m_volumeKnob->setVolumeKnob( true );
m_volumeKnob->setModel( &_it->m_volumeModel );
m_volumeKnob->setHintText( tr( "Volume:" ), "%" );
m_volumeKnob->setLabel( tr( "VOL" ) );
m_volumeKnob->show();
m_panningKnob = new Knob( KnobType::Small17, getTrackSettingsWidget(),
tr( "Panning" ) );
m_panningKnob->setModel( &_it->m_panningModel );
m_panningKnob->setHintText(tr("Panning:"), "%");
m_panningKnob->setLabel( tr( "PAN" ) );
m_panningKnob->show();
m_midiMenu = new QMenu( tr( "MIDI" ), this );
// sequenced MIDI?
if( !Engine::audioEngine()->midiClient()->isRaw() )
{
_it->m_midiPort.m_readablePortsMenu = new MidiPortMenu(
MidiPort::Mode::Input );
_it->m_midiPort.m_writablePortsMenu = new MidiPortMenu(
MidiPort::Mode::Output );
_it->m_midiPort.m_readablePortsMenu->setModel(
&_it->m_midiPort );
_it->m_midiPort.m_writablePortsMenu->setModel(
&_it->m_midiPort );
m_midiInputAction = m_midiMenu->addMenu(
_it->m_midiPort.m_readablePortsMenu );
m_midiOutputAction = m_midiMenu->addMenu(
_it->m_midiPort.m_writablePortsMenu );
}
else
{
m_midiInputAction = m_midiMenu->addAction( "" );
m_midiOutputAction = m_midiMenu->addAction( "" );
m_midiInputAction->setCheckable( true );
m_midiOutputAction->setCheckable( true );
connect( m_midiInputAction, SIGNAL(changed()), this,
SLOT(midiInSelected()));
connect( m_midiOutputAction, SIGNAL(changed()), this,
SLOT(midiOutSelected()));
connect( &_it->m_midiPort, SIGNAL(modeChanged()),
this, SLOT(midiConfigChanged()));
}
m_midiInputAction->setText( tr( "Input" ) );
m_midiOutputAction->setText( tr( "Output" ) );
QAction *midiRackAction = m_midiMenu->addAction(tr("Open/Close MIDI CC Rack"));
midiRackAction->setIcon(embed::getIconPixmap("midi_cc_rack"));
connect(midiRackAction, SIGNAL(triggered()),
this, SLOT(toggleMidiCCRack()));
m_activityIndicator = new FadeButton( QApplication::palette().color( QPalette::Active,
QPalette::Window),
QApplication::palette().color( QPalette::Active,
QPalette::BrightText ),
QApplication::palette().color( QPalette::Active,
QPalette::BrightText).darker(),
getTrackSettingsWidget() );
m_activityIndicator->setFixedSize(8, 28);
m_activityIndicator->show();
auto masterLayout = new QVBoxLayout(getTrackSettingsWidget());
masterLayout->setContentsMargins(0, 1, 0, 0);
auto layout = new QHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(m_tlb);
layout->addWidget(m_mixerChannelNumber);
layout->addWidget(m_activityIndicator);
layout->addWidget(m_volumeKnob);
layout->addWidget(m_panningKnob);
masterLayout->addLayout(layout);
masterLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
connect( m_activityIndicator, SIGNAL(pressed()),
this, SLOT(activityIndicatorPressed()));
connect( m_activityIndicator, SIGNAL(released()),
this, SLOT(activityIndicatorReleased()));
connect( _it, SIGNAL(newNote()),
m_activityIndicator, SLOT(activate()));
connect( _it, SIGNAL(endNote()),
m_activityIndicator, SLOT(noteEnd()));
setModel( _it );
}
InstrumentTrackView::~InstrumentTrackView()
{
delete m_window;
m_window = nullptr;
delete model()->m_midiPort.m_readablePortsMenu;
delete model()->m_midiPort.m_writablePortsMenu;
}
void InstrumentTrackView::toggleMidiCCRack()
{
// Lazy creation: midiCCRackView is only created when accessed the first time.
// this->model() returns pointer to the InstrumentTrack who owns this InstrumentTrackView.
if (!m_midiCCRackView)
{
m_midiCCRackView = std::unique_ptr<MidiCCRackView>(new MidiCCRackView(this->model()));
}
if (m_midiCCRackView->parentWidget()->isVisible())
{
m_midiCCRackView->parentWidget()->hide();
}
else
{
m_midiCCRackView->parentWidget()->show();
m_midiCCRackView->show();
}
}
InstrumentTrackWindow * InstrumentTrackView::topLevelInstrumentTrackWindow()
{
InstrumentTrackWindow * w = nullptr;
for( const QMdiSubWindow * sw :
getGUI()->mainWindow()->workspace()->subWindowList(
QMdiArea::ActivationHistoryOrder ) )
{
if( sw->isVisible() && sw->widget()->inherits( "lmms::gui::InstrumentTrackWindow" ) )
{
w = qobject_cast<InstrumentTrackWindow *>( sw->widget() );
}
}
return w;
}
/*! \brief Create and assign a new mixer Channel for this track */
void InstrumentTrackView::createMixerLine()
{
int channelIndex = getGUI()->mixerView()->addNewChannel();
auto channel = Engine::mixer()->mixerChannel(channelIndex);
channel->m_name = getTrack()->name();
channel->setColor(getTrack()->color());
assignMixerLine(channelIndex);
}
/*! \brief Assign a specific mixer Channel for this track */
void InstrumentTrackView::assignMixerLine(int channelIndex)
{
model()->mixerChannelModel()->setValue( channelIndex );
getGUI()->mixerView()->setCurrentMixerChannel(channelIndex);
}
InstrumentTrackWindow * InstrumentTrackView::getInstrumentTrackWindow()
{
if (!m_window)
{
m_window = new InstrumentTrackWindow(this);
}
return m_window;
}
void InstrumentTrackView::handleConfigChange(QString cls, QString attr, QString value)
{
// When one instrument track window mode is turned on,
// close windows except last opened one.
if (cls == "ui" && attr == "oneinstrumenttrackwindow" && value.toInt())
{
m_tlb->setChecked(m_window && m_window == topLevelInstrumentTrackWindow());
}
}
void InstrumentTrackView::modelChanged()
{
TrackView::modelChanged();
auto st = castModel<InstrumentTrack>();
m_mixerChannelNumber->setModel(&st->m_mixerChannelModel);
}
void InstrumentTrackView::dragEnterEvent( QDragEnterEvent * _dee )
{
InstrumentTrackWindow::dragEnterEventGeneric( _dee );
if( !_dee->isAccepted() )
{
TrackView::dragEnterEvent( _dee );
}
}
void InstrumentTrackView::dropEvent( QDropEvent * _de )
{
getInstrumentTrackWindow()->dropEvent( _de );
TrackView::dropEvent( _de );
}
void InstrumentTrackView::toggleInstrumentWindow( bool _on )
{
if (_on && ConfigManager::inst()->value("ui", "oneinstrumenttrackwindow").toInt())
{
if (topLevelInstrumentTrackWindow())
{
topLevelInstrumentTrackWindow()->m_itv->m_tlb->setChecked(false);
}
}
getInstrumentTrackWindow()->toggleVisibility( _on );
}
void InstrumentTrackView::activityIndicatorPressed()
{
model()->processInEvent( MidiEvent( MidiNoteOn, 0, DefaultKey, MidiDefaultVelocity ) );
}
void InstrumentTrackView::activityIndicatorReleased()
{
model()->processInEvent( MidiEvent( MidiNoteOff, 0, DefaultKey, 0 ) );
}
void InstrumentTrackView::midiInSelected()
{
if( model() )
{
model()->m_midiPort.setReadable( m_midiInputAction->isChecked() );
}
}
void InstrumentTrackView::midiOutSelected()
{
if( model() )
{
model()->m_midiPort.setWritable( m_midiOutputAction->isChecked() );
}
}
void InstrumentTrackView::midiConfigChanged()
{
m_midiInputAction->setChecked( model()->m_midiPort.isReadable() );
m_midiOutputAction->setChecked( model()->m_midiPort.isWritable() );
}
//FIXME: This is identical to SampleTrackView::createMixerMenu
QMenu * InstrumentTrackView::createMixerMenu(QString title, QString newMixerLabel)
{
int channelIndex = model()->mixerChannelModel()->value();
MixerChannel *mixerChannel = Engine::mixer()->mixerChannel( channelIndex );
// If title allows interpolation, pass channel index and name
if ( title.contains( "%2" ) )
{
title = title.arg( channelIndex ).arg( mixerChannel->m_name );
}
auto mixerMenu = new QMenu(title);
mixerMenu->addAction( newMixerLabel, this, SLOT(createMixerLine()));
mixerMenu->addSeparator();
for (int i = 0; i < Engine::mixer()->numChannels(); ++i)
{
MixerChannel * currentChannel = Engine::mixer()->mixerChannel( i );
if ( currentChannel != mixerChannel )
{
auto index = currentChannel->m_channelIndex;
QString label = tr( "%1: %2" ).arg( currentChannel->m_channelIndex ).arg( currentChannel->m_name );
mixerMenu->addAction(label, [this, index](){
assignMixerLine(index);
});
}
}
return mixerMenu;
}
QPixmap InstrumentTrackView::determinePixmap(InstrumentTrack* instrumentTrack)
{
if (instrumentTrack)
{
Instrument* instrument = instrumentTrack->instrument();
if (instrument && instrument->descriptor())
{
const PixmapLoader* pl = instrument->key().isValid()
? instrument->key().logo()
: instrument->descriptor()->logo;
if (pl)
{
return pl->pixmap();
}
}
}
return embed::getIconPixmap("instrument_track");
}
} // namespace lmms::gui
| 10,975
|
C++
|
.cpp
| 320
| 31.653125
| 107
| 0.737705
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,977
|
TrackContentWidget.cpp
|
LMMS_lmms/src/gui/tracks/TrackContentWidget.cpp
|
/*
* TrackContentWidget.cpp - implementation of TrackContentWidget class
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackContentWidget.h"
#include <QApplication>
#include <QContextMenuEvent>
#include <QMenu>
#include <QPainter>
#include "AutomationClip.h"
#include "Clipboard.h"
#include "DataFile.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "PatternEditor.h"
#include "PatternStore.h"
#include "Song.h"
#include "SongEditor.h"
#include "StringPairDrag.h"
#include "TrackContainerView.h"
#include "ClipView.h"
#include "TrackView.h"
namespace lmms::gui
{
/*! Alternate between a darker and a lighter background color every 4 bars
*/
const int BARS_PER_GROUP = 4;
/* Lines between bars will disappear if zoomed too far out (i.e
if there are less than 4 pixels between lines)*/
const int MIN_PIXELS_BETWEEN_LINES = 4;
/*! \brief Create a new trackContentWidget
*
* Creates a new track content widget for the given track.
* The content widget comprises the 'grip bar' and the 'tools' button
* for the track's context menu.
*
* \param parent The parent track.
*/
TrackContentWidget::TrackContentWidget( TrackView * parent ) :
QWidget( parent ),
m_trackView( parent ),
m_darkerColor( Qt::SolidPattern ),
m_lighterColor( Qt::SolidPattern ),
m_coarseGridColor( Qt::SolidPattern ),
m_fineGridColor( Qt::SolidPattern ),
m_horizontalColor( Qt::SolidPattern ),
m_embossColor( Qt::SolidPattern ),
m_coarseGridWidth(2),
m_fineGridWidth(1),
m_horizontalWidth(1),
m_embossWidth(0),
m_embossOffset(0)
{
setAcceptDrops( true );
connect( parent->trackContainerView(),
SIGNAL( positionChanged( const lmms::TimePos& ) ),
this, SLOT( changePosition( const lmms::TimePos& ) ) );
// Update background if snap size changes
connect(getGUI()->songEditor()->m_editor->snappingModel(), &Model::dataChanged,
this, &TrackContentWidget::updateBackground);
// Also update background if proportional snap is enabled/disabled
connect(getGUI()->songEditor()->m_editor, &SongEditor::proportionalSnapChanged,
this, &TrackContentWidget::updateBackground);
setStyle( QApplication::style() );
updateBackground();
}
void TrackContentWidget::updateBackground()
{
// use snapSize to determine number of lines to draw
float snapSize = getGUI()->songEditor()->m_editor->getSnapSize();
const TrackContainerView * tcv = m_trackView->trackContainerView();
// Assume even-pixels-per-bar. Makes sense, should be like this anyways
int ppb = static_cast<int>( tcv->pixelsPerBar() );
// Coarse grid appears every bar (less frequently if quantization > 1 bar)
float coarseGridResolution = (snapSize >= 1) ? snapSize : 1;
// Fine grid appears within bars
float fineGridResolution = snapSize;
// Increase fine grid resolution (size between lines) if it results in less than
// 4 pixels between each line to avoid cluttering
float pixelsBetweenLines = ppb * snapSize;
if (pixelsBetweenLines < MIN_PIXELS_BETWEEN_LINES) {
// Scale fineGridResolution so that there are enough pixels between lines
// scaleFactor should be a power of 2
int scaleFactor = 1 << static_cast<int>( std::ceil( std::log2( MIN_PIXELS_BETWEEN_LINES / pixelsBetweenLines ) ) );
fineGridResolution *= scaleFactor;
}
int w = ppb * BARS_PER_GROUP;
int h = height();
m_background = QPixmap( w * 2, height() );
QPainter pmp( &m_background );
pmp.fillRect( 0, 0, w, h, darkerColor() );
pmp.fillRect( w, 0, w , h, lighterColor() );
// draw lines
// draw fine grid
pmp.setPen( QPen( fineGridColor(), fineGridWidth() ) );
for (float x = 0; x < w * 2; x += ppb * fineGridResolution)
{
pmp.drawLine( QLineF( x, 0.0, x, h ) );
}
// draw coarse grid
pmp.setPen( QPen( coarseGridColor(), coarseGridWidth() ) );
for (float x = 0; x < w * 2; x += ppb * coarseGridResolution)
{
pmp.drawLine( QLineF( x, 0.0, x, h ) );
}
pmp.setPen( QPen( embossColor(), embossWidth() ) );
for (float x = (coarseGridWidth() + embossOffset()); x < w * 2; x += ppb * coarseGridResolution)
{
pmp.drawLine( QLineF( x, 0.0, x, h ) );
}
// draw horizontal line
pmp.setPen( QPen( horizontalColor(), horizontalWidth() ) );
pmp.drawLine(0, h - (horizontalWidth() + 1) / 2, w * 2, h - (horizontalWidth() + 1) / 2);
pmp.end();
// Force redraw
update();
}
/*! \brief Adds a ClipView to this widget.
*
* Adds a(nother) ClipView to our list of views. We also
* check that our position is up-to-date.
*
* \param clipv The ClipView to add.
*/
void TrackContentWidget::addClipView( ClipView * clipv )
{
Clip * clip = clipv->getClip();
m_clipViews.push_back( clipv );
clip->saveJournallingState( false );
changePosition();
clip->restoreJournallingState();
}
/*! \brief Removes the given ClipView from this widget.
*
* Removes the given ClipView from our list of views.
*
* \param clipv The ClipView to add.
*/
void TrackContentWidget::removeClipView( ClipView * clipv )
{
clipViewVector::iterator it = std::find( m_clipViews.begin(),
m_clipViews.end(),
clipv );
if( it != m_clipViews.end() )
{
m_clipViews.erase( it );
Engine::getSong()->setModified();
}
}
/*! \brief Update ourselves by updating all the ClipViews attached.
*
*/
void TrackContentWidget::update()
{
for (const auto& clipView : m_clipViews)
{
clipView->setFixedHeight(height() - 1);
clipView->update();
}
QWidget::update();
}
// resposible for moving track-content-widgets to appropriate position after
// change of visible viewport
/*! \brief Move the trackContentWidget to a new place in time
*
* \param newPos The MIDI time to move to.
*/
void TrackContentWidget::changePosition( const TimePos & newPos )
{
if (m_trackView->trackContainerView() == getGUI()->patternEditor()->m_editor)
{
const int curPattern = Engine::patternStore()->currentPattern();
setUpdatesEnabled( false );
// first show clip for current pattern...
for (const auto& clipView : m_clipViews)
{
if (clipView->getClip()->startPosition().getBar() == curPattern)
{
clipView->move(0, clipView->y());
clipView->raise();
clipView->show();
}
else { clipView->lower(); }
}
// ...then hide others to avoid flickering
for (const auto& clipView : m_clipViews)
{
if (clipView->getClip()->startPosition().getBar() != curPattern) { clipView->hide(); }
}
setUpdatesEnabled( true );
return;
}
TimePos pos = newPos;
if( pos < 0 )
{
pos = m_trackView->trackContainerView()->currentPosition();
}
const int begin = pos;
const int end = endPosition( pos );
const float ppb = m_trackView->trackContainerView()->pixelsPerBar();
setUpdatesEnabled( false );
for (const auto& clipView : m_clipViews)
{
Clip* clip = clipView->getClip();
clip->changeLength( clip->length() );
const int ts = clip->startPosition();
const int te = clip->endPosition()-3;
if( ( ts >= begin && ts <= end ) ||
( te >= begin && te <= end ) ||
( ts <= begin && te >= end ) )
{
clipView->move(static_cast<int>((ts - begin) * ppb / TimePos::ticksPerBar()), clipView->y());
if (!clipView->isVisible())
{
clipView->show();
}
}
else
{
clipView->move(-clipView->width() - 10, clipView->y());
}
}
setUpdatesEnabled( true );
// redraw background
updateBackground();
// update();
}
/*! \brief Return the position of the trackContentWidget in bars.
*
* \param mouseX the mouse's current X position in pixels.
*/
TimePos TrackContentWidget::getPosition( int mouseX )
{
TrackContainerView * tv = m_trackView->trackContainerView();
return TimePos( tv->currentPosition() +
mouseX *
TimePos::ticksPerBar() /
static_cast<int>( tv->pixelsPerBar() ) );
}
/*! \brief Respond to a drag enter event on the trackContentWidget
*
* \param dee the Drag Enter Event to respond to
*/
void TrackContentWidget::dragEnterEvent( QDragEnterEvent * dee )
{
TimePos clipPos = getPosition( dee->pos().x() );
if( canPasteSelection( clipPos, dee ) == false )
{
dee->ignore();
}
else
{
StringPairDrag::processDragEnterEvent( dee, "clip_" +
QString::number( static_cast<int>(getTrack()->type()) ) );
}
}
/*! \brief Returns whether a selection of Clips can be pasted into this
*
* \param clipPos the position of the Clip slot being pasted on
* \param de the DropEvent generated
*/
bool TrackContentWidget::canPasteSelection( TimePos clipPos, const QDropEvent* de )
{
const QMimeData * mimeData = de->mimeData();
// If the source of the DropEvent is the current instance of LMMS we don't allow pasting in the same bar
// if it's another instance of LMMS we allow it
return de->source()
? canPasteSelection( clipPos, mimeData )
: canPasteSelection( clipPos, mimeData, true );
}
// Overloaded method to make it possible to call this method without a Drag&Drop event
bool TrackContentWidget::canPasteSelection( TimePos clipPos, const QMimeData* md , bool allowSameBar )
{
// For decodeKey() and decodeValue()
using namespace Clipboard;
Track * t = getTrack();
QString type = decodeKey( md );
QString value = decodeValue( md );
// We can only paste into tracks of the same type
if (type != ("clip_" + QString::number(static_cast<int>(t->type()))))
{
return false;
}
// value contains XML needed to reconstruct Clips and place them
DataFile dataFile( value.toUtf8() );
// Extract the metadata and which Clip was grabbed
QDomElement metadata = dataFile.content().firstChildElement( "copyMetadata" );
QDomAttr clipPosAttr = metadata.attributeNode( "grabbedClipPos" );
TimePos grabbedClipPos = clipPosAttr.value().toInt();
TimePos grabbedClipBar = TimePos( grabbedClipPos.getBar(), 0 );
// Extract the track index that was originally clicked
QDomAttr tiAttr = metadata.attributeNode( "initialTrackIndex" );
const int initialTrackIndex = tiAttr.value().toInt();
// Get the current track's index
const TrackContainer::TrackList& tracks = t->trackContainer()->tracks();
const auto currentTrackIt = std::find(tracks.begin(), tracks.end(), t);
const int currentTrackIndex = currentTrackIt != tracks.end() ? std::distance(tracks.begin(), currentTrackIt) : -1;
// Don't paste if we're on the same bar and allowSameBar is false
auto sourceTrackContainerId = metadata.attributeNode( "trackContainerId" ).value().toUInt();
if( !allowSameBar && sourceTrackContainerId == t->trackContainer()->id() &&
clipPos == grabbedClipBar && currentTrackIndex == initialTrackIndex )
{
return false;
}
// Extract the clip data
QDomElement clipParent = dataFile.content().firstChildElement("clips");
QDomNodeList clipNodes = clipParent.childNodes();
// If we are pasting into the PatternEditor, only a single Clip is allowed to be pasted
// so we don't have the unexpected behavior of pasting on different PatternTracks
if (m_trackView->trackContainerView()->fixedClips() == true &&
clipNodes.length() > 1)
{
return false;
}
// Determine if all the Clips will land on a valid track
for( int i = 0; i < clipNodes.length(); i++ )
{
QDomElement clipElement = clipNodes.item( i ).toElement();
int trackIndex = clipElement.attributeNode( "trackIndex" ).value().toInt();
int finalTrackIndex = trackIndex + currentTrackIndex - initialTrackIndex;
// Track must be in TrackContainer's tracks
if (finalTrackIndex < 0 || static_cast<std::size_t>(finalTrackIndex) >= tracks.size())
{
return false;
}
// Track must be of the same type
auto startTrackType = static_cast<Track::Type>(clipElement.attributeNode("trackType").value().toInt());
Track * endTrack = tracks.at( finalTrackIndex );
if( startTrackType != endTrack->type() )
{
return false;
}
}
return true;
}
/*! \brief Pastes a selection of Clips onto the track
*
* \param clipPos the position of the Clip slot being pasted on
* \param de the DropEvent generated
*/
bool TrackContentWidget::pasteSelection( TimePos clipPos, QDropEvent * de )
{
const QMimeData * mimeData = de->mimeData();
if( canPasteSelection( clipPos, de ) == false )
{
return false;
}
// We set skipSafetyCheck to true because we already called canPasteSelection
return pasteSelection( clipPos, mimeData, true );
}
// Overloaded method so we can call it without a Drag&Drop event
bool TrackContentWidget::pasteSelection( TimePos clipPos, const QMimeData * md, bool skipSafetyCheck )
{
// For decodeKey() and decodeValue()
using namespace Clipboard;
// When canPasteSelection was already called before, skipSafetyCheck will skip this
if( !skipSafetyCheck && canPasteSelection( clipPos, md ) == false )
{
return false;
}
QString type = decodeKey( md );
QString value = decodeValue( md );
getTrack()->addJournalCheckPoint();
// value contains XML needed to reconstruct Clips and place them
DataFile dataFile( value.toUtf8() );
// Extract the clip data
QDomElement clipParent = dataFile.content().firstChildElement("clips");
QDomNodeList clipNodes = clipParent.childNodes();
// Extract the track index that was originally clicked
QDomElement metadata = dataFile.content().firstChildElement( "copyMetadata" );
QDomAttr tiAttr = metadata.attributeNode( "initialTrackIndex" );
int initialTrackIndex = tiAttr.value().toInt();
QDomAttr clipPosAttr = metadata.attributeNode( "grabbedClipPos" );
TimePos grabbedClipPos = clipPosAttr.value().toInt();
// Snap the mouse position to the beginning of the dropped bar, in ticks
const TrackContainer::TrackList& tracks = getTrack()->trackContainer()->tracks();
const auto currentTrackIt = std::find(tracks.begin(), tracks.end(), getTrack());
const int currentTrackIndex = currentTrackIt != tracks.end() ? std::distance(tracks.begin(), currentTrackIt) : -1;
bool wasSelection = m_trackView->trackContainerView()->rubberBand()->selectedObjects().count();
// Unselect the old group
const QVector<selectableObject *> so =
m_trackView->trackContainerView()->selectedObjects();
for (const auto& obj : so)
{
obj->setSelected(false);
}
// TODO -- Need to draw the hovericon either way, or ghost the Clips
// onto their final position.
float snapSize = getGUI()->songEditor()->m_editor->getSnapSize();
// All clips should be offset the same amount as the grabbed clip
auto offset = TimePos(clipPos - grabbedClipPos);
// Users expect clips to "fall" backwards, so bias the offset
offset -= TimePos::ticksPerBar() * snapSize / 2;
// The offset is quantized (rather than the positions) to preserve fine adjustments
offset = offset.quantize(snapSize);
// Get the leftmost Clip and fix the offset if it reaches below bar 0
TimePos leftmostPos = grabbedClipPos;
for(int i = 0; i < clipNodes.length(); ++i)
{
QDomElement outerClipElement = clipNodes.item(i).toElement();
QDomElement clipElement = outerClipElement.firstChildElement();
TimePos pos = clipElement.attributeNode("pos").value().toInt();
if(pos < leftmostPos) { leftmostPos = pos; }
}
// Fix offset if it sets the left most Clip to a negative position
offset = std::max(offset.getTicks(), -leftmostPos.getTicks());
for( int i = 0; i<clipNodes.length(); i++ )
{
QDomElement outerClipElement = clipNodes.item( i ).toElement();
QDomElement clipElement = outerClipElement.firstChildElement();
int trackIndex = outerClipElement.attributeNode( "trackIndex" ).value().toInt();
int finalTrackIndex = trackIndex + ( currentTrackIndex - initialTrackIndex );
Track * t = tracks.at( finalTrackIndex );
// The new position is the old position plus the offset.
TimePos pos = clipElement.attributeNode( "pos" ).value().toInt() + offset;
// If we land on ourselves, offset by one snap
TimePos shift = TimePos::ticksPerBar() * getGUI()->songEditor()->m_editor->getSnapSize();
if (offset == 0 && initialTrackIndex == currentTrackIndex) { pos += shift; }
Clip * clip = t->createClip( pos );
clip->restoreState( clipElement );
clip->movePosition(pos); // Because we restored the state, we need to move the Clip again.
if( wasSelection )
{
clip->selectViewOnCreate( true );
}
}
AutomationClip::resolveAllIDs();
return true;
}
/*! \brief Respond to a drop event on the trackContentWidget
*
* \param de the Drop Event to respond to
*/
void TrackContentWidget::dropEvent( QDropEvent * de )
{
TimePos clipPos = TimePos( getPosition( de->pos().x() ) );
if( pasteSelection( clipPos, de ) == true )
{
de->accept();
}
}
/*! \brief Respond to a mouse press on the trackContentWidget
*
* \param me the mouse press event to respond to
*/
void TrackContentWidget::mousePressEvent( QMouseEvent * me )
{
// Enable box select if control is held when clicking an empty space
// (If we had clicked a Clip it would have intercepted the mouse event)
if( me->modifiers() & Qt::ControlModifier ){
getGUI()->songEditor()->m_editor->setEditMode(SongEditor::EditMode::Select);
}
// Forward event to allow box select if the editor supports it and is in that mode
if( m_trackView->trackContainerView()->allowRubberband() == true )
{
QWidget::mousePressEvent( me );
}
// Forward shift clicks so tracks can be resized
else if( me->modifiers() & Qt::ShiftModifier )
{
QWidget::mousePressEvent( me );
}
// For an unmodified click, create a new Clip
else if( me->button() == Qt::LeftButton &&
!m_trackView->trackContainerView()->fixedClips() )
{
QVector<selectableObject*> so = m_trackView->trackContainerView()->rubberBand()->selectedObjects();
for( int i = 0; i < so.count(); ++i )
{
so.at( i )->setSelected( false);
}
getTrack()->addJournalCheckPoint();
const TimePos pos = getPosition( me->x() ).getBar() *
TimePos::ticksPerBar();
getTrack()->createClip(pos);
}
}
void TrackContentWidget::mouseReleaseEvent( QMouseEvent * me )
{
getGUI()->songEditor()->syncEditMode();
QWidget::mouseReleaseEvent(me);
}
/*! \brief Repaint the trackContentWidget on command
*
* \param pe the Paint Event to respond to
*/
void TrackContentWidget::paintEvent( QPaintEvent * pe )
{
// Assume even-pixels-per-bar. Makes sense, should be like this anyways
const TrackContainerView * tcv = m_trackView->trackContainerView();
int ppb = static_cast<int>( tcv->pixelsPerBar() );
QPainter p( this );
// Don't draw background on Pattern Editor
if (m_trackView->trackContainerView() != getGUI()->patternEditor()->m_editor)
{
p.drawTiledPixmap(rect(), m_background, QPoint(
tcv->currentPosition().getTicks() * ppb / TimePos::ticksPerBar(), 0));
}
}
/*! \brief Updates the background tile pixmap on size changes.
*
* \param resizeEvent the resize event to pass to base class
*/
void TrackContentWidget::resizeEvent( QResizeEvent * resizeEvent )
{
// Update backgroud
updateBackground();
// Force redraw
QWidget::resizeEvent( resizeEvent );
}
/*! \brief Return the track shown by the trackContentWidget
*
*/
Track * TrackContentWidget::getTrack()
{
return m_trackView->getTrack();
}
/*! \brief Return the end position of the trackContentWidget in Bars.
*
* \param posStart the starting position of the Widget (from getPosition())
*/
TimePos TrackContentWidget::endPosition( const TimePos & posStart )
{
const float ppb = m_trackView->trackContainerView()->pixelsPerBar();
const int w = width();
return posStart + static_cast<int>( w * TimePos::ticksPerBar() / ppb );
}
void TrackContentWidget::contextMenuEvent( QContextMenuEvent * cme )
{
// For hasFormat(), MimeType enum class and getMimeData()
using namespace Clipboard;
if( cme->modifiers() )
{
return;
}
// If we don't have Clip data in the clipboard there's no need to create this menu
// since "paste" is the only action at the moment.
if( ! hasFormat( MimeType::StringPair ) )
{
return;
}
QMenu contextMenu( this );
QAction *pasteA = contextMenu.addAction( embed::getIconPixmap( "edit_paste" ),
tr( "Paste" ), [this, cme](){ contextMenuAction( cme, ContextMenuAction::Paste ); } );
// If we can't paste in the current TCW for some reason, disable the action so the user knows
pasteA->setEnabled( canPasteSelection( getPosition( cme->x() ), getMimeData() ) ? true : false );
contextMenu.exec( QCursor::pos() );
}
void TrackContentWidget::contextMenuAction( QContextMenuEvent * cme, ContextMenuAction action )
{
// For getMimeData()
using namespace Clipboard;
switch( action )
{
case ContextMenuAction::Paste:
// Paste the selection on the TimePos of the context menu event
TimePos clipPos = getPosition( cme->x() );
pasteSelection( clipPos, getMimeData() );
break;
}
}
// qproperty access methods
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::darkerColor() const
{ return m_darkerColor; }
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::lighterColor() const
{ return m_lighterColor; }
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::coarseGridColor() const
{ return m_coarseGridColor; }
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::fineGridColor() const
{ return m_fineGridColor; }
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::horizontalColor() const
{ return m_horizontalColor; }
//! \brief CSS theming qproperty access method
QBrush TrackContentWidget::embossColor() const
{ return m_embossColor; }
//! \brief CSS theming qproperty access method
int TrackContentWidget::coarseGridWidth() const
{ return m_coarseGridWidth; }
//! \brief CSS theming qproperty access method
int TrackContentWidget::fineGridWidth() const
{ return m_fineGridWidth; }
//! \brief CSS theming qproperty access method
int TrackContentWidget::horizontalWidth() const
{ return m_horizontalWidth; }
//! \brief CSS theming qproperty access method
int TrackContentWidget::embossWidth() const
{ return m_embossWidth; }
//! \brief CSS theming qproperty access method
int TrackContentWidget::embossOffset() const
{ return m_embossOffset; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setDarkerColor( const QBrush & c )
{ m_darkerColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setLighterColor( const QBrush & c )
{ m_lighterColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setCoarseGridColor( const QBrush & c )
{ m_coarseGridColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setFineGridColor( const QBrush & c )
{ m_fineGridColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setHorizontalColor( const QBrush & c )
{ m_horizontalColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setEmbossColor( const QBrush & c )
{ m_embossColor = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setCoarseGridWidth(int c)
{ m_coarseGridWidth = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setFineGridWidth(int c)
{ m_fineGridWidth = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setHorizontalWidth(int c)
{ m_horizontalWidth = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setEmbossWidth(int c)
{ m_embossWidth = c; }
//! \brief CSS theming qproperty access method
void TrackContentWidget::setEmbossOffset(int c)
{ m_embossOffset = c; }
} // namespace lmms::gui
| 24,107
|
C++
|
.cpp
| 648
| 34.905864
| 117
| 0.735502
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,978
|
FadeButton.cpp
|
LMMS_lmms/src/gui/tracks/FadeButton.cpp
|
/*
* FadeButton.cpp - implementation of fade-button
*
* Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QTimer>
#include <QPainter>
#include "embed.h"
#include "FadeButton.h"
namespace lmms::gui
{
const float FadeDuration = 300;
FadeButton::FadeButton(const QColor & _normal_color,
const QColor & _activated_color,
const QColor & holdColor,
QWidget * _parent) :
QAbstractButton( _parent ),
m_stateTimer(),
m_releaseTimer(),
m_normalColor( _normal_color ),
m_activatedColor( _activated_color ),
m_holdColor( holdColor )
{
setAttribute(Qt::WA_OpaquePaintEvent, true);
setCursor(QCursor(embed::getIconPixmap("hand"), 3, 3));
setFocusPolicy(Qt::NoFocus);
activeNotes = 0;
}
void FadeButton::setActiveColor(const QColor & activated_color)
{
m_activatedColor = activated_color;
}
void FadeButton::activate()
{
m_stateTimer.restart();
activeNotes++;
update();
}
void FadeButton::activateOnce()
{
if (activeNotes == 0) { activate(); }
}
void FadeButton::noteEnd()
{
if (activeNotes <= 0)
{
qWarning("noteEnd() triggered without a corresponding activate()!");
activeNotes = 0;
}
else
{
activeNotes--;
}
if (activeNotes == 0)
{
m_releaseTimer.restart();
}
update();
}
void FadeButton::paintEvent(QPaintEvent * _pe)
{
QColor col = m_normalColor;
if(m_stateTimer.isValid() && m_stateTimer.elapsed() < FadeDuration)
{
// The first part of the fade, when a note is triggered.
col = fadeToColor(m_activatedColor, m_holdColor, m_stateTimer, FadeDuration);
QTimer::singleShot(20, this, SLOT(update()));
}
else if (m_stateTimer.isValid()
&& m_stateTimer.elapsed() >= FadeDuration
&& activeNotes > 0)
{
// The fade is done, but at least one note is still held.
col = m_holdColor;
}
else if (m_releaseTimer.isValid() && m_releaseTimer.elapsed() < FadeDuration)
{
// Last note just ended. Fade to default color.
col = fadeToColor(m_holdColor, m_normalColor, m_releaseTimer, FadeDuration);
QTimer::singleShot(20, this, SLOT(update()));
}
else
{
// No fade, no notes. Set to default color.
col = m_normalColor;
}
QPainter p(this);
p.fillRect(rect(), col);
int w = rect().right();
int h = rect().bottom();
p.setPen(m_normalColor.darker(130));
p.drawLine(w, 1, w, h);
p.drawLine(1, h, w, h);
p.setPen(m_normalColor.lighter(130));
p.drawLine(0, 0, 0, h-1);
p.drawLine(0, 0, w, 0);
}
QColor FadeButton::fadeToColor(QColor startCol, QColor endCol, QElapsedTimer timer, float duration)
{
QColor col;
const float state = 1 - timer.elapsed() / duration;
const int r = (int)(endCol.red() * (1.0f - state)
+ startCol.red() * state);
const int g = (int)(endCol.green() * (1.0f - state)
+ startCol.green() * state);
const int b = (int)(endCol.blue() * (1.0f - state)
+ startCol.blue() * state);
col.setRgb(r, g, b);
return col;
}
} // namespace lmms::gui
| 3,691
|
C++
|
.cpp
| 129
| 26.379845
| 99
| 0.715948
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,979
|
TrackLabelButton.cpp
|
LMMS_lmms/src/gui/tracks/TrackLabelButton.cpp
|
/*
* TrackLabelButton.cpp - implementation of class trackLabelButton, a label
* which is renamable by double-clicking it
*
* Copyright (c) 2004-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackLabelButton.h"
#include <QMouseEvent>
#include "ConfigManager.h"
#include "embed.h"
#include "InstrumentTrackView.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "RenameDialog.h"
#include "TrackRenameLineEdit.h"
#include "TrackView.h"
#include "Track.h"
namespace lmms::gui
{
TrackLabelButton::TrackLabelButton( TrackView * _tv, QWidget * _parent ) :
QToolButton( _parent ),
m_trackView( _tv ),
m_iconName()
{
setAttribute( Qt::WA_OpaquePaintEvent, true );
setAcceptDrops( true );
setCursor( QCursor( embed::getIconPixmap( "hand" ), 3, 3 ) );
setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
m_renameLineEdit = new TrackRenameLineEdit( this );
m_renameLineEdit->hide();
if (isInCompactMode())
{
setFixedSize( 32, 29 );
}
else
{
setFixedSize( 160, 29 );
connect( m_renameLineEdit, SIGNAL(editingFinished()), this, SLOT(renameFinished()));
}
setIconSize( QSize( 24, 24 ) );
connect( m_trackView->getTrack(), SIGNAL(dataChanged()), this, SLOT(update()));
connect( m_trackView->getTrack(), SIGNAL(nameChanged()), this, SLOT(nameChanged()));
}
void TrackLabelButton::rename()
{
if (isInCompactMode())
{
QString txt = m_trackView->getTrack()->name();
RenameDialog renameDlg( txt );
renameDlg.exec();
if( txt != text() )
{
m_trackView->getTrack()->setName( txt );
}
}
else
{
const auto & trackName = m_trackView->getTrack()->name();
m_renameLineEdit->setText(trackName);
m_renameLineEdit->selectAll();
m_renameLineEdit->setFocus();
// Make sure that the rename line edit uses the same font as the widget
// which is set via style sheets
m_renameLineEdit->setFont(font());
// Move the line edit to the correct position by taking the size of the
// icon into account.
const auto iconWidth = iconSize().width();
m_renameLineEdit->move(iconWidth + 1, (height() / 2 - m_renameLineEdit->sizeHint().height() / 2) + 1);
m_renameLineEdit->setFixedWidth(width() - (iconWidth + 6));
m_renameLineEdit->show();
}
}
void TrackLabelButton::renameFinished()
{
if (!isInCompactMode())
{
m_renameLineEdit->clearFocus();
m_renameLineEdit->hide();
if( m_renameLineEdit->text() != "" )
{
if( m_renameLineEdit->text() != m_trackView->getTrack()->name() )
{
setText( elideName( m_renameLineEdit->text() ) );
m_trackView->getTrack()->setName( m_renameLineEdit->text() );
}
}
}
}
void TrackLabelButton::nameChanged()
{
setText( elideName( m_trackView->getTrack()->name() ) );
}
void TrackLabelButton::dragEnterEvent( QDragEnterEvent * _dee )
{
m_trackView->dragEnterEvent( _dee );
}
void TrackLabelButton::dropEvent( QDropEvent * _de )
{
m_trackView->dropEvent( _de );
setChecked( true );
}
void TrackLabelButton::mousePressEvent( QMouseEvent * _me )
{
if( _me->button() == Qt::RightButton )
{
rename();
}
else
{
m_buttonRect = QRect( this->mapToGlobal( pos() ), size() );
_me->ignore();
}
}
void TrackLabelButton::mouseDoubleClickEvent( QMouseEvent * _me )
{
rename();
}
void TrackLabelButton::mouseReleaseEvent( QMouseEvent *_me )
{
if( m_buttonRect.contains( _me->globalPos(), true ) && m_renameLineEdit->isHidden() )
{
QToolButton::mousePressEvent( _me );
}
QToolButton::mouseReleaseEvent( _me );
_me->ignore();
}
void TrackLabelButton::paintEvent(QPaintEvent* pe)
{
if (m_trackView->getTrack()->type() == Track::Type::Instrument)
{
auto it = dynamic_cast<InstrumentTrack*>(m_trackView->getTrack());
const PixmapLoader* pl;
auto get_logo = [](InstrumentTrack* it) -> const PixmapLoader*
{
return it->instrument()->key().isValid()
? it->instrument()->key().logo()
: it->instrument()->descriptor()->logo;
};
if (it && it->instrument() &&
it->instrument()->descriptor() &&
(pl = get_logo(it)))
{
if (pl->pixmapName() != m_iconName)
{
m_iconName = pl->pixmapName();
setIcon(pl->pixmap());
}
}
}
QToolButton::paintEvent(pe);
}
void TrackLabelButton::resizeEvent(QResizeEvent *_re)
{
setText( elideName( m_trackView->getTrack()->displayName() ) );
}
QString TrackLabelButton::elideName( const QString &name )
{
const int spacing = 16;
const int maxTextWidth = width() - spacing - iconSize().width();
if( maxTextWidth < 1 )
{
setToolTip( m_trackView->getTrack()->displayName() );
return QString( " " );
}
setToolTip( "" );
QFontMetrics metrics( font() );
QString elidedName = metrics.elidedText( name, Qt::ElideRight, maxTextWidth );
return elidedName;
}
bool TrackLabelButton::isInCompactMode() const
{
return ConfigManager::inst()->value("ui", "compacttrackbuttons").toInt();
}
} // namespace lmms::gui
| 5,683
|
C++
|
.cpp
| 192
| 27.15625
| 105
| 0.708211
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,980
|
TrackOperationsWidget.cpp
|
LMMS_lmms/src/gui/tracks/TrackOperationsWidget.cpp
|
/*
* TrackOperationsWidget.cpp - implementation of TrackOperationsWidget class
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackOperationsWidget.h"
#include <QBoxLayout>
#include <QMenu>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QCheckBox>
#include "AutomationClip.h"
#include "AutomationTrackView.h"
#include "ColorChooser.h"
#include "ConfigManager.h"
#include "DataFile.h"
#include "embed.h"
#include "Engine.h"
#include "InstrumentTrackView.h"
#include "PixmapButton.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "Track.h"
#include "TrackContainerView.h"
#include "TrackGrip.h"
#include "TrackView.h"
namespace lmms::gui
{
/*! \brief Create a new trackOperationsWidget
*
* The trackOperationsWidget is the grip and the mute button of a track.
*
* \param parent the trackView to contain this widget
*/
TrackOperationsWidget::TrackOperationsWidget( TrackView * parent ) :
QWidget( parent ), /*!< The parent widget */
m_trackView( parent ) /*!< The parent track view */
{
setToolTip(tr("Press <%1> while clicking on move-grip "
"to begin a new drag'n'drop action." ).arg(UI_CTRL_KEY) );
auto toMenu = new QMenu(this);
connect( toMenu, SIGNAL(aboutToShow()), this, SLOT(updateMenu()));
setObjectName( "automationEnabled" );
auto layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->setAlignment(Qt::AlignTop);
m_trackGrip = new TrackGrip(m_trackView->getTrack(), this);
layout->addWidget(m_trackGrip);
// This widget holds the gear icon and the mute and solo
// buttons in a layout.
auto operationsWidget = new QWidget(this);
auto operationsLayout = new QHBoxLayout(operationsWidget);
operationsLayout->setContentsMargins(0, 0, 0, 0);
operationsLayout->setSpacing(0);
m_trackOps = new QPushButton(operationsWidget);
m_trackOps->setFocusPolicy( Qt::NoFocus );
m_trackOps->setMenu( toMenu );
m_trackOps->setToolTip(tr("Actions"));
// This helper lambda wraps a PixmapButton in a QWidget. This is necessary due to some strange effect where the
// PixmapButtons are resized to a size that's larger than their minimum/fixed size when the method "show" is called
// in "TrackContainerView::realignTracks". Specifically, with the default theme the buttons are resized from
// (16, 14) to (26, 26). This then makes them behave not as expected in layouts.
// The resizing is not done for QWidgets. Therefore we wrap the PixmapButton in a QWidget which is set to a
// fixed size that will be able to show the active and inactive pixmap. We can then use the QWidget in layouts
// without any disturbances.
//
// The resizing only seems to affect the track view hierarchy and is triggered by Qt's internal mechanisms.
// For example the buttons in the mixer view do not seem to be affected.
// If you want to debug this simply override "PixmapButton::resizeEvent" and trigger a break point in there.
auto buildPixmapButtonWrappedInWidget = [](QWidget* parent, const QString& toolTip,
std::string_view activeGraphic, std::string_view inactiveGraphic, PixmapButton*& pixmapButton)
{
const auto activePixmap = embed::getIconPixmap(activeGraphic);
const auto inactivePixmap = embed::getIconPixmap(inactiveGraphic);
auto necessarySize = activePixmap.size().expandedTo(inactivePixmap.size());
auto wrapperWidget = new QWidget(parent);
wrapperWidget->setFixedSize(necessarySize);
auto button = new PixmapButton(wrapperWidget, toolTip);
button->setCheckable(true);
button->setActiveGraphic(activePixmap);
button->setInactiveGraphic(inactivePixmap);
button->setToolTip(toolTip);
pixmapButton = button;
return wrapperWidget;
};
auto muteWidget = buildPixmapButtonWrappedInWidget(operationsWidget, tr("Mute"), "led_off", "led_green", m_muteBtn);
auto soloWidget = buildPixmapButtonWrappedInWidget(operationsWidget, tr("Solo"), "led_red", "led_off", m_soloBtn);
operationsLayout->addWidget(m_trackOps, Qt::AlignCenter);
operationsLayout->addSpacing(5);
if( ConfigManager::inst()->value( "ui",
"compacttrackbuttons" ).toInt() )
{
auto vlayout = new QVBoxLayout();
vlayout->setContentsMargins(0, 0, 0, 0);
vlayout->setSpacing(0);
vlayout->addStretch(1);
vlayout->addWidget(muteWidget);
vlayout->addWidget(soloWidget);
vlayout->addStretch(1);
operationsLayout->addLayout(vlayout);
}
else
{
operationsLayout->addWidget(muteWidget, Qt::AlignCenter);
operationsLayout->addWidget(soloWidget, Qt::AlignCenter);
}
operationsLayout->addStretch(1);
layout->addWidget(operationsWidget, 0, Qt::AlignTop);
connect( this, SIGNAL(trackRemovalScheduled(lmms::gui::TrackView*)),
m_trackView->trackContainerView(),
SLOT(deleteTrackView(lmms::gui::TrackView*)),
Qt::QueuedConnection );
connect( m_trackView->getTrack()->getMutedModel(), SIGNAL(dataChanged()),
this, SLOT(update()));
connect(m_trackView->getTrack(), SIGNAL(colorChanged()), this, SLOT(update()));
}
/*! \brief Respond to trackOperationsWidget mouse events
*
* If it's the left mouse button, and Ctrl is held down, and we're
* not a Pattern Editor track, then start a new drag event to
* copy this track.
*
* Otherwise, ignore all other events.
*
* \param me The mouse event to respond to.
*/
void TrackOperationsWidget::mousePressEvent( QMouseEvent * me )
{
if( me->button() == Qt::LeftButton &&
me->modifiers() & Qt::ControlModifier &&
m_trackView->getTrack()->type() != Track::Type::Pattern)
{
DataFile dataFile( DataFile::Type::DragNDropData );
m_trackView->getTrack()->saveState( dataFile, dataFile.content() );
new StringPairDrag( QString( "track_%1" ).arg(
static_cast<int>(m_trackView->getTrack()->type()) ),
dataFile.toString(), m_trackView->getTrackSettingsWidget()->grab(),
this );
}
else if( me->button() == Qt::LeftButton )
{
// track-widget (parent-widget) initiates track-move
me->ignore();
}
}
/*!
* \brief Repaint the trackOperationsWidget
*
* Only things that's done for now is to paint the background
* with the brush of the window from the palette.
*/
void TrackOperationsWidget::paintEvent(QPaintEvent*)
{
QPainter p( this );
p.fillRect(rect(), palette().brush(QPalette::Window));
}
/*! \brief Show a message box warning the user that this track is about to be closed */
bool TrackOperationsWidget::confirmRemoval()
{
bool needConfirm = ConfigManager::inst()->value("ui", "trackdeletionwarning", "1").toInt();
if (!needConfirm){ return true; }
QString messageRemoveTrack = tr("After removing a track, it can not "
"be recovered. Are you sure you want to remove track \"%1\"?")
.arg(m_trackView->getTrack()->name());
QString messageTitleRemoveTrack = tr("Confirm removal");
QString askAgainText = tr("Don't ask again");
auto askAgainCheckBox = new QCheckBox(askAgainText, nullptr);
connect(askAgainCheckBox, &QCheckBox::stateChanged, [](int state){
// Invert button state, if it's checked we *shouldn't* ask again
ConfigManager::inst()->setValue("ui", "trackdeletionwarning", state ? "0" : "1");
});
QMessageBox mb(this);
mb.setText(messageRemoveTrack);
mb.setWindowTitle(messageTitleRemoveTrack);
mb.setIcon(QMessageBox::Warning);
mb.addButton(QMessageBox::Cancel);
mb.addButton(QMessageBox::Ok);
mb.setCheckBox(askAgainCheckBox);
mb.setDefaultButton(QMessageBox::Cancel);
int answer = mb.exec();
if( answer == QMessageBox::Ok )
{
return true;
}
return false;
}
/*! \brief Clone this track
*
*/
void TrackOperationsWidget::cloneTrack()
{
TrackContainerView *tcView = m_trackView->trackContainerView();
Track *newTrack = m_trackView->getTrack()->clone();
TrackView *newTrackView = tcView->createTrackView( newTrack );
int index = tcView->trackViews().indexOf( m_trackView );
int i = tcView->trackViews().size();
while ( i != index + 1 )
{
tcView->moveTrackView( newTrackView, i - 1 );
i--;
}
if (m_soloBtn->model()->value())
{
// if this track was solo, make the new track the new solo
newTrack->toggleSolo();
}
}
/*! \brief Clear this track - clears all Clips from the track */
void TrackOperationsWidget::clearTrack()
{
Track * t = m_trackView->getTrack();
t->addJournalCheckPoint();
t->lock();
t->deleteClips();
t->unlock();
}
/*! \brief Remove this track from the track list
*
*/
void TrackOperationsWidget::removeTrack()
{
if (confirmRemoval())
{
emit trackRemovalScheduled(m_trackView);
}
}
void TrackOperationsWidget::selectTrackColor()
{
const auto newColor = ColorChooser{this}
.withPalette(ColorChooser::Palette::Track)
->getColor(m_trackView->getTrack()->color().value_or(Qt::white));
if (!newColor.isValid()) { return; }
const auto track = m_trackView->getTrack();
track->addJournalCheckPoint();
track->setColor(newColor);
Engine::getSong()->setModified();
}
void TrackOperationsWidget::resetTrackColor()
{
auto track = m_trackView->getTrack();
track->addJournalCheckPoint();
track->setColor(std::nullopt);
Engine::getSong()->setModified();
}
void TrackOperationsWidget::randomizeTrackColor()
{
QColor buffer = ColorChooser::getPalette( ColorChooser::Palette::Track )[ rand() % 48 ];
auto track = m_trackView->getTrack();
track->addJournalCheckPoint();
track->setColor(buffer);
Engine::getSong()->setModified();
}
void TrackOperationsWidget::resetClipColors()
{
auto track = m_trackView->getTrack();
track->addJournalCheckPoint();
for (auto clip : track->getClips())
{
clip->setColor(std::nullopt);
}
Engine::getSong()->setModified();
}
/*! \brief Update the trackOperationsWidget context menu
*
* For all track types, we have the Clone and Remove options.
* For instrument-tracks we also offer the MIDI-control-menu
* For automation tracks, extra options: turn on/off recording
* on all Clips (same should be added for sample tracks when
* sampletrack recording is implemented)
*/
void TrackOperationsWidget::updateMenu()
{
QMenu * toMenu = m_trackOps->menu();
toMenu->clear();
toMenu->addAction( embed::getIconPixmap( "edit_copy", 16, 16 ),
tr( "Clone this track" ),
this, SLOT(cloneTrack()));
toMenu->addAction( embed::getIconPixmap( "cancel", 16, 16 ),
tr( "Remove this track" ),
this, SLOT(removeTrack()));
if( ! m_trackView->trackContainerView()->fixedClips() )
{
toMenu->addAction( tr( "Clear this track" ), this, SLOT(clearTrack()));
}
if (QMenu *mixerMenu = m_trackView->createMixerMenu(tr("Channel %1: %2"), tr("Assign to new Mixer Channel")))
{
toMenu->addMenu(mixerMenu);
}
if (auto trackView = dynamic_cast<InstrumentTrackView*>(m_trackView))
{
toMenu->addSeparator();
toMenu->addMenu(trackView->midiMenu());
}
if( dynamic_cast<AutomationTrackView *>( m_trackView ) )
{
toMenu->addAction( tr( "Turn all recording on" ), this, SLOT(recordingOn()));
toMenu->addAction( tr( "Turn all recording off" ), this, SLOT(recordingOff()));
}
toMenu->addSeparator();
QMenu* colorMenu = toMenu->addMenu(tr("Track color"));
colorMenu->setIcon(embed::getIconPixmap("colorize"));
colorMenu->addAction(tr("Change"), this, SLOT(selectTrackColor()));
colorMenu->addAction(tr("Reset"), this, SLOT(resetTrackColor()));
colorMenu->addAction(tr("Pick random"), this, SLOT(randomizeTrackColor()));
colorMenu->addSeparator();
colorMenu->addAction(tr("Reset clip colors"), this, SLOT(resetClipColors()));
}
void TrackOperationsWidget::toggleRecording( bool on )
{
auto atv = dynamic_cast<AutomationTrackView*>(m_trackView);
if( atv )
{
for( Clip * clip : atv->getTrack()->getClips() )
{
auto ap = dynamic_cast<AutomationClip*>(clip);
if( ap ) { ap->setRecording( on ); }
}
atv->update();
}
}
void TrackOperationsWidget::recordingOn()
{
toggleRecording( true );
}
void TrackOperationsWidget::recordingOff()
{
toggleRecording( false );
}
} // namespace lmms::gui
| 12,736
|
C++
|
.cpp
| 350
| 34.057143
| 117
| 0.739886
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,981
|
TrackRenameLineEdit.cpp
|
LMMS_lmms/src/gui/tracks/TrackRenameLineEdit.cpp
|
/*
* TrackRenameLineEdit.cpp - implementation of class TrackRenameLineEdit, which
* represents the text field that appears when one
* double-clicks a track's label to rename it
*
* Copyright (c) 2004-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2017 Alexandre Almeida <http://m374lx.users.sourceforge.net/>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackRenameLineEdit.h"
#include <QKeyEvent>
namespace lmms::gui
{
TrackRenameLineEdit::TrackRenameLineEdit( QWidget * parent ) :
QLineEdit( parent )
{
}
void TrackRenameLineEdit::show()
{
m_oldName = text();
QLineEdit::show();
}
void TrackRenameLineEdit::keyPressEvent( QKeyEvent * ke )
{
if( ke->key() == Qt::Key_Escape )
{
setText( m_oldName );
hide();
}
QLineEdit::keyPressEvent( ke );
}
} // namespace lmms::gui
| 1,605
|
C++
|
.cpp
| 49
| 30.632653
| 79
| 0.74399
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,982
|
TrackGrip.cpp
|
LMMS_lmms/src/gui/tracks/TrackGrip.cpp
|
/*
* TrackGrip.cpp - Grip that can be used to move tracks
*
* Copyright (c) 2024- Michael Gregorius
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackGrip.h"
#include "embed.h"
#include "Track.h"
#include <QPainter>
#include <QPixmap>
#include <QMouseEvent>
namespace lmms::gui
{
QPixmap* TrackGrip::s_grabbedPixmap = nullptr;
QPixmap* TrackGrip::s_releasedPixmap = nullptr;
constexpr int c_margin = 2;
TrackGrip::TrackGrip(Track* track, QWidget* parent) :
QWidget(parent),
m_track(track)
{
if (!s_grabbedPixmap)
{
s_grabbedPixmap = new QPixmap(embed::getIconPixmap("track_op_grip_c"));
}
if (!s_releasedPixmap)
{
s_releasedPixmap = new QPixmap(embed::getIconPixmap("track_op_grip"));
}
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
setCursor(Qt::OpenHandCursor);
setFixedWidth(std::max(s_grabbedPixmap->width(), s_releasedPixmap->width()) + 2 * c_margin);
}
void TrackGrip::mousePressEvent(QMouseEvent* m)
{
m->accept();
m_isGrabbed = true;
setCursor(Qt::ClosedHandCursor);
emit grabbed();
update();
}
void TrackGrip::mouseReleaseEvent(QMouseEvent* m)
{
m->accept();
m_isGrabbed = false;
setCursor(Qt::OpenHandCursor);
emit released();
update();
}
void TrackGrip::paintEvent(QPaintEvent*)
{
QPainter p(this);
// Check if the color of the track should be used for the background
const auto color = m_track->color();
const auto muted = m_track->getMutedModel()->value();
if (color.has_value() && !muted)
{
p.fillRect(rect(), color.value());
}
// Paint the pixmap
auto r = rect().marginsRemoved(QMargins(c_margin, c_margin, c_margin, c_margin));
p.drawTiledPixmap(r, m_isGrabbed ? *s_grabbedPixmap : *s_releasedPixmap);
}
} // namespace lmms::gui
| 2,485
|
C++
|
.cpp
| 81
| 28.62963
| 93
| 0.742749
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,983
|
SampleTrackView.cpp
|
LMMS_lmms/src/gui/tracks/SampleTrackView.cpp
|
/*
* SampleTrackView.cpp
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SampleTrackView.h"
#include <QApplication>
#include <QMenu>
#include "ConfigManager.h"
#include "embed.h"
#include "Engine.h"
#include "FadeButton.h"
#include "Mixer.h"
#include "MixerView.h"
#include "GuiApplication.h"
#include "Knob.h"
#include "SampleClip.h"
#include "SampleTrackWindow.h"
#include "StringPairDrag.h"
#include "TrackContainerView.h"
#include "TrackLabelButton.h"
namespace lmms::gui
{
SampleTrackView::SampleTrackView( SampleTrack * _t, TrackContainerView* tcv ) :
TrackView( _t, tcv )
{
setFixedHeight( 32 );
m_tlb = new TrackLabelButton(this, getTrackSettingsWidget());
m_tlb->setCheckable(true);
connect(m_tlb, SIGNAL(clicked(bool)),
this, SLOT(showEffects()));
m_tlb->setIcon(embed::getIconPixmap("sample_track"));
m_tlb->show();
m_mixerChannelNumber = new MixerChannelLcdSpinBox(2, getTrackSettingsWidget(), tr("Mixer channel"), this);
m_mixerChannelNumber->show();
m_volumeKnob = new Knob( KnobType::Small17, getTrackSettingsWidget(),
tr( "Track volume" ) );
m_volumeKnob->setVolumeKnob( true );
m_volumeKnob->setModel( &_t->m_volumeModel );
m_volumeKnob->setHintText( tr( "Channel volume:" ), "%" );
m_volumeKnob->setLabel( tr( "VOL" ) );
m_volumeKnob->show();
m_panningKnob = new Knob( KnobType::Small17, getTrackSettingsWidget(),
tr( "Panning" ) );
m_panningKnob->setModel( &_t->m_panningModel );
m_panningKnob->setHintText( tr( "Panning:" ), "%" );
m_panningKnob->setLabel( tr( "PAN" ) );
m_panningKnob->show();
m_activityIndicator = new FadeButton(
QApplication::palette().color(QPalette::Active, QPalette::Window),
QApplication::palette().color(QPalette::Active, QPalette::BrightText),
QApplication::palette().color(QPalette::Active, QPalette::BrightText).darker(),
getTrackSettingsWidget()
);
m_activityIndicator->setFixedSize(8, 28);
m_activityIndicator->show();
auto masterLayout = new QVBoxLayout(getTrackSettingsWidget());
masterLayout->setContentsMargins(0, 1, 0, 0);
auto layout = new QHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(m_tlb);
layout->addWidget(m_mixerChannelNumber);
layout->addWidget(m_activityIndicator);
layout->addWidget(m_volumeKnob);
layout->addWidget(m_panningKnob);
masterLayout->addLayout(layout);
masterLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
connect(_t, SIGNAL(playingChanged()), this, SLOT(updateIndicator()));
setModel( _t );
m_window = new SampleTrackWindow(this);
m_window->toggleVisibility(false);
}
void SampleTrackView::updateIndicator()
{
if (model()->isPlaying()) { m_activityIndicator->activateOnce(); }
else { m_activityIndicator->noteEnd(); }
}
SampleTrackView::~SampleTrackView()
{
if(m_window != nullptr)
{
m_window->setSampleTrackView(nullptr);
m_window->parentWidget()->hide();
}
m_window = nullptr;
}
//FIXME: This is identical to InstrumentTrackView::createMixerMenu
QMenu * SampleTrackView::createMixerMenu(QString title, QString newMixerLabel)
{
int channelIndex = model()->mixerChannelModel()->value();
MixerChannel *mixerChannel = Engine::mixer()->mixerChannel(channelIndex);
// If title allows interpolation, pass channel index and name
if (title.contains("%2"))
{
title = title.arg(channelIndex).arg(mixerChannel->m_name);
}
auto mixerMenu = new QMenu(title);
mixerMenu->addAction(newMixerLabel, this, SLOT(createMixerLine()));
mixerMenu->addSeparator();
for (int i = 0; i < Engine::mixer()->numChannels(); ++i)
{
MixerChannel * currentChannel = Engine::mixer()->mixerChannel(i);
if (currentChannel != mixerChannel)
{
const auto index = currentChannel->m_channelIndex;
QString label = tr("%1: %2").arg(currentChannel->m_channelIndex).arg(currentChannel->m_name);
mixerMenu->addAction(label, [this, index](){
assignMixerLine(index);
});
}
}
return mixerMenu;
}
void SampleTrackView::showEffects()
{
m_window->toggleVisibility(m_window->parentWidget()->isHidden());
}
void SampleTrackView::modelChanged()
{
auto st = castModel<SampleTrack>();
m_volumeKnob->setModel(&st->m_volumeModel);
m_mixerChannelNumber->setModel(&st->m_mixerChannelModel);
TrackView::modelChanged();
}
void SampleTrackView::dragEnterEvent(QDragEnterEvent *dee)
{
StringPairDrag::processDragEnterEvent(dee, QString("samplefile"));
}
void SampleTrackView::dropEvent(QDropEvent *de)
{
QString type = StringPairDrag::decodeKey(de);
QString value = StringPairDrag::decodeValue(de);
if (type == "samplefile")
{
int trackHeadWidth = ConfigManager::inst()->value("ui", "compacttrackbuttons").toInt()==1
? DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT + TRACK_OP_WIDTH_COMPACT
: DEFAULT_SETTINGS_WIDGET_WIDTH + TRACK_OP_WIDTH;
int xPos = de->pos().x() < trackHeadWidth
? trackHeadWidth
: de->pos().x();
TimePos clipPos = trackContainerView()->fixedClips()
? TimePos(0)
: TimePos(((xPos - trackHeadWidth) / trackContainerView()->pixelsPerBar()
* TimePos::ticksPerBar()) + trackContainerView()->currentPosition()
).quantize(1.0);
auto sClip = static_cast<SampleClip*>(getTrack()->createClip(clipPos));
if (sClip) { sClip->setSampleFile(value); }
}
}
/*! \brief Create and assign a new mixer Channel for this track */
void SampleTrackView::createMixerLine()
{
int channelIndex = getGUI()->mixerView()->addNewChannel();
auto channel = Engine::mixer()->mixerChannel(channelIndex);
channel->m_name = getTrack()->name();
channel->setColor(getTrack()->color());
assignMixerLine(channelIndex);
}
/*! \brief Assign a specific mixer Channel for this track */
void SampleTrackView::assignMixerLine(int channelIndex)
{
model()->mixerChannelModel()->setValue(channelIndex);
getGUI()->mixerView()->setCurrentMixerChannel(channelIndex);
}
} // namespace lmms::gui
| 6,752
|
C++
|
.cpp
| 184
| 34.217391
| 107
| 0.744154
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,984
|
TimeLineWidget.cpp
|
LMMS_lmms/src/gui/editors/TimeLineWidget.cpp
|
/*
* TimeLineWidget.cpp - class timeLine, representing a time-line with position marker
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TimeLineWidget.h"
#include <cmath>
#include <QDomElement>
#include <QGuiApplication>
#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QTimer>
#include <QToolBar>
#include "ConfigManager.h"
#include "embed.h"
#include "GuiApplication.h"
#include "NStateButton.h"
#include "TextFloat.h"
namespace lmms::gui
{
namespace
{
constexpr int MIN_BAR_LABEL_DISTANCE = 35;
}
TimeLineWidget::TimeLineWidget(const int xoff, const int yoff, const float ppb, Song::PlayPos& pos, Timeline& timeline,
const TimePos& begin, Song::PlayMode mode, QWidget* parent) :
QWidget{parent},
m_xOffset{xoff},
m_ppb{ppb},
m_pos{pos},
m_timeline{&timeline},
m_begin{begin},
m_mode{mode}
{
setAttribute( Qt::WA_OpaquePaintEvent, true );
move( 0, yoff );
setMouseTracking(true);
auto updateTimer = new QTimer(this);
connect(updateTimer, &QTimer::timeout, this, &TimeLineWidget::updatePosition);
updateTimer->start( 1000 / 60 ); // 60 fps
connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)),
this, SLOT(update()));
}
TimeLineWidget::~TimeLineWidget()
{
delete m_hint;
}
void TimeLineWidget::setXOffset(const int x)
{
m_xOffset = x;
}
void TimeLineWidget::addToolButtons( QToolBar * _tool_bar )
{
auto autoScroll = new NStateButton(_tool_bar);
autoScroll->setGeneralToolTip(tr("Auto scrolling"));
autoScroll->addState(embed::getIconPixmap("autoscroll_stepped_on"), tr("Stepped auto scrolling"));
autoScroll->addState(embed::getIconPixmap("autoscroll_continuous_on"), tr("Continuous auto scrolling"));
autoScroll->addState(embed::getIconPixmap("autoscroll_off"), tr("Auto scrolling disabled"));
connect( autoScroll, SIGNAL(changedState(int)), this,
SLOT(toggleAutoScroll(int)));
auto loopPoints = new NStateButton(_tool_bar);
loopPoints->setGeneralToolTip( tr( "Loop points" ) );
loopPoints->addState( embed::getIconPixmap( "loop_points_off" ) );
loopPoints->addState( embed::getIconPixmap( "loop_points_on" ) );
connect(loopPoints, &NStateButton::changedState, m_timeline, &Timeline::setLoopEnabled);
connect(m_timeline, &Timeline::loopEnabledChanged, loopPoints, &NStateButton::changeState);
connect(m_timeline, &Timeline::loopEnabledChanged, this, static_cast<void (QWidget::*)()>(&QWidget::update));
loopPoints->changeState(static_cast<int>(m_timeline->loopEnabled()));
auto behaviourAtStop = new NStateButton(_tool_bar);
behaviourAtStop->addState( embed::getIconPixmap( "back_to_zero" ),
tr( "After stopping go back to beginning" )
);
behaviourAtStop->addState( embed::getIconPixmap( "back_to_start" ),
tr( "After stopping go back to "
"position at which playing was "
"started" ) );
behaviourAtStop->addState( embed::getIconPixmap( "keep_stop_position" ),
tr( "After stopping keep position" ) );
connect(behaviourAtStop, &NStateButton::changedState, m_timeline,
[timeline = m_timeline](int value) {
timeline->setStopBehaviour(static_cast<Timeline::StopBehaviour>(value));
}
);
connect(m_timeline, &Timeline::stopBehaviourChanged, behaviourAtStop,
[button = behaviourAtStop](Timeline::StopBehaviour value) {
button->changeState(static_cast<int>(value));
}
);
behaviourAtStop->changeState(static_cast<int>(m_timeline->stopBehaviour()));
_tool_bar->addWidget( autoScroll );
_tool_bar->addWidget( loopPoints );
_tool_bar->addWidget( behaviourAtStop );
}
void TimeLineWidget::updatePosition()
{
emit positionChanged(m_pos);
update();
}
void TimeLineWidget::toggleAutoScroll( int _n )
{
m_autoScroll = static_cast<AutoScrollState>( _n );
}
void TimeLineWidget::paintEvent( QPaintEvent * )
{
QPainter p( this );
// Draw background
p.fillRect( 0, 0, width(), height(), p.background() );
// Clip so that we only draw everything starting from the offset
p.setClipRect(m_xOffset, 0, width() - m_xOffset, height());
// Variables for the loop rectangle
int const loopRectMargin = getLoopRectangleVerticalPadding();
int const loopRectHeight = this->height() - 2 * loopRectMargin;
int const loopStart = markerX(m_timeline->loopBegin());
int const loopEndR = markerX(m_timeline->loopEnd());
int const loopRectWidth = loopEndR - loopStart;
bool const loopPointsActive = m_timeline->loopEnabled();
// Draw the main loop rectangle (inner fill only)
QRect outerRectangle( loopStart, loopRectMargin, loopRectWidth - 1, loopRectHeight - 1 );
p.fillRect( outerRectangle, loopPointsActive ? getActiveLoopBrush() : getInactiveLoopBrush());
// Draw the bar lines and numbers
// Activate hinting on the font
QFont font = p.font();
font.setHintingPreference( QFont::PreferFullHinting );
p.setFont(font);
int const fontAscent = p.fontMetrics().ascent();
int const fontHeight = p.fontMetrics().height();
QColor const & barLineColor = getBarLineColor();
QColor const & barNumberColor = getBarNumberColor();
bar_t barNumber = m_begin.getBar();
int const x = m_xOffset - ((static_cast<int>(m_begin * m_ppb) / TimePos::ticksPerBar()) % static_cast<int>(m_ppb));
// Double the interval between bar numbers until they are far enough appart
int barLabelInterval = 1;
while (barLabelInterval * m_ppb < MIN_BAR_LABEL_DISTANCE) { barLabelInterval *= 2; }
for( int i = 0; x + i * m_ppb < width(); ++i )
{
++barNumber;
if ((barNumber - 1) % barLabelInterval == 0)
{
const int cx = x + qRound( i * m_ppb );
p.setPen( barLineColor );
p.drawLine( cx, 5, cx, height() - 6 );
const QString s = QString::number( barNumber );
p.setPen( barNumberColor );
p.drawText( cx + 5, ((height() - fontHeight) / 2) + fontAscent, s );
}
}
// Draw the loop rectangle's outer outline
p.setPen( loopPointsActive ? getActiveLoopColor() : getInactiveLoopColor() );
p.setBrush( Qt::NoBrush );
p.drawRect( outerRectangle );
// Draw the loop rectangle's inner outline
QRect innerRectangle = outerRectangle.adjusted( 1, 1, -1, -1 );
p.setPen( loopPointsActive ? getActiveLoopInnerColor() : getInactiveLoopInnerColor() );
p.setBrush( Qt::NoBrush );
p.drawRect( innerRectangle );
// Draw loop handles if necessary
const auto handleMode = ConfigManager::inst()->value("app", "loopmarkermode") == "handles";
if (handleMode && underMouse() && QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier))
{
const auto handleWidth = std::min(m_loopHandleWidth, loopRectWidth / 2 - 1);
const auto leftHandle = QRectF(loopStart - .5, loopRectMargin - .5, handleWidth, loopRectHeight);
const auto rightHandle = QRectF(loopEndR - handleWidth - .5, loopRectMargin - .5, handleWidth, loopRectHeight);
const auto color = loopPointsActive ? m_activeLoopHandleColor : m_inactiveLoopHandleColor;
p.fillRect(leftHandle, color);
p.fillRect(rightHandle, color);
}
// Only draw the position marker if the position line is in view
if (markerX(m_pos) >= m_xOffset && markerX(m_pos) < width() - m_posMarkerPixmap.width() / 2)
{
// Let the position marker extrude to the left
p.setClipping(false);
p.setOpacity(0.6);
p.drawPixmap(markerX(m_pos) - (m_posMarkerPixmap.width() / 2),
height() - m_posMarkerPixmap.height(), m_posMarkerPixmap);
}
}
auto TimeLineWidget::getClickedTime(const int xPosition) const -> TimePos
{
// How far into the timeline we clicked, measuring pixels from the leftmost part of the editor
const auto pixelDelta = std::max(xPosition - m_xOffset, 0);
return m_begin + static_cast<int>(pixelDelta * TimePos::ticksPerBar() / m_ppb);
}
auto TimeLineWidget::getLoopAction(QMouseEvent* event) const -> TimeLineWidget::Action
{
const auto mode = ConfigManager::inst()->value("app", "loopmarkermode");
const auto xPos = event->x();
const auto button = event->button();
if (mode == "handles")
{
// Loop start and end pos, or closest edge of screen if loop extends off it
const auto leftMost = std::max(markerX(m_timeline->loopBegin()), m_xOffset);
const auto rightMost = std::min(markerX(m_timeline->loopEnd()), width());
// Distance from click to handle, positive aimed towards center of loop
const auto deltaLeft = xPos - leftMost;
const auto deltaRight = rightMost - xPos;
if (deltaLeft < 0 || deltaRight < 0) { return Action::NoAction; } // Clicked outside loop
else if (deltaLeft <= m_loopHandleWidth && deltaLeft < deltaRight) { return Action::MoveLoopBegin; }
else if (deltaRight <= m_loopHandleWidth) { return Action::MoveLoopEnd; }
else { return Action::MoveLoop; }
}
else if (mode == "closest")
{
const TimePos loopMid = (m_timeline->loopBegin() + m_timeline->loopEnd()) / 2;
return getClickedTime(xPos) < loopMid ? Action::MoveLoopBegin : Action::MoveLoopEnd;
}
else // Default to dual-button mode
{
if (button == Qt::LeftButton) { return Action::MoveLoopBegin; }
else if (button == Qt::RightButton) { return Action::MoveLoopEnd; }
return Action::NoAction;
}
}
auto TimeLineWidget::actionCursor(Action action) const -> QCursor
{
switch (action) {
case Action::MoveLoop: return Qt::SizeHorCursor;
case Action::MoveLoopBegin: return m_cursorSelectLeft;
case Action::MoveLoopEnd: return m_cursorSelectRight;
// Fall back to normal cursor if no action or action cursor not specified
default: return Qt::ArrowCursor;
}
}
void TimeLineWidget::mousePressEvent(QMouseEvent* event)
{
if (event->x() < m_xOffset) { return; }
const auto shift = event->modifiers() & Qt::ShiftModifier;
const auto ctrl = event->modifiers() & Qt::ControlModifier;
if (shift) // loop marker manipulation
{
m_action = getLoopAction(event);
setCursor(actionCursor(m_action));
if (m_action == Action::MoveLoop)
{
m_dragStartPos = getClickedTime(event->x());
m_oldLoopPos = {m_timeline->loopBegin(), m_timeline->loopEnd()};
}
}
else if (event->button() == Qt::LeftButton && ctrl) // selection
{
m_action = Action::SelectSongClip;
m_initalXSelect = event->x();
}
else if (event->button() == Qt::LeftButton && !ctrl) // move playhead
{
m_action = Action::MovePositionMarker;
}
if (m_action == Action::MoveLoopBegin || m_action == Action::MoveLoopEnd)
{
delete m_hint;
m_hint = TextFloat::displayMessage(tr("Hint"),
tr("Press <%1> to disable magnetic loop points.").arg(UI_CTRL_KEY),
embed::getIconPixmap("hint"), 0);
}
setContextMenuPolicy(m_action == Action::NoAction ? Qt::DefaultContextMenu : Qt::PreventContextMenu);
mouseMoveEvent(event);
}
void TimeLineWidget::mouseMoveEvent( QMouseEvent* event )
{
parentWidget()->update(); // essential for widgets that this timeline had taken their mouse move event from.
auto timeAtCursor = getClickedTime(event->x());
const auto control = event->modifiers() & Qt::ControlModifier;
switch( m_action )
{
case Action::MovePositionMarker:
m_pos.setTicks(timeAtCursor.getTicks());
Engine::getSong()->setToTime(timeAtCursor, m_mode);
if (!( Engine::getSong()->isPlaying()))
{
//Song::PlayMode::None is used when nothing is being played.
Engine::getSong()->setToTime(timeAtCursor, Song::PlayMode::None);
}
m_pos.setCurrentFrame( 0 );
m_pos.setJumped( true );
updatePosition();
break;
case Action::MoveLoopBegin:
case Action::MoveLoopEnd:
{
const auto otherPoint = m_action == Action::MoveLoopBegin
? m_timeline->loopEnd()
: m_timeline->loopBegin();
if (control)
{
// no ctrl-press-hint when having ctrl pressed
delete m_hint;
m_hint = nullptr;
}
else
{
timeAtCursor = timeAtCursor.quantize(m_snapSize);
}
// Catch begin == end
if (timeAtCursor == otherPoint)
{
const int offset = control ? 1 : m_snapSize * TimePos::ticksPerBar();
if (m_action == Action::MoveLoopBegin) { timeAtCursor -= offset; }
else { timeAtCursor += offset; }
}
// Update m_action so we still move the correct point even if it is
// dragged past the other.
m_action = timeAtCursor < otherPoint ? Action::MoveLoopBegin : Action::MoveLoopEnd;
m_timeline->setLoopPoints(timeAtCursor, otherPoint);
update();
break;
}
case Action::MoveLoop:
{
const TimePos dragDelta = timeAtCursor - m_dragStartPos;
auto loopPos = m_oldLoopPos;
for (auto& point : loopPos)
{
point += dragDelta;
if (!control) { point = point.quantize(m_snapSize); }
}
m_timeline->setLoopPoints(loopPos[0], loopPos[1]);
break;
}
case Action::SelectSongClip:
emit regionSelectedFromPixels( m_initalXSelect , event->x() );
break;
default:
break;
}
if (event->buttons() == Qt::NoButton)
{
setCursor(QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)
? actionCursor(getLoopAction(event))
: Qt::ArrowCursor
);
}
}
void TimeLineWidget::mouseReleaseEvent( QMouseEvent* event )
{
delete m_hint;
m_hint = nullptr;
if ( m_action == Action::SelectSongClip ) { emit selectionFinished(); }
m_action = Action::NoAction;
}
void TimeLineWidget::contextMenuEvent(QContextMenuEvent* event)
{
if (event->x() < m_xOffset) { return; }
auto menu = QMenu{};
menu.addAction(tr("Set loop begin here"), [this, event] {
auto begin = getClickedTime(event->x());
const auto end = m_timeline->loopEnd();
if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) { begin = begin.quantize(m_snapSize); }
if (begin == end) { m_timeline->setLoopEnd(end + m_snapSize * TimePos::ticksPerBar()); }
m_timeline->setLoopBegin(begin);
update();
});
menu.addAction(tr("Set loop end here"), [this, event] {
const auto begin = m_timeline->loopBegin();
auto end = getClickedTime(event->x());
if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) { end = end.quantize(m_snapSize); }
if (begin == end) { m_timeline->setLoopBegin(begin - m_snapSize * TimePos::ticksPerBar()); }
m_timeline->setLoopEnd(end);
update();
});
menu.addSeparator();
const auto loopMenu = menu.addMenu(tr("Loop edit mode (hold shift)"));
const auto loopMode = ConfigManager::inst()->value("app", "loopmarkermode", "dual");
const auto addLoopModeAction = [loopMenu, &loopMode](QString text, QString mode) {
const auto action = loopMenu->addAction(text, [mode] {
ConfigManager::inst()->setValue("app", "loopmarkermode", mode);
});
action->setCheckable(true);
if (loopMode == mode) { action->setChecked(true); }
};
addLoopModeAction(tr("Dual-button"), "dual");
addLoopModeAction(tr("Grab closest"), "closest");
addLoopModeAction(tr("Handles"), "handles");
menu.exec(event->globalPos());
}
} // namespace lmms::gui
| 15,367
|
C++
|
.cpp
| 393
| 36.437659
| 119
| 0.725315
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,985
|
Editor.cpp
|
LMMS_lmms/src/gui/editors/Editor.cpp
|
/*
* Editor.cpp - implementation of Editor class
*
* Copyright (c) 2014 Lukas W <lukaswhl/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Editor.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "Song.h"
#include "embed.h"
#include <QAction>
#include <QShortcut>
#include <QCloseEvent>
namespace lmms::gui
{
void Editor::setPauseIcon(bool displayPauseIcon)
{
// If we're playing, show a pause icon
if (displayPauseIcon)
m_playAction->setIcon(embed::getIconPixmap("pause"));
else
m_playAction->setIcon(embed::getIconPixmap("play"));
}
DropToolBar * Editor::addDropToolBarToTop(QString const & windowTitle)
{
return addDropToolBar(Qt::TopToolBarArea, windowTitle);
}
DropToolBar * Editor::addDropToolBar(Qt::ToolBarArea whereToAdd, QString const & windowTitle)
{
return addDropToolBar(this, whereToAdd, windowTitle);
}
DropToolBar * Editor::addDropToolBar(QWidget * parent, Qt::ToolBarArea whereToAdd, QString const & windowTitle)
{
auto toolBar = new DropToolBar(parent);
addToolBar(whereToAdd, toolBar);
toolBar->setMovable(false);
toolBar->setFloatable(false);
toolBar->setContextMenuPolicy(Qt::PreventContextMenu);
toolBar->setWindowTitle(windowTitle);
return toolBar;
}
void Editor::togglePlayStop()
{
if (Engine::getSong()->isPlaying())
stop();
else
play();
}
void Editor::togglePause()
{
Engine::getSong()->togglePause();
}
void Editor::toggleMaximize()
{
isMaximized() ? showNormal() : showMaximized();
}
Editor::Editor(bool record, bool stepRecord) :
m_toolBar(new DropToolBar(this)),
m_playAction(nullptr),
m_recordAction(nullptr),
m_recordAccompanyAction(nullptr),
m_toggleStepRecordingAction(nullptr),
m_stopAction(nullptr)
{
m_toolBar = addDropToolBarToTop(tr("Transport controls"));
auto addButton = [this](QAction* action, QString objectName) {
m_toolBar->addAction(action);
m_toolBar->widgetForAction(action)->setObjectName(objectName);
};
// Set up play and record actions
m_playAction = new QAction(embed::getIconPixmap("play"), tr("Play (Space)"), this);
m_stopAction = new QAction(embed::getIconPixmap("stop"), tr("Stop (Space)"), this);
m_recordAction = new QAction(embed::getIconPixmap("record"), tr("Record"), this);
m_recordAccompanyAction = new QAction(embed::getIconPixmap("record_accompany"), tr("Record while playing"), this);
m_toggleStepRecordingAction = new QAction(embed::getIconPixmap("record_step_off"), tr("Toggle Step Recording"), this);
// Set up connections
connect(m_playAction, SIGNAL(triggered()), this, SLOT(play()));
connect(m_recordAction, SIGNAL(triggered()), this, SLOT(record()));
connect(m_recordAccompanyAction, SIGNAL(triggered()), this, SLOT(recordAccompany()));
connect(m_toggleStepRecordingAction, SIGNAL(triggered()), this, SLOT(toggleStepRecording()));
connect(m_stopAction, SIGNAL(triggered()), this, SLOT(stop()));
new QShortcut(Qt::Key_Space, this, SLOT(togglePlayStop()));
new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Space), this, SLOT(togglePause()));
new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F11), this, SLOT(toggleMaximize()));
// Add actions to toolbar
addButton(m_playAction, "playButton");
if (record)
{
addButton(m_recordAction, "recordButton");
addButton(m_recordAccompanyAction, "recordAccompanyButton");
}
if(stepRecord)
{
addButton(m_toggleStepRecordingAction, "stepRecordButton");
}
addButton(m_stopAction, "stopButton");
}
QAction *Editor::playAction() const
{
return m_playAction;
}
void Editor::closeEvent(QCloseEvent * event)
{
if( parentWidget() )
{
parentWidget()->hide();
}
else
{
hide();
}
getGUI()->mainWindow()->refocus();
event->ignore();
}
DropToolBar::DropToolBar(QWidget* parent) : QToolBar(parent)
{
setAcceptDrops(true);
}
void DropToolBar::dragEnterEvent(QDragEnterEvent* event)
{
dragEntered(event);
}
void DropToolBar::dropEvent(QDropEvent* event)
{
dropped(event);
}
} // namespace lmms::gui
| 4,690
|
C++
|
.cpp
| 145
| 30.413793
| 119
| 0.7593
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,986
|
TrackContainerView.cpp
|
LMMS_lmms/src/gui/editors/TrackContainerView.cpp
|
/*
* TrackContainerView.cpp - view-component for TrackContainer
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TrackContainerView.h"
#include <QLayout>
#include <QScrollBar>
#include <QWheelEvent>
#include "TrackContainer.h"
#include "AudioEngine.h"
#include "DataFile.h"
#include "MainWindow.h"
#include "FileBrowser.h"
#include "ImportFilter.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "PatternTrack.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "TrackView.h"
#include "GuiApplication.h"
#include "PluginFactory.h"
namespace lmms
{
using namespace std;
InstrumentLoaderThread::InstrumentLoaderThread( QObject *parent, InstrumentTrack *it, QString name ) :
QThread( parent ),
m_it( it ),
m_name( name )
{
m_containerThread = thread();
}
void InstrumentLoaderThread::run()
{
Instrument *i = m_it->loadInstrument(m_name, nullptr,
true /*always DnD*/);
QObject *parent = i->parent();
i->setParent( 0 );
i->moveToThread( m_containerThread );
i->setParent( parent );
}
namespace gui
{
TrackContainerView::TrackContainerView( TrackContainer * _tc ) :
QWidget(),
ModelView( nullptr, this ),
JournallingObject(),
SerializingObjectHook(),
m_currentPosition( 0, 0 ),
m_tc( _tc ),
m_trackViews(),
m_scrollArea( new scrollArea( this ) ),
m_ppb( DEFAULT_PIXELS_PER_BAR ),
m_rubberBand( new RubberBand( m_scrollArea ) )
{
m_tc->setHook( this );
//keeps the direction of the widget, undepended on the locale
setLayoutDirection( Qt::LeftToRight );
// The main layout - by default it only contains the scroll area,
// but SongEditor uses the layout to add a TimeLineWidget on top
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing( 0 );
layout->addWidget( m_scrollArea );
// The widget that will contain all TrackViews
auto scrollContent = new QWidget;
m_scrollLayout = new QVBoxLayout( scrollContent );
m_scrollLayout->setContentsMargins(0, 0, 0, 0);
m_scrollLayout->setSpacing( 0 );
m_scrollLayout->setSizeConstraint( QLayout::SetMinAndMaxSize );
m_scrollArea->setWidget( scrollContent );
m_scrollArea->setWidgetResizable(true);
m_scrollArea->show();
m_rubberBand->hide();
m_rubberBand->setEnabled( false );
setAcceptDrops( true );
connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)),
this, SLOT(realignTracks()));
connect( m_tc, SIGNAL(trackAdded(lmms::Track*)),
this, SLOT(createTrackView(lmms::Track*)),
Qt::QueuedConnection );
}
TrackContainerView::~TrackContainerView()
{
while( !m_trackViews.empty() )
{
delete m_trackViews.takeLast();
}
}
void TrackContainerView::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
MainWindow::saveWidgetState( this, _this );
}
void TrackContainerView::loadSettings( const QDomElement & _this )
{
MainWindow::restoreWidgetState( this, _this );
}
TrackView * TrackContainerView::addTrackView( TrackView * _tv )
{
m_trackViews.push_back( _tv );
m_scrollLayout->addWidget( _tv );
connect( this, SIGNAL( positionChanged( const lmms::TimePos& ) ),
_tv->getTrackContentWidget(),
SLOT( changePosition( const lmms::TimePos& ) ) );
realignTracks();
return( _tv );
}
void TrackContainerView::removeTrackView( TrackView * _tv )
{
int index = m_trackViews.indexOf( _tv );
if( index != -1 )
{
m_trackViews.removeAt( index );
disconnect( _tv );
m_scrollLayout->removeWidget( _tv );
realignTracks();
if( Engine::getSong() )
{
Engine::getSong()->setModified();
}
}
}
void TrackContainerView::moveTrackView( TrackView * trackView, int indexTo )
{
// Can't move out of bounds
if ( indexTo >= m_trackViews.size() || indexTo < 0 ) { return; }
// Does not need to move to itself
int indexFrom = m_trackViews.indexOf( trackView );
if ( indexFrom == indexTo ) { return; }
PatternTrack::swapPatternTracks( trackView->getTrack(),
m_trackViews[indexTo]->getTrack() );
m_scrollLayout->removeWidget( trackView );
m_scrollLayout->insertWidget( indexTo, trackView );
Track * track = m_tc->m_tracks[indexFrom];
m_tc->m_tracks.erase(m_tc->m_tracks.begin() + indexFrom);
m_tc->m_tracks.insert(m_tc->m_tracks.begin() + indexTo, track);
m_trackViews.move( indexFrom, indexTo );
realignTracks();
}
void TrackContainerView::moveTrackViewUp( TrackView * trackView )
{
int index = m_trackViews.indexOf( trackView );
moveTrackView( trackView, index - 1 );
}
void TrackContainerView::moveTrackViewDown( TrackView * trackView )
{
int index = m_trackViews.indexOf( trackView );
moveTrackView( trackView, index + 1 );
}
void TrackContainerView::scrollToTrackView( TrackView * _tv )
{
if (!m_trackViews.contains(_tv))
{
qWarning("TrackContainerView::scrollToTrackView: TrackView is not owned by this");
}
else
{
int currentScrollTop = m_scrollArea->verticalScrollBar()->value();
int scrollAreaHeight = m_scrollArea->size().height();
int trackViewTop = _tv->pos().y();
int trackViewBottom = trackViewTop + _tv->size().height();
// displayed_location = widget_location - currentScrollTop
// want to make sure that the widget top has displayed location > 0,
// and widget bottom < scrollAreaHeight
// trackViewTop - scrollY > 0 && trackViewBottom - scrollY < scrollAreaHeight
// therefore scrollY < trackViewTop && scrollY > trackViewBottom - scrollAreaHeight
int newScroll = std::max( trackViewBottom-scrollAreaHeight, std::min(currentScrollTop, trackViewTop) );
m_scrollArea->verticalScrollBar()->setValue(newScroll);
}
}
void TrackContainerView::realignTracks()
{
for (const auto& trackView : m_trackViews)
{
trackView->show();
trackView->update();
}
emit tracksRealigned();
}
TrackView * TrackContainerView::createTrackView( Track * _t )
{
//m_tc->addJournalCheckPoint();
// Avoid duplicating track views
for (const auto& trackView : m_trackViews)
{
if (trackView->getTrack() == _t) { return trackView; }
}
return _t->createView( this );
}
void TrackContainerView::deleteTrackView( TrackView * _tv )
{
//m_tc->addJournalCheckPoint();
Track * t = _tv->getTrack();
removeTrackView( _tv );
delete _tv;
Engine::audioEngine()->requestChangeInModel();
delete t;
Engine::audioEngine()->doneChangeInModel();
}
const TrackView * TrackContainerView::trackViewAt( const int _y ) const
{
const int abs_y = _y + m_scrollArea->verticalScrollBar()->value();
int y_cnt = 0;
// debug code
// qDebug( "abs_y %d", abs_y );
for (const auto& trackView : m_trackViews)
{
const int y_cnt1 = y_cnt;
y_cnt += trackView->height();
if (abs_y >= y_cnt1 && abs_y < y_cnt) { return trackView; }
}
return( nullptr );
}
bool TrackContainerView::allowRubberband() const
{
return( false );
}
bool TrackContainerView::knifeMode() const
{
return false;
}
void TrackContainerView::setPixelsPerBar( int ppb )
{
m_ppb = ppb;
// tell all TrackContentWidgets to update their background tile pixmap
for (const auto& trackView : m_trackViews)
{
trackView->getTrackContentWidget()->updateBackground();
}
}
void TrackContainerView::clearAllTracks()
{
while( !m_trackViews.empty() )
{
TrackView * tv = m_trackViews.takeLast();
Track * t = tv->getTrack();
delete tv;
delete t;
}
}
void TrackContainerView::dragEnterEvent( QDragEnterEvent * _dee )
{
StringPairDrag::processDragEnterEvent( _dee,
QString( "presetfile,pluginpresetfile,samplefile,instrument,"
"importedproject,soundfontfile,patchfile,vstpluginfile,projectfile,"
"track_%1,track_%2" ).
arg( static_cast<int>(Track::Type::Instrument) ).
arg( static_cast<int>(Track::Type::Sample) ) );
}
void TrackContainerView::stopRubberBand()
{
m_rubberBand->hide();
m_rubberBand->setEnabled( false );
}
void TrackContainerView::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString value = StringPairDrag::decodeValue( _de );
if( type == "instrument" )
{
auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, m_tc));
auto ilt = new InstrumentLoaderThread(this, it, value);
ilt->start();
//it->toggledInstrumentTrackButton( true );
_de->accept();
}
else if( type == "samplefile" || type == "pluginpresetfile"
|| type == "soundfontfile" || type == "vstpluginfile"
|| type == "patchfile" )
{
auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, m_tc));
PluginFactory::PluginInfoAndKey piakn =
getPluginFactory()->pluginSupportingExtension(FileItem::extension(value));
Instrument * i = it->loadInstrument(piakn.info.name(), &piakn.key);
i->loadFile( value );
//it->toggledInstrumentTrackButton( true );
_de->accept();
}
else if( type == "presetfile" )
{
DataFile dataFile( value );
auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, m_tc));
it->loadPreset(dataFile.content().toElement());
//it->toggledInstrumentTrackButton( true );
_de->accept();
}
else if( type == "importedproject" )
{
ImportFilter::import( value, m_tc );
_de->accept();
}
else if( type == "projectfile")
{
if( getGUI()->mainWindow()->mayChangeProject(true) )
{
Engine::getSong()->loadProject( value );
}
_de->accept();
}
else if( type.left( 6 ) == "track_" )
{
DataFile dataFile( value.toUtf8() );
Track::create( dataFile.content().firstChild().toElement(), m_tc );
_de->accept();
}
}
RubberBand *TrackContainerView::rubberBand() const
{
return m_rubberBand;
}
TrackContainerView::scrollArea::scrollArea( TrackContainerView * _parent ) :
QScrollArea( _parent ),
m_trackContainerView( _parent )
{
setFrameStyle( QFrame::NoFrame );
setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
}
void TrackContainerView::scrollArea::wheelEvent( QWheelEvent * _we )
{
// always pass wheel-event to parent-widget (song-editor
// pattern-editor etc.) because they might want to use it for zooming
// or scrolling left/right if a modifier-key is pressed, otherwise
// they do not accept it and we pass it up to QScrollArea
m_trackContainerView->wheelEvent( _we );
if( !_we->isAccepted() )
{
QScrollArea::wheelEvent( _we );
}
}
unsigned int TrackContainerView::totalHeightOfTracks() const
{
unsigned int heightSum = 0;
for (auto & trackView : m_trackViews)
{
heightSum += trackView->getTrack()->getHeight();
}
return heightSum;
}
} // namespace gui
} // namespace lmms
| 11,246
|
C++
|
.cpp
| 360
| 28.833333
| 105
| 0.730995
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,987
|
SongEditor.cpp
|
LMMS_lmms/src/gui/editors/SongEditor.cpp
|
/*
* SongEditor.cpp - basic window for song-editing
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SongEditor.h"
#include <cmath>
#include <QAction>
#include <QKeyEvent>
#include <QLabel>
#include <QMdiArea>
#include <QScrollBar>
#include <QSlider>
#include <QTimeLine>
#include "ActionGroup.h"
#include "AudioDevice.h"
#include "AudioEngine.h"
#include "AutomatableSlider.h"
#include "ClipView.h"
#include "ComboBox.h"
#include "ConfigManager.h"
#include "CPULoadWidget.h"
#include "DeprecationHelper.h"
#include "embed.h"
#include "GuiApplication.h"
#include "LcdSpinBox.h"
#include "MainWindow.h"
#include "MeterDialog.h"
#include "Oscilloscope.h"
#include "PianoRoll.h"
#include "PositionLine.h"
#include "SubWindow.h"
#include "TextFloat.h"
#include "TimeDisplayWidget.h"
#include "TimeLineWidget.h"
#include "TrackView.h"
namespace lmms::gui
{
namespace
{
constexpr int MIN_PIXELS_PER_BAR = 4;
constexpr int MAX_PIXELS_PER_BAR = 400;
constexpr int ZOOM_STEPS = 200;
constexpr std::array SNAP_SIZES{8.f, 4.f, 2.f, 1.f, 1/2.f, 1/4.f, 1/8.f, 1/16.f};
constexpr std::array PROPORTIONAL_SNAP_SIZES{64.f, 32.f, 16.f, 8.f, 4.f, 2.f, 1.f, 1/2.f, 1/4.f, 1/8.f, 1/16.f, 1/32.f, 1/64.f};
}
SongEditor::SongEditor( Song * song ) :
TrackContainerView( song ),
m_song( song ),
m_zoomingModel(new IntModel(calculateZoomSliderValue(DEFAULT_PIXELS_PER_BAR), 0, ZOOM_STEPS, nullptr, tr("Zoom"))),
m_snappingModel(new ComboBoxModel()),
m_proportionalSnap( false ),
m_scrollBack( false ),
m_smoothScroll( ConfigManager::inst()->value( "ui", "smoothscroll" ).toInt() ),
m_mode(EditMode::Draw),
m_origin(),
m_scrollPos(),
m_mousePos(),
m_rubberBandStartTrackview(0),
m_rubberbandStartTimePos(0),
m_rubberbandPixelsPerBar(DEFAULT_PIXELS_PER_BAR),
m_trackHeadWidth(ConfigManager::inst()->value("ui", "compacttrackbuttons").toInt()==1
? DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT + TRACK_OP_WIDTH_COMPACT
: DEFAULT_SETTINGS_WIDGET_WIDTH + TRACK_OP_WIDTH),
m_selectRegion(false)
{
m_zoomingModel->setParent(this);
m_snappingModel->setParent(this);
m_timeLine = new TimeLineWidget(m_trackHeadWidth, 32, pixelsPerBar(),
m_song->getPlayPos(Song::PlayMode::Song),
m_song->getTimeline(Song::PlayMode::Song),
m_currentPosition, Song::PlayMode::Song, this
);
connect(this, &TrackContainerView::positionChanged, m_timeLine, &TimeLineWidget::updatePosition);
connect( m_timeLine, SIGNAL( positionChanged( const lmms::TimePos& ) ),
this, SLOT( updatePosition( const lmms::TimePos& ) ) );
connect( m_timeLine, SIGNAL(regionSelectedFromPixels(int,int)),
this, SLOT(selectRegionFromPixels(int,int)));
connect( m_timeLine, SIGNAL(selectionFinished()),
this, SLOT(stopRubberBand()));
// when tracks realign, adjust height of position line
connect(this, &TrackContainerView::tracksRealigned, this, &SongEditor::updatePositionLine);
m_positionLine = new PositionLine(this);
static_cast<QVBoxLayout *>( layout() )->insertWidget( 1, m_timeLine );
connect( m_song, SIGNAL(playbackStateChanged()),
m_positionLine, SLOT(update()));
// When zoom changes, update position line
// But we must convert pixels per bar to a zoom factor where 1.0 is 100%
connect(this, &SongEditor::pixelsPerBarChanged, m_positionLine,
[this]() { m_positionLine->zoomChange(pixelsPerBar() / float(DEFAULT_PIXELS_PER_BAR)); });
// Ensure loop markers snap to same increments as clips. Zoom & proportional
// snap changes are handled in zoomingChanged() and toggleProportionalSnap()
connect(m_snappingModel, &ComboBoxModel::dataChanged,
[this]() { m_timeLine->setSnapSize(getSnapSize()); });
// add some essential widgets to global tool-bar
QWidget * tb = getGUI()->mainWindow()->toolBar();
getGUI()->mainWindow()->addSpacingToToolBar( 40 );
m_tempoSpinBox = new LcdSpinBox( 3, tb, tr( "Tempo" ) );
m_tempoSpinBox->setModel( &m_song->m_tempoModel );
m_tempoSpinBox->setLabel( tr( "TEMPO" ) );
m_tempoSpinBox->setToolTip(tr("Tempo in BPM"));
int tempoSpinBoxCol = getGUI()->mainWindow()->addWidgetToToolBar( m_tempoSpinBox, 0 );
getGUI()->mainWindow()->addWidgetToToolBar( new TimeDisplayWidget, 1, tempoSpinBoxCol );
getGUI()->mainWindow()->addSpacingToToolBar( 10 );
m_timeSigDisplay = new MeterDialog( this, true );
m_timeSigDisplay->setModel( &m_song->m_timeSigModel );
getGUI()->mainWindow()->addWidgetToToolBar( m_timeSigDisplay );
getGUI()->mainWindow()->addSpacingToToolBar( 10 );
auto master_vol_lbl = new QLabel(tb);
master_vol_lbl->setPixmap( embed::getIconPixmap( "master_volume" ) );
m_masterVolumeSlider = new AutomatableSlider( tb,
tr( "Master volume" ) );
m_masterVolumeSlider->setModel( &m_song->m_masterVolumeModel );
m_masterVolumeSlider->setOrientation( Qt::Vertical );
m_masterVolumeSlider->setPageStep( 1 );
m_masterVolumeSlider->setTickPosition( QSlider::TicksLeft );
m_masterVolumeSlider->setFixedSize( 26, 60 );
m_masterVolumeSlider->setTickInterval( 50 );
m_masterVolumeSlider->setToolTip(tr("Master volume"));
connect( m_masterVolumeSlider, SIGNAL(logicValueChanged(int)), this,
SLOT(setMasterVolume(int)));
connect( m_masterVolumeSlider, SIGNAL(sliderPressed()), this,
SLOT(showMasterVolumeFloat()));
connect( m_masterVolumeSlider, SIGNAL(logicSliderMoved(int)), this,
SLOT(updateMasterVolumeFloat(int)));
connect( m_masterVolumeSlider, SIGNAL(sliderReleased()), this,
SLOT(hideMasterVolumeFloat()));
m_mvsStatus = new TextFloat;
m_mvsStatus->setTitle(tr("Master volume"));
m_mvsStatus->setPixmap(embed::getIconPixmap("master_volume"));
getGUI()->mainWindow()->addWidgetToToolBar( master_vol_lbl );
getGUI()->mainWindow()->addWidgetToToolBar( m_masterVolumeSlider );
getGUI()->mainWindow()->addSpacingToToolBar( 10 );
auto master_pitch_lbl = new QLabel(tb);
master_pitch_lbl->setPixmap( embed::getIconPixmap( "master_pitch" ) );
master_pitch_lbl->setFixedHeight( 64 );
m_masterPitchSlider = new AutomatableSlider( tb, tr( "Global transposition" ) );
m_masterPitchSlider->setModel( &m_song->m_masterPitchModel );
m_masterPitchSlider->setOrientation( Qt::Vertical );
m_masterPitchSlider->setPageStep( 1 );
m_masterPitchSlider->setTickPosition( QSlider::TicksLeft );
m_masterPitchSlider->setFixedSize( 26, 60 );
m_masterPitchSlider->setTickInterval( 12 );
m_masterPitchSlider->setToolTip(tr("Global transposition"));
connect( m_masterPitchSlider, SIGNAL(logicValueChanged(int)), this,
SLOT(setMasterPitch(int)));
connect( m_masterPitchSlider, SIGNAL(sliderPressed()), this,
SLOT(showMasterPitchFloat()));
connect( m_masterPitchSlider, SIGNAL(logicSliderMoved(int)), this,
SLOT(updateMasterPitchFloat(int)));
connect( m_masterPitchSlider, SIGNAL(sliderReleased()), this,
SLOT(hideMasterPitchFloat()));
m_mpsStatus = new TextFloat;
m_mpsStatus->setTitle( tr( "Global transposition" ) );
m_mpsStatus->setPixmap( embed::getIconPixmap( "master_pitch" ) );
getGUI()->mainWindow()->addWidgetToToolBar( master_pitch_lbl );
getGUI()->mainWindow()->addWidgetToToolBar( m_masterPitchSlider );
getGUI()->mainWindow()->addSpacingToToolBar( 10 );
// create widget for oscilloscope- and cpu-load-widget
auto vc_w = new QWidget(tb);
auto vcw_layout = new QVBoxLayout(vc_w);
vcw_layout->setContentsMargins(0, 0, 0, 0);
vcw_layout->setSpacing( 0 );
vcw_layout->addStretch();
vcw_layout->addWidget( new Oscilloscope( vc_w ) );
vcw_layout->addWidget( new CPULoadWidget( vc_w ) );
vcw_layout->addStretch();
getGUI()->mainWindow()->addWidgetToToolBar( vc_w );
static_cast<QVBoxLayout *>( layout() )->insertWidget( 0, m_timeLine );
m_leftRightScroll = new QScrollBar( Qt::Horizontal, this );
m_leftRightScroll->setMinimum(0);
m_leftRightScroll->setMaximum(0);
m_leftRightScroll->setSingleStep(1);
m_leftRightScroll->setPageStep(20 * TimePos::ticksPerBar());
static_cast<QVBoxLayout *>( layout() )->addWidget( m_leftRightScroll );
connect( m_leftRightScroll, SIGNAL(valueChanged(int)),
this, SLOT(scrolled(int)));
connect( m_song, SIGNAL(lengthChanged(int)),
this, SLOT(updateScrollBar(int)));
connect(m_leftRightScroll, SIGNAL(valueChanged(int)),this, SLOT(updateRubberband()));
connect(contentWidget()->verticalScrollBar(), SIGNAL(valueChanged(int)),this, SLOT(updateRubberband()));
connect(m_timeLine, SIGNAL(selectionFinished()), this, SLOT(stopSelectRegion()));
//zoom connects
connect(m_zoomingModel, SIGNAL(dataChanged()), this, SLOT(zoomingChanged()));
// Set up snapping model
for (float bars : SNAP_SIZES)
{
if (bars > 1.0f)
{
m_snappingModel->addItem(QString("%1 Bars").arg(bars));
}
else if (bars == 1.0f)
{
m_snappingModel->addItem( "1 Bar" );
}
else
{
m_snappingModel->addItem(QString("1/%1 Bar").arg(1 / bars));
}
}
m_snappingModel->setInitValue( m_snappingModel->findText( "1/4 Bar" ) );
setFocusPolicy( Qt::StrongFocus );
setFocus();
}
void SongEditor::saveSettings( QDomDocument& doc, QDomElement& element )
{
MainWindow::saveWidgetState( parentWidget(), element );
}
void SongEditor::loadSettings( const QDomElement& element )
{
MainWindow::restoreWidgetState(parentWidget(), element);
}
/*! \brief Return grid size as number of bars */
float SongEditor::getSnapSize() const
{
float snapSize = SNAP_SIZES[m_snappingModel->value()];
// If proportional snap is on, we snap to finer values when zoomed in
if (m_proportionalSnap)
{
// Finds the closest available snap size
const float optimalSize = snapSize * DEFAULT_PIXELS_PER_BAR / pixelsPerBar();
return *std::min_element(PROPORTIONAL_SNAP_SIZES.begin(), PROPORTIONAL_SNAP_SIZES.end(), [optimalSize](float a, float b)
{
return std::abs(a - optimalSize) < std::abs(b - optimalSize);
});
}
return snapSize;
}
QString SongEditor::getSnapSizeString() const
{
float bars = getSnapSize();
if (bars < 1)
{
return QString(tr("1/%1 Bar")).arg(round(1 / bars));
}
else if (bars >= 2)
{
return QString(tr("%1 Bars")).arg(bars);
}
else
{
return QString("1 Bar");
}
}
void SongEditor::scrolled( int new_pos )
{
update();
emit positionChanged(m_currentPosition = TimePos(new_pos));
}
void SongEditor::selectRegionFromPixels(int xStart, int xEnd)
{
if (!m_selectRegion)
{
m_selectRegion = true;
//deselect all clips
for (auto &it : findChildren<selectableObject *>()) { it->setSelected(false); }
rubberBand()->setEnabled(true);
rubberBand()->show();
//we save the position of scrollbars, mouse position and zooming level
m_origin = QPoint(xStart, 0);
m_scrollPos = QPoint(m_leftRightScroll->value(), contentWidget()->verticalScrollBar()->value());
m_rubberbandPixelsPerBar = pixelsPerBar();
//calculate the song position where the mouse was clicked
m_rubberbandStartTimePos = TimePos((xStart - m_trackHeadWidth)
/ pixelsPerBar() * TimePos::ticksPerBar())
+ m_currentPosition;
m_rubberBandStartTrackview = 0;
}
//the current mouse position within the borders of song editor
m_mousePos = QPoint(qMax(m_trackHeadWidth, qMin(xEnd, width()))
, std::numeric_limits<int>::max());
updateRubberband();
}
void SongEditor::stopSelectRegion()
{
m_selectRegion = false;
}
void SongEditor::updateRubberband()
{
if (rubberBandActive())
{
int originX = m_origin.x();
//take care of the zooming
if (m_rubberbandPixelsPerBar != pixelsPerBar())
{
originX = m_trackHeadWidth + (originX - m_trackHeadWidth) * pixelsPerBar() / m_rubberbandPixelsPerBar;
}
//take care of the scrollbar position
int hs = (m_leftRightScroll->value() - m_scrollPos.x()) * pixelsPerBar() / TimePos::ticksPerBar();
int vs = contentWidget()->verticalScrollBar()->value() - m_scrollPos.y();
//the adjusted origin point
QPoint origin = QPoint(qMax(originX - hs, m_trackHeadWidth), m_origin.y() - vs);
//paint the rubber band rect
rubberBand()->setGeometry(QRect(origin,
contentWidget()->mapFromParent(QPoint(m_mousePos.x(), m_mousePos.y()))
).normalized());
//the index of the TrackView the mouse is hover
int rubberBandTrackview = trackIndexFromSelectionPoint(m_mousePos.y());
//the time position the mouse is hover
TimePos rubberbandTimePos = TimePos((qMin(m_mousePos.x(), width()) - m_trackHeadWidth)
/ pixelsPerBar() * TimePos::ticksPerBar())
+ m_currentPosition;
//are clips in the rect of selection?
for (auto &it : findChildren<selectableObject *>())
{
auto clip = dynamic_cast<ClipView*>(it);
if (clip)
{
auto indexOfTrackView = trackViews().indexOf(clip->getTrackView());
bool isBeetweenRubberbandViews = indexOfTrackView >= qMin(m_rubberBandStartTrackview, rubberBandTrackview)
&& indexOfTrackView <= qMax(m_rubberBandStartTrackview, rubberBandTrackview);
bool isBeetweenRubberbandTimePos = clip->getClip()->endPosition() >= qMin(m_rubberbandStartTimePos, rubberbandTimePos)
&& clip->getClip()->startPosition() <= qMax(m_rubberbandStartTimePos, rubberbandTimePos);
it->setSelected(isBeetweenRubberbandViews && isBeetweenRubberbandTimePos);
}
}
}
}
void SongEditor::setEditMode( EditMode mode )
{
m_mode = mode;
}
void SongEditor::setEditModeDraw()
{
setEditMode(EditMode::Draw);
}
void SongEditor::setEditModeKnife()
{
setEditMode(EditMode::Knife);
}
void SongEditor::setEditModeSelect()
{
setEditMode(EditMode::Select);
}
void SongEditor::toggleProportionalSnap()
{
m_proportionalSnap = !m_proportionalSnap;
m_timeLine->setSnapSize(getSnapSize());
emit proportionalSnapChanged();
}
void SongEditor::keyPressEvent( QKeyEvent * ke )
{
bool isShiftPressed = ke->modifiers() & Qt::ShiftModifier;
if( isShiftPressed &&
( ke->key() == Qt::Key_Insert || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return ) )
{
m_song->insertBar();
}
else if( isShiftPressed &&
( ke->key() == Qt::Key_Delete || ke->key() == Qt::Key_Backspace ) )
{
m_song->removeBar();
}
else if( ke->key() == Qt::Key_Left )
{
tick_t t = m_song->currentTick() - TimePos::ticksPerBar();
if( t >= 0 )
{
m_song->setPlayPos( t, Song::PlayMode::Song );
}
}
else if( ke->key() == Qt::Key_Right )
{
tick_t t = m_song->currentTick() + TimePos::ticksPerBar();
if( t < MaxSongLength )
{
m_song->setPlayPos( t, Song::PlayMode::Song );
}
}
else if( ke->key() == Qt::Key_Home )
{
m_song->setPlayPos( 0, Song::PlayMode::Song );
}
else if( ke->key() == Qt::Key_Delete || ke->key() == Qt::Key_Backspace )
{
QVector<selectableObject *> so = selectedObjects();
for (const auto& selectedClip : so)
{
auto clipv = dynamic_cast<ClipView*>(selectedClip);
clipv->remove();
}
}
else if( ke->key() == Qt::Key_A && ke->modifiers() & Qt::ControlModifier )
{
selectAllClips( !isShiftPressed );
}
else if( ke->key() == Qt::Key_Escape )
{
selectAllClips( false );
}
else if (ke->key() == Qt::Key_0 && ke->modifiers() & Qt::ControlModifier)
{
m_zoomingModel->reset();
}
else
{
QWidget::keyPressEvent(ke);
}
}
void SongEditor::adjustLeftRightScoll(int value)
{
m_leftRightScroll->setValue(m_leftRightScroll->value()
- value * DEFAULT_PIXELS_PER_BAR / pixelsPerBar());
}
void SongEditor::wheelEvent( QWheelEvent * we )
{
if ((we->modifiers() & Qt::ControlModifier) && (position(we).x() > m_trackHeadWidth))
{
int x = position(we).x() - m_trackHeadWidth;
// tick based on the mouse x-position where the scroll wheel was used
int tick = x / pixelsPerBar() * TimePos::ticksPerBar();
// move zoom slider (pixelsPerBar will change automatically)
int step = we->modifiers() & Qt::ShiftModifier ? 1 : 5;
// when Alt is pressed, wheelEvent returns delta for x coordinate (mimics horizontal mouse wheel)
int direction = (we->angleDelta().y() + we->angleDelta().x()) > 0 ? 1 : -1;
m_zoomingModel->incValue(step * direction);
// scroll to zooming around cursor's tick
int newTick = static_cast<int>(x / pixelsPerBar() * TimePos::ticksPerBar());
m_leftRightScroll->setValue(m_leftRightScroll->value() + tick - newTick);
// update timeline
m_timeLine->setPixelsPerBar(pixelsPerBar());
// and make sure, all Clip's are resized and relocated
realignTracks();
}
// FIXME: Reconsider if determining orientation is necessary in Qt6.
else if (std::abs(we->angleDelta().x()) > std::abs(we->angleDelta().y())) // scrolling is horizontal
{
adjustLeftRightScoll(we->angleDelta().x());
}
else if (we->modifiers() & Qt::ShiftModifier)
{
adjustLeftRightScoll(we->angleDelta().y());
}
else
{
we->ignore();
return;
}
we->accept();
}
void SongEditor::closeEvent( QCloseEvent * ce )
{
if( parentWidget() )
{
parentWidget()->hide();
}
else
{
hide();
}
ce->ignore();
}
void SongEditor::mousePressEvent(QMouseEvent *me)
{
if (allowRubberband())
{
//we save the position of scrollbars, mouse position and zooming level
m_scrollPos = QPoint(m_leftRightScroll->value(), contentWidget()->verticalScrollBar()->value());
m_origin = contentWidget()->mapFromParent(QPoint(me->pos().x(), me->pos().y()));
m_rubberbandPixelsPerBar = pixelsPerBar();
//paint the rubberband
rubberBand()->setEnabled(true);
rubberBand()->setGeometry(QRect(m_origin, QSize()));
rubberBand()->show();
//the trackView(index) and the time position where the mouse was clicked
m_rubberBandStartTrackview = trackIndexFromSelectionPoint(me->y());
m_rubberbandStartTimePos = TimePos((me->x() - m_trackHeadWidth)
/ pixelsPerBar() * TimePos::ticksPerBar())
+ m_currentPosition;
}
QWidget::mousePressEvent(me);
}
void SongEditor::mouseMoveEvent(QMouseEvent *me)
{
m_mousePos = me->pos();
updateRubberband();
QWidget::mouseMoveEvent(me);
}
void SongEditor::mouseReleaseEvent(QMouseEvent *me)
{
rubberBand()->hide();
rubberBand()->setEnabled(false);
QWidget::mouseReleaseEvent(me);
}
void SongEditor::setMasterVolume( int new_val )
{
updateMasterVolumeFloat( new_val );
if (!m_mvsStatus->isVisible() && !m_song->m_loadingProject
&& m_masterVolumeSlider->showStatus() )
{
m_mvsStatus->moveGlobal(m_masterVolumeSlider,
QPoint( m_masterVolumeSlider->width() + 2, -2 ) );
m_mvsStatus->setVisibilityTimeOut(1000);
}
Engine::audioEngine()->setMasterGain( new_val / 100.0f );
}
void SongEditor::showMasterVolumeFloat( void )
{
m_mvsStatus->moveGlobal(m_masterVolumeSlider,
QPoint( m_masterVolumeSlider->width() + 2, -2 ) );
m_mvsStatus->show();
updateMasterVolumeFloat( m_song->m_masterVolumeModel.value() );
}
void SongEditor::updateMasterVolumeFloat( int new_val )
{
m_mvsStatus->setText(tr("Value: %1%").arg(new_val));
}
void SongEditor::hideMasterVolumeFloat( void )
{
m_mvsStatus->hide();
}
void SongEditor::setMasterPitch( int new_val )
{
updateMasterPitchFloat( new_val );
if( m_mpsStatus->isVisible() == false && m_song->m_loadingProject == false
&& m_masterPitchSlider->showStatus() )
{
m_mpsStatus->moveGlobal( m_masterPitchSlider,
QPoint( m_masterPitchSlider->width() + 2, -2 ) );
m_mpsStatus->setVisibilityTimeOut( 1000 );
}
}
void SongEditor::showMasterPitchFloat( void )
{
m_mpsStatus->moveGlobal( m_masterPitchSlider,
QPoint( m_masterPitchSlider->width() + 2, -2 ) );
m_mpsStatus->show();
updateMasterPitchFloat( m_song->m_masterPitchModel.value() );
}
void SongEditor::updateMasterPitchFloat( int new_val )
{
m_mpsStatus->setText( tr( "Value: %1 keys").arg( new_val ) );
}
void SongEditor::hideMasterPitchFloat( void )
{
m_mpsStatus->hide();
}
void SongEditor::updateScrollBar(int len)
{
m_leftRightScroll->setMaximum(len * TimePos::ticksPerBar());
}
static inline void animateScroll( QScrollBar *scrollBar, int newVal, bool smoothScroll )
{
if( smoothScroll == false )
{
scrollBar->setValue( newVal );
}
else
{
// do smooth scroll animation using QTimeLine
auto t = scrollBar->findChild<QTimeLine*>();
if( t == nullptr )
{
t = new QTimeLine( 600, scrollBar );
t->setFrameRange( scrollBar->value(), newVal );
t->connect( t, SIGNAL(finished()), SLOT(deleteLater()));
scrollBar->connect( t, SIGNAL(frameChanged(int)), SLOT(setValue(int)));
t->start();
}
else
{
// smooth scrolling is still active, therefore just update the end frame
t->setEndFrame( newVal );
}
}
}
void SongEditor::updatePosition( const TimePos & t )
{
const bool compactTrackButtons = ConfigManager::inst()->value("ui", "compacttrackbuttons").toInt();
const auto widgetWidth = compactTrackButtons ? DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT : DEFAULT_SETTINGS_WIDGET_WIDTH;
const auto trackOpWidth = compactTrackButtons ? TRACK_OP_WIDTH_COMPACT : TRACK_OP_WIDTH;
if ((m_song->isPlaying() && m_song->m_playMode == Song::PlayMode::Song)
|| m_scrollBack)
{
m_smoothScroll = ConfigManager::inst()->value( "ui", "smoothscroll" ).toInt();
const int w = width() - widgetWidth
- trackOpWidth
- contentWidget()->verticalScrollBar()->width(); // width of right scrollbar
if (m_timeLine->autoScroll() == TimeLineWidget::AutoScrollState::Stepped)
{
const auto nextPosition = m_currentPosition + w * TimePos::ticksPerBar() / pixelsPerBar();
if (t > nextPosition || t < m_currentPosition)
{
animateScroll(m_leftRightScroll, t.getTicks(), m_smoothScroll);
}
}
else if (m_timeLine->autoScroll() == TimeLineWidget::AutoScrollState::Continuous)
{
m_leftRightScroll->setValue(std::max(t.getTicks() - w * TimePos::ticksPerBar() / pixelsPerBar() / 2, 0.0f));
}
m_scrollBack = false;
}
const int x = m_timeLine->markerX(t);
if( x >= trackOpWidth + widgetWidth -1 )
{
m_positionLine->show();
m_positionLine->move( x-( m_positionLine->width() - 1 ), m_timeLine->height() );
}
else
{
m_positionLine->hide();
}
updatePositionLine();
}
void SongEditor::updatePositionLine()
{
m_positionLine->setFixedHeight(totalHeightOfTracks());
}
//! Convert zoom slider's value to bar width in pixels
int SongEditor::calculatePixelsPerBar() const
{
// What we need to raise 2 by to get MIN_PIXELS_PER_BAR and MAX_PIXELS_PER_BAR
static const double minExp = std::log2(MIN_PIXELS_PER_BAR);
static const double maxExp = std::log2(MAX_PIXELS_PER_BAR);
static const double stepsInv = 1 / static_cast<double>(ZOOM_STEPS) * (maxExp - minExp);
double exponent = m_zoomingModel->value() * stepsInv + minExp;
double ppb = std::exp2(exponent);
return static_cast<int>(std::round(ppb));
}
//! Convert bar width in pixels to zoom slider value
int SongEditor::calculateZoomSliderValue(int pixelsPerBar) const
{
// What we need to raise 2 by to get MIN_PIXELS_PER_BAR and MAX_PIXELS_PER_BAR
static const double minExp = std::log2(MIN_PIXELS_PER_BAR);
static const double maxExp = std::log2(MAX_PIXELS_PER_BAR);
double exponent = std::log2(pixelsPerBar);
double sliderValue = (exponent - minExp) / (maxExp - minExp) * ZOOM_STEPS;
return static_cast<int>(std::round(sliderValue));
}
void SongEditor::zoomingChanged()
{
int ppb = calculatePixelsPerBar();
setPixelsPerBar(ppb);
m_timeLine->setPixelsPerBar(ppb);
realignTracks();
updateRubberband();
m_timeLine->setSnapSize(getSnapSize());
emit pixelsPerBarChanged(ppb);
}
void SongEditor::selectAllClips( bool select )
{
QVector<selectableObject *> so = select ? rubberBand()->selectableObjects() : rubberBand()->selectedObjects();
for( int i = 0; i < so.count(); ++i )
{
so.at(i)->setSelected( select );
}
}
bool SongEditor::allowRubberband() const
{
return m_mode == EditMode::Select;
}
bool SongEditor::knifeMode() const
{
return m_mode == EditMode::Knife;
}
int SongEditor::trackIndexFromSelectionPoint(int yPos)
{
const TrackView * tv = trackViewAt(yPos - m_timeLine->height());
return tv ? indexOfTrackView(tv)
: yPos < m_timeLine->height() ? 0
: trackViews().count();
}
int SongEditor::indexOfTrackView(const TrackView *tv)
{
return static_cast<int>(std::distance(trackViews().begin(),
std::find(trackViews().begin(), trackViews().end(), tv)));
}
ComboBoxModel *SongEditor::snappingModel() const
{
return m_snappingModel;
}
SongEditorWindow::SongEditorWindow(Song* song) :
Editor(Engine::audioEngine()->audioDev()->supportsCapture(), false),
m_editor(new SongEditor(song)),
m_crtlAction( nullptr ),
m_snapSizeLabel( new QLabel( m_toolBar ) )
{
setWindowTitle( tr( "Song-Editor" ) );
setWindowIcon( embed::getIconPixmap( "songeditor" ) );
setCentralWidget(m_editor);
setAcceptDrops(true);
m_toolBar->setAcceptDrops(true);
connect(m_toolBar, SIGNAL(dragEntered(QDragEnterEvent*)), m_editor, SLOT(dragEnterEvent(QDragEnterEvent*)));
connect(m_toolBar, SIGNAL(dropped(QDropEvent*)), m_editor, SLOT(dropEvent(QDropEvent*)));
// Set up buttons
m_playAction->setToolTip(tr("Play song (Space)"));
m_recordAction->setToolTip(tr("Record samples from Audio-device"));
m_recordAccompanyAction->setToolTip(tr("Record samples from Audio-device while playing song or pattern track"));
m_stopAction->setToolTip(tr( "Stop song (Space)" ));
// Track actions
DropToolBar *trackActionsToolBar = addDropToolBarToTop(tr("Track actions"));
m_addPatternTrackAction = new QAction(embed::getIconPixmap("add_pattern_track"),
tr("Add pattern-track"), this);
m_addSampleTrackAction = new QAction(embed::getIconPixmap("add_sample_track"),
tr("Add sample-track"), this);
m_addAutomationTrackAction = new QAction(embed::getIconPixmap("add_automation"),
tr("Add automation-track"), this);
connect(m_addPatternTrackAction, SIGNAL(triggered()), m_editor->m_song, SLOT(addPatternTrack()));
connect(m_addSampleTrackAction, SIGNAL(triggered()), m_editor->m_song, SLOT(addSampleTrack()));
connect(m_addAutomationTrackAction, SIGNAL(triggered()), m_editor->m_song, SLOT(addAutomationTrack()));
trackActionsToolBar->addAction( m_addPatternTrackAction );
trackActionsToolBar->addAction( m_addSampleTrackAction );
trackActionsToolBar->addAction( m_addAutomationTrackAction );
// Edit actions
DropToolBar *editActionsToolBar = addDropToolBarToTop(tr("Edit actions"));
m_editModeGroup = new ActionGroup(this);
m_drawModeAction = m_editModeGroup->addAction(embed::getIconPixmap("edit_draw"), tr("Draw mode"));
m_knifeModeAction = m_editModeGroup->addAction(embed::getIconPixmap("edit_knife"), tr("Knife mode (split sample clips)"));
m_selectModeAction = m_editModeGroup->addAction(embed::getIconPixmap("edit_select"), tr("Edit mode (select and move)"));
m_drawModeAction->setChecked(true);
connect(m_drawModeAction, SIGNAL(triggered()), m_editor, SLOT(setEditModeDraw()));
connect(m_knifeModeAction, SIGNAL(triggered()), m_editor, SLOT(setEditModeKnife()));
connect(m_selectModeAction, SIGNAL(triggered()), m_editor, SLOT(setEditModeSelect()));
editActionsToolBar->addAction( m_drawModeAction );
editActionsToolBar->addAction( m_knifeModeAction );
editActionsToolBar->addAction( m_selectModeAction );
DropToolBar *timeLineToolBar = addDropToolBarToTop(tr("Timeline controls"));
m_editor->m_timeLine->addToolButtons(timeLineToolBar);
DropToolBar *insertActionsToolBar = addDropToolBarToTop(tr("Bar insert controls"));
m_insertBarAction = new QAction(embed::getIconPixmap("insert_bar"), tr("Insert bar"), this);
m_removeBarAction = new QAction(embed::getIconPixmap("remove_bar"), tr("Remove bar"), this);
insertActionsToolBar->addAction( m_insertBarAction );
insertActionsToolBar->addAction( m_removeBarAction );
connect(m_insertBarAction, SIGNAL(triggered()), song, SLOT(insertBar()));
connect(m_removeBarAction, SIGNAL(triggered()), song, SLOT(removeBar()));
DropToolBar *zoomToolBar = addDropToolBarToTop(tr("Zoom controls"));
auto zoom_lbl = new QLabel(m_toolBar);
zoom_lbl->setPixmap( embed::getIconPixmap( "zoom" ) );
// Set slider zoom
m_zoomingSlider = new AutomatableSlider(m_toolBar, tr("Zoom"));
m_zoomingSlider->setModel(m_editor->m_zoomingModel);
m_zoomingSlider->setOrientation(Qt::Horizontal);
m_zoomingSlider->setPageStep(1);
m_zoomingSlider->setFocusPolicy(Qt::NoFocus);
m_zoomingSlider->setFixedSize(100, 26);
m_zoomingSlider->setToolTip(tr("Zoom"));
m_zoomingSlider->setContextMenuPolicy(Qt::NoContextMenu);
connect(m_editor->m_zoomingModel, SIGNAL(dataChanged()), this, SLOT(updateSnapLabel()));
zoomToolBar->addWidget( zoom_lbl );
zoomToolBar->addWidget(m_zoomingSlider);
DropToolBar *snapToolBar = addDropToolBarToTop(tr("Snap controls"));
auto snap_lbl = new QLabel(m_toolBar);
snap_lbl->setPixmap( embed::getIconPixmap( "quantize" ) );
//Set up quantization/snapping selector
m_snappingComboBox = new ComboBox( m_toolBar );
m_snappingComboBox->setFixedSize( 80, ComboBox::DEFAULT_HEIGHT );
m_snappingComboBox->setModel(m_editor->m_snappingModel);
m_snappingComboBox->setToolTip(tr("Clip snapping size"));
connect(m_editor->snappingModel(), SIGNAL(dataChanged()), this, SLOT(updateSnapLabel()));
m_setProportionalSnapAction = new QAction(embed::getIconPixmap("proportional_snap"),
tr("Toggle proportional snap on/off"), this);
m_setProportionalSnapAction->setCheckable(true);
m_setProportionalSnapAction->setChecked(false);
connect(m_setProportionalSnapAction, SIGNAL(triggered()), m_editor, SLOT(toggleProportionalSnap()));
connect(m_setProportionalSnapAction, SIGNAL(triggered()), this, SLOT(updateSnapLabel()));
snapToolBar->addWidget( snap_lbl );
snapToolBar->addWidget( m_snappingComboBox );
snapToolBar->addSeparator();
snapToolBar->addAction( m_setProportionalSnapAction );
snapToolBar->addSeparator();
snapToolBar->addWidget( m_snapSizeLabel );
connect(song, SIGNAL(projectLoaded()), this, SLOT(adjustUiAfterProjectLoad()));
connect(this, SIGNAL(resized()), m_editor, SLOT(updatePositionLine()));
}
QSize SongEditorWindow::sizeHint() const
{
return {900, 300};
}
void SongEditorWindow::updateSnapLabel(){
if (m_setProportionalSnapAction->isChecked())
{
m_snapSizeLabel->setText(QString("Snap: ") + m_editor->getSnapSizeString());
m_snappingComboBox->setToolTip(tr("Base snapping size"));
}
else
{
m_snappingComboBox->setToolTip(tr("Clip snapping size"));
m_snapSizeLabel->clear();
}
}
void SongEditorWindow::syncEditMode(){
m_editModeGroup->checkedAction()->trigger();
}
void SongEditorWindow::resizeEvent(QResizeEvent *event)
{
emit resized();
}
void SongEditorWindow::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::WindowStateChange)
{
m_editor->realignTracks();
}
}
void SongEditorWindow::play()
{
emit playTriggered();
if( Engine::getSong()->playMode() != Song::PlayMode::Song )
{
Engine::getSong()->playSong();
}
else
{
Engine::getSong()->togglePause();
}
}
void SongEditorWindow::record()
{
m_editor->m_song->record();
}
void SongEditorWindow::recordAccompany()
{
m_editor->m_song->playAndRecord();
}
void SongEditorWindow::stop()
{
m_editor->m_song->stop();
getGUI()->pianoRoll()->stopRecording();
}
void SongEditorWindow::lostFocus()
{
if( m_crtlAction )
{
m_crtlAction->setChecked( true );
m_crtlAction->trigger();
}
}
void SongEditorWindow::adjustUiAfterProjectLoad()
{
// make sure to bring us to front as the song editor is the central
// widget in a song and when just opening a song in order to listen to
// it, it's very annyoing to manually bring up the song editor each time
getGUI()->mainWindow()->workspace()->setActiveSubWindow(
qobject_cast<QMdiSubWindow *>( parentWidget() ) );
connect( qobject_cast<SubWindow *>( parentWidget() ), SIGNAL(focusLost()), this, SLOT(lostFocus()));
m_editor->scrolled(0);
}
} // namespace lmms::gui
| 32,383
|
C++
|
.cpp
| 857
| 35.128355
| 128
| 0.734106
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,988
|
Rubberband.cpp
|
LMMS_lmms/src/gui/editors/Rubberband.cpp
|
/*
* Rubberband.cpp - rubberband - either own implementation for Qt3 or wrapper
* for Qt4
*
* Copyright (c) 2006-2011 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Rubberband.h"
namespace lmms::gui
{
RubberBand::RubberBand( QWidget * _parent ) :
QRubberBand( Rectangle, _parent )
{
}
QVector<selectableObject *> RubberBand::selectedObjects() const
{
QVector<selectableObject *> so = selectableObjects();
for( QVector<selectableObject *>::iterator it = so.begin();
it != so.end(); )
{
if( ( *it )->isSelected() == false )
{
it = so.erase( it );
}
else
{
++it;
}
}
return( so );
}
void RubberBand::resizeEvent( QResizeEvent * _re )
{
QRubberBand::resizeEvent( _re );
}
QVector<selectableObject *> RubberBand::selectableObjects() const
{
QVector<selectableObject *> so;
if( parentWidget() == nullptr )
{
return( so );
}
QList<selectableObject *> l =
parentWidget()->findChildren<selectableObject *>();
for (const auto& obj : l)
{
so.push_back(obj);
}
return( so );
}
} // namespace lmms::gui
| 1,900
|
C++
|
.cpp
| 68
| 25.602941
| 77
| 0.706402
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,989
|
StepRecorderWidget.cpp
|
LMMS_lmms/src/gui/editors/StepRecorderWidget.cpp
|
/*
* StepRecoderWidget.cpp - widget that provide gui markers for step recording
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QPainter>
#include "StepRecorderWidget.h"
#include "TextFloat.h"
#include "embed.h"
namespace lmms::gui
{
StepRecorderWidget::StepRecorderWidget(
QWidget * parent,
const int ppb,
const int marginTop,
const int marginBottom,
const int marginLeft,
const int marginRight) :
QWidget(parent),
m_marginTop(marginTop),
m_marginBottom(marginBottom),
m_marginLeft(marginLeft),
m_marginRight(marginRight)
{
const QColor baseColor = QColor(255, 0, 0);// QColor(204, 163, 0); // Orange
m_colorLineEnd = baseColor.lighter(150);
m_colorLineStart = baseColor.darker(120);
setAttribute(Qt::WA_NoSystemBackground, true);
setPixelsPerBar(ppb);
m_top = m_marginTop;
m_left = m_marginLeft;
}
void StepRecorderWidget::setPixelsPerBar(int ppb)
{
m_ppb = ppb;
}
void StepRecorderWidget::setCurrentPosition(TimePos currentPosition)
{
m_currentPosition = currentPosition;
}
void StepRecorderWidget::setMargins(const QMargins &qm)
{
m_left = qm.left();
m_right = qm.right();
m_top = qm.top();
m_bottom = qm.bottom();
}
QMargins StepRecorderWidget::margins()
{
return QMargins(m_left, m_top, m_right, m_bottom);
}
void StepRecorderWidget::setBottomMargin(const int marginBottom)
{
m_marginBottom = marginBottom;
}
void StepRecorderWidget::setStartPosition(TimePos pos)
{
m_curStepStartPos = pos;
}
void StepRecorderWidget::setEndPosition(TimePos pos)
{
m_curStepEndPos = pos;
emit positionChanged(m_curStepEndPos);
}
void StepRecorderWidget::showHint()
{
TextFloat::displayMessage(tr( "Hint" ), tr("Move recording curser using <Left/Right> arrows"),
embed::getIconPixmap("hint"));
}
void StepRecorderWidget::setStepsLength(TimePos stepsLength)
{
m_stepsLength = stepsLength;
}
void StepRecorderWidget::paintEvent(QPaintEvent * pe)
{
QPainter painter(this);
updateBoundaries();
move(0, 0);
//draw steps ruler
painter.setPen(m_colorLineEnd);
TimePos curPos = m_curStepEndPos;
int x = xCoordOfTick(curPos);
while(x <= m_right)
{
const int w = 2;
const int h = 4;
painter.drawRect(x - 1, m_top, w, h);
curPos += m_stepsLength;
x = xCoordOfTick(curPos);
}
//draw current step start/end position lines
if(m_curStepStartPos != m_curStepEndPos)
{
drawVerLine(&painter, m_curStepStartPos, m_colorLineStart, m_top, m_bottom);
}
drawVerLine(&painter, m_curStepEndPos, m_colorLineEnd, m_top, m_bottom);
//if the line is adjacent to the keyboard at the left - it cannot be seen.
//add another line to make it clearer
if(m_curStepEndPos == 0)
{
drawVerLine(&painter, xCoordOfTick(m_curStepEndPos) + 1, m_colorLineEnd, m_top, m_bottom);
}
}
int StepRecorderWidget::xCoordOfTick(int tick)
{
return m_marginLeft + ((tick - m_currentPosition) * m_ppb / TimePos::ticksPerBar());
}
void StepRecorderWidget::drawVerLine(QPainter* painter, int x, const QColor& color, int top, int bottom)
{
if(x >= m_marginLeft && x <= (width() - m_marginRight))
{
painter->setPen(color);
painter->drawLine( x, top, x, bottom );
}
}
void StepRecorderWidget::drawVerLine(QPainter* painter, const TimePos& pos, const QColor& color, int top, int bottom)
{
drawVerLine(painter, xCoordOfTick(pos), color, top, bottom);
}
void StepRecorderWidget::updateBoundaries()
{
setFixedSize(parentWidget()->size());
m_bottom = height() - m_marginBottom;
m_right = width() - m_marginTop;
//(no need to change top and left as they are static)
}
} // namespace lmms::gui
| 4,292
|
C++
|
.cpp
| 143
| 28.055944
| 117
| 0.754978
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,990
|
PatternEditor.cpp
|
LMMS_lmms/src/gui/editors/PatternEditor.cpp
|
/*
* PatternEditor.cpp - basic main-window for editing patterns
*
* Copyright (c) 2004-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PatternEditor.h"
#include <QAction>
#include "ClipView.h"
#include "ComboBox.h"
#include "DataFile.h"
#include "embed.h"
#include "MainWindow.h"
#include "PatternStore.h"
#include "PatternTrack.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "TrackView.h"
#include "MidiClip.h"
namespace lmms::gui
{
PatternEditor::PatternEditor(PatternStore* ps) :
TrackContainerView(ps),
m_ps(ps)
{
setModel(ps);
}
void PatternEditor::addSteps()
{
makeSteps( false );
}
void PatternEditor::cloneSteps()
{
makeSteps( true );
}
void PatternEditor::removeSteps()
{
const TrackContainer::TrackList& tl = model()->tracks();
for (const auto& track : tl)
{
if (track->type() == Track::Type::Instrument)
{
auto p = static_cast<MidiClip*>(track->getClip(m_ps->currentPattern()));
p->removeSteps();
}
}
}
void PatternEditor::addSampleTrack()
{
(void) Track::create( Track::Type::Sample, model() );
}
void PatternEditor::addAutomationTrack()
{
(void) Track::create( Track::Type::Automation, model() );
}
void PatternEditor::removeViewsForPattern(int pattern)
{
for( TrackView* view : trackViews() )
{
view->getTrackContentWidget()->removeClipView(pattern);
}
}
void PatternEditor::saveSettings(QDomDocument& doc, QDomElement& element)
{
MainWindow::saveWidgetState( parentWidget(), element );
}
void PatternEditor::loadSettings(const QDomElement& element)
{
MainWindow::restoreWidgetState(parentWidget(), element);
}
void PatternEditor::dropEvent(QDropEvent* de)
{
QString type = StringPairDrag::decodeKey( de );
QString value = StringPairDrag::decodeValue( de );
if( type.left( 6 ) == "track_" )
{
DataFile dataFile( value.toUtf8() );
Track * t = Track::create( dataFile.content().firstChild().toElement(), model() );
// Ensure pattern clips exist
bool hasValidPatternClips = false;
if (t->getClips().size() == static_cast<std::size_t>(m_ps->numOfPatterns()))
{
hasValidPatternClips = true;
for (auto i = std::size_t{0}; i < t->getClips().size(); ++i)
{
if (t->getClips()[i]->startPosition() != TimePos(i, 0))
{
hasValidPatternClips = false;
break;
}
}
}
if (!hasValidPatternClips)
{
t->deleteClips();
t->createClipsForPattern(m_ps->numOfPatterns() - 1);
}
m_ps->updateAfterTrackAdd();
de->accept();
}
else
{
TrackContainerView::dropEvent( de );
}
}
void PatternEditor::updatePosition()
{
//realignTracks();
emit positionChanged( m_currentPosition );
}
void PatternEditor::makeSteps( bool clone )
{
const TrackContainer::TrackList& tl = model()->tracks();
for (const auto& track : tl)
{
if (track->type() == Track::Type::Instrument)
{
auto p = static_cast<MidiClip*>(track->getClip(m_ps->currentPattern()));
if( clone )
{
p->cloneSteps();
} else
{
p->addSteps();
}
}
}
}
// Creates a clone of the current pattern track with the same content, but no clips in the song editor
// TODO: Avoid repeated code from cloneTrack and clearTrack in TrackOperationsWidget somehow
void PatternEditor::cloneClip()
{
// Get the current PatternTrack id
auto ps = static_cast<PatternStore*>(model());
const int currentPattern = ps->currentPattern();
PatternTrack* pt = PatternTrack::findPatternTrack(currentPattern);
if (pt)
{
// Clone the track
Track* newTrack = pt->clone();
ps->setCurrentPattern(static_cast<PatternTrack*>(newTrack)->patternIndex());
// Track still have the clips which is undesirable in this case, clear the track
newTrack->lock();
newTrack->deleteClips();
newTrack->unlock();
}
}
PatternEditorWindow::PatternEditorWindow(PatternStore* ps) :
Editor(false),
m_editor(new PatternEditor(ps))
{
setWindowIcon(embed::getIconPixmap("pattern_track_btn"));
setWindowTitle(tr("Pattern Editor"));
setCentralWidget(m_editor);
setAcceptDrops(true);
m_toolBar->setAcceptDrops(true);
connect(m_toolBar, SIGNAL(dragEntered(QDragEnterEvent*)), m_editor, SLOT(dragEnterEvent(QDragEnterEvent*)));
connect(m_toolBar, SIGNAL(dropped(QDropEvent*)), m_editor, SLOT(dropEvent(QDropEvent*)));
// TODO: Use style sheet
if (ConfigManager::inst()->value("ui", "compacttrackbuttons").toInt())
{
setMinimumWidth(TRACK_OP_WIDTH_COMPACT + DEFAULT_SETTINGS_WIDGET_WIDTH_COMPACT + 2 * ClipView::BORDER_WIDTH + 384);
}
else
{
setMinimumWidth(TRACK_OP_WIDTH + DEFAULT_SETTINGS_WIDGET_WIDTH + 2 * ClipView::BORDER_WIDTH + 384);
}
m_playAction->setToolTip(tr("Play/pause current pattern (Space)"));
m_stopAction->setToolTip(tr("Stop playback of current pattern (Space)"));
// Pattern selector
DropToolBar* patternSelectionToolBar = addDropToolBarToTop(tr("Pattern selector"));
m_patternComboBox = new ComboBox(m_toolBar);
m_patternComboBox->setFixedSize(200, ComboBox::DEFAULT_HEIGHT);
m_patternComboBox->setModel(&ps->m_patternComboBoxModel);
patternSelectionToolBar->addWidget(m_patternComboBox);
// Track actions
DropToolBar *trackAndStepActionsToolBar = addDropToolBarToTop(tr("Track and step actions"));
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("add_pattern_track"), tr("New pattern"),
Engine::getSong(), SLOT(addPatternTrack()));
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("clone_pattern_track_clip"), tr("Clone pattern"),
m_editor, SLOT(cloneClip()));
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("add_sample_track"), tr("Add sample-track"),
m_editor, SLOT(addSampleTrack()));
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("add_automation"), tr("Add automation-track"),
m_editor, SLOT(addAutomationTrack()));
auto stretch = new QWidget(m_toolBar);
stretch->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
trackAndStepActionsToolBar->addWidget(stretch);
// Step actions
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("step_btn_remove"), tr("Remove steps"),
m_editor, SLOT(removeSteps()));
trackAndStepActionsToolBar->addAction(embed::getIconPixmap("step_btn_add"), tr("Add steps"),
m_editor, SLOT(addSteps()));
trackAndStepActionsToolBar->addAction( embed::getIconPixmap("step_btn_duplicate"), tr("Clone Steps"),
m_editor, SLOT(cloneSteps()));
connect(&ps->m_patternComboBoxModel, SIGNAL(dataChanged()),
m_editor, SLOT(updatePosition()));
auto viewNext = new QAction(this);
connect(viewNext, SIGNAL(triggered()), m_patternComboBox, SLOT(selectNext()));
viewNext->setShortcut(Qt::Key_Plus);
addAction(viewNext);
auto viewPrevious = new QAction(this);
connect(viewPrevious, SIGNAL(triggered()), m_patternComboBox, SLOT(selectPrevious()));
viewPrevious->setShortcut(Qt::Key_Minus);
addAction(viewPrevious);
}
QSize PatternEditorWindow::sizeHint() const
{
return {minimumWidth() + 10, 300};
}
void PatternEditorWindow::play()
{
if (Engine::getSong()->playMode() != Song::PlayMode::Pattern)
{
Engine::getSong()->playPattern();
}
else
{
Engine::getSong()->togglePause();
}
}
void PatternEditorWindow::stop()
{
Engine::getSong()->stop();
}
} // namespace lmms::gui
| 8,005
|
C++
|
.cpp
| 243
| 30.403292
| 117
| 0.741146
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,991
|
PianoRoll.cpp
|
LMMS_lmms/src/gui/editors/PianoRoll.cpp
|
/*
* PianoRoll.cpp - implementation of piano roll which is used for actual
* writing of melodies
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008 Andrew Kelley <superjoe30/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PianoRoll.h"
#include <QtMath>
#include <QApplication>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QMargins>
#include <QMessageBox>
#include <QPainter>
#include <QPointer>
#include <QPushButton>
#include <QScrollBar>
#include <QStyleOption>
#include <QToolButton>
#ifndef __USE_XOPEN
#define __USE_XOPEN
#endif
#include <cmath>
#include <utility>
#include "AutomationEditor.h"
#include "ActionGroup.h"
#include "Clipboard.h"
#include "ComboBox.h"
#include "ConfigManager.h"
#include "DataFile.h"
#include "debug.h"
#include "DeprecationHelper.h"
#include "DetuningHelper.h"
#include "embed.h"
#include "GuiApplication.h"
#include "FontHelper.h"
#include "InstrumentTrack.h"
#include "MainWindow.h"
#include "MidiClip.h"
#include "PatternStore.h"
#include "PianoView.h"
#include "PositionLine.h"
#include "SimpleTextFloat.h"
#include "SongEditor.h"
#include "StepRecorderWidget.h"
#include "TextFloat.h"
#include "TimeLineWidget.h"
#include "FileDialog.h"
namespace lmms
{
using timeMap = AutomationClip::timeMap;
namespace gui
{
// some constants...
const int INITIAL_PIANOROLL_WIDTH = 970;
const int INITIAL_PIANOROLL_HEIGHT = 485;
const int SCROLLBAR_SIZE = 12;
const int PIANO_X = 0;
const int WHITE_KEY_WIDTH = 64;
const int BLACK_KEY_WIDTH = 41;
const int DEFAULT_KEY_LINE_HEIGHT = 12;
const int DEFAULT_CELL_WIDTH = 12;
const int NOTE_EDIT_RESIZE_BAR = 6;
const int NOTE_EDIT_MIN_HEIGHT = 50;
const int KEY_AREA_MIN_HEIGHT = DEFAULT_KEY_LINE_HEIGHT * 10;
const int PR_BOTTOM_MARGIN = SCROLLBAR_SIZE;
const int PR_TOP_MARGIN = 18;
const int PR_RIGHT_MARGIN = SCROLLBAR_SIZE;
// width of area used for resizing (the grip at the end of a note)
const int RESIZE_AREA_WIDTH = 9;
// width of line for setting volume/panning of note
const int NOTE_EDIT_LINE_WIDTH = 3;
// key where to start
const int INITIAL_START_KEY = Octave::Octave_4 + Key::C;
// number of each note to provide in quantization and note lengths
const int NUM_EVEN_LENGTHS = 6;
const int NUM_TRIPLET_LENGTHS = 5;
SimpleTextFloat * PianoRoll::s_textFloat = nullptr;
static std::array<QString, 12> s_noteStrings {
"C", "C\u266F / D\u266D", "D", "D\u266F / E\u266D", "E", "F", "F\u266F / G\u266D",
"G", "G\u266F / A\u266D", "A", "A\u266F / B\u266D", "B"
};
static QString getNoteString(int key)
{
return s_noteStrings[key % 12] + QString::number(static_cast<int>(FirstOctave + key / KeysPerOctave));
}
// used for drawing of piano
std::array<PianoRoll::KeyType, 12> PianoRoll::prKeyOrder
{
KeyType::WhiteSmall, KeyType::Black, KeyType::WhiteBig, KeyType::Black,
KeyType::WhiteSmall, KeyType::WhiteSmall, KeyType::Black, KeyType::WhiteBig,
KeyType::Black, KeyType::WhiteBig, KeyType::Black, KeyType::WhiteSmall
} ;
const int DEFAULT_PR_PPB = DEFAULT_CELL_WIDTH * DefaultStepsPerBar;
const std::vector<float> PianoRoll::m_zoomLevels =
{0.125f, 0.25f, 0.5f, 1.0f, 1.5f, 2.0f, 4.0f, 8.0f};
const std::vector<float> PianoRoll::m_zoomYLevels =
{0.25f, 0.5f, 1.0f, 1.5f, 2.0f, 2.5f, 3.0f, 4.0f};
PianoRoll::PianoRoll() :
m_noteEditMenu( nullptr ),
m_semiToneMarkerMenu( nullptr ),
m_zoomingModel(),
m_zoomingYModel(),
m_quantizeModel(),
m_noteLenModel(),
m_scaleModel(),
m_chordModel(),
m_midiClip( nullptr ),
m_currentPosition(),
m_recording( false ),
m_doAutoQuantization(ConfigManager::inst()->value("midi", "autoquantize").toInt() != 0),
m_currentNote( nullptr ),
m_action( Action::None ),
m_noteEditMode( NoteEditMode::Volume ),
m_moveBoundaryLeft( 0 ),
m_moveBoundaryTop( 0 ),
m_moveBoundaryRight( 0 ),
m_moveBoundaryBottom( 0 ),
m_mouseDownKey( 0 ),
m_mouseDownTick( 0 ),
m_lastMouseX( 0 ),
m_lastMouseY( 0 ),
m_notesEditHeight( 100 ),
m_userSetNotesEditHeight(100),
m_ppb( DEFAULT_PR_PPB ),
m_keyLineHeight(DEFAULT_KEY_LINE_HEIGHT),
m_whiteKeySmallHeight(qFloor(m_keyLineHeight * 1.5)),
m_whiteKeyBigHeight(m_keyLineHeight * 2),
m_blackKeyHeight(m_keyLineHeight),
m_lenOfNewNotes( TimePos( 0, DefaultTicksPerBar/4 ) ),
m_lastNoteVolume( DefaultVolume ),
m_lastNotePanning( DefaultPanning ),
m_minResizeLen( 0 ),
m_startKey( INITIAL_START_KEY ),
m_lastKey( 0 ),
m_editMode( EditMode::Draw ),
m_ctrlMode( EditMode::Draw ),
m_mouseDownRight( false ),
m_scrollBack( false ),
m_stepRecorderWidget(this, DEFAULT_PR_PPB, PR_TOP_MARGIN, PR_BOTTOM_MARGIN + m_notesEditHeight, WHITE_KEY_WIDTH, 0),
m_stepRecorder(*this, m_stepRecorderWidget),
m_barLineColor( 0, 0, 0 ),
m_beatLineColor( 0, 0, 0 ),
m_lineColor( 0, 0, 0 ),
m_noteModeColor( 0, 0, 0 ),
m_noteColor( 0, 0, 0 ),
m_ghostNoteColor( 0, 0, 0 ),
m_ghostNoteTextColor( 0, 0, 0 ),
m_barColor( 0, 0, 0 ),
m_selectedNoteColor( 0, 0, 0 ),
m_textColor( 0, 0, 0 ),
m_textColorLight( 0, 0, 0 ),
m_textShadow( 0, 0, 0 ),
m_markedSemitoneColor( 0, 0, 0 ),
m_knifeCutLineColor(0, 0, 0),
m_noteOpacity( 255 ),
m_ghostNoteOpacity( 255 ),
m_noteBorders( true ),
m_ghostNoteBorders( true ),
m_backgroundShade( 0, 0, 0 ),
m_whiteKeyWidth(WHITE_KEY_WIDTH),
m_blackKeyWidth(BLACK_KEY_WIDTH)
{
// gui names of edit modes
m_nemStr.push_back( tr( "Note Velocity" ) );
m_nemStr.push_back( tr( "Note Panning" ) );
m_noteEditMenu = new QMenu( this );
m_noteEditMenu->clear();
for (auto i = std::size_t{0}; i < m_nemStr.size(); ++i)
{
auto act = new QAction(m_nemStr.at(i), this);
connect( act, &QAction::triggered, [this, i](){ changeNoteEditMode(i); } );
m_noteEditMenu->addAction( act );
}
m_semiToneMarkerMenu = new QMenu( this );
auto markSemitoneAction = new QAction(tr("Mark/unmark current semitone"), this);
auto markAllOctaveSemitonesAction = new QAction(tr("Mark/unmark all corresponding octave semitones"), this);
auto markScaleAction = new QAction(tr("Mark current scale"), this);
auto markChordAction = new QAction(tr("Mark current chord"), this);
auto unmarkAllAction = new QAction(tr("Unmark all"), this);
auto copyAllNotesAction = new QAction(tr("Select all notes on this key"), this);
connect( markSemitoneAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::MarkCurrentSemiTone); });
connect( markAllOctaveSemitonesAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::MarkAllOctaveSemiTones); });
connect( markScaleAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::MarkCurrentScale); });
connect( markChordAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::MarkCurrentChord); });
connect( unmarkAllAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::UnmarkAll); });
connect( copyAllNotesAction, &QAction::triggered, [this](){ markSemiTone(SemiToneMarkerAction::CopyAllNotesOnKey); });
connect(ConfigManager::inst(), &ConfigManager::valueChanged,
[this](QString const& cls, QString const& attribute, QString const& value)
{
if (!(cls == "midi" && attribute == "autoquantize"))
{
return;
}
this->m_doAutoQuantization = (value.toInt() != 0);
});
markScaleAction->setEnabled( false );
markChordAction->setEnabled( false );
connect( this, SIGNAL(semiToneMarkerMenuScaleSetEnabled(bool)), markScaleAction, SLOT(setEnabled(bool)));
connect( this, SIGNAL(semiToneMarkerMenuChordSetEnabled(bool)), markChordAction, SLOT(setEnabled(bool)));
m_semiToneMarkerMenu->addAction( markSemitoneAction );
m_semiToneMarkerMenu->addAction( markAllOctaveSemitonesAction );
m_semiToneMarkerMenu->addAction( markScaleAction );
m_semiToneMarkerMenu->addAction( markChordAction );
m_semiToneMarkerMenu->addAction( unmarkAllAction );
m_semiToneMarkerMenu->addAction( copyAllNotesAction );
// init text-float
if( s_textFloat == nullptr )
{
s_textFloat = new SimpleTextFloat;
}
setAttribute( Qt::WA_OpaquePaintEvent, true );
// add time-line
m_timeLine = new TimeLineWidget(m_whiteKeyWidth, 0, m_ppb,
Engine::getSong()->getPlayPos(Song::PlayMode::MidiClip),
Engine::getSong()->getTimeline(Song::PlayMode::MidiClip),
m_currentPosition, Song::PlayMode::MidiClip, this
);
connect(this, &PianoRoll::positionChanged, m_timeLine, &TimeLineWidget::updatePosition);
connect( m_timeLine, SIGNAL( positionChanged( const lmms::TimePos& ) ),
this, SLOT( updatePosition( const lmms::TimePos& ) ) );
// white position line follows timeline marker
m_positionLine = new PositionLine(this);
//update timeline when in step-recording mode
connect( &m_stepRecorderWidget, SIGNAL( positionChanged( const lmms::TimePos& ) ),
this, SLOT( updatePositionStepRecording( const lmms::TimePos& ) ) );
// update timeline when in record-accompany mode
connect(m_timeLine, &TimeLineWidget::positionChanged, this, &PianoRoll::updatePositionAccompany);
// TODO
/* connect( engine::getSong()->getPlayPos( Song::PlayMode::Pattern ).m_timeLine,
SIGNAL( positionChanged( const lmms::TimePos& ) ),
this,
SLOT( updatePositionAccompany( const lmms::TimePos& ) ) );*/
removeSelection();
// init scrollbars
m_leftRightScroll = new QScrollBar( Qt::Horizontal, this );
m_leftRightScroll->setSingleStep( 1 );
connect( m_leftRightScroll, SIGNAL(valueChanged(int)), this,
SLOT(horScrolled(int)));
m_topBottomScroll = new QScrollBar( Qt::Vertical, this );
m_topBottomScroll->setSingleStep( 1 );
m_topBottomScroll->setPageStep( 20 );
connect( m_topBottomScroll, SIGNAL(valueChanged(int)), this,
SLOT(verScrolled(int)));
// setup zooming-stuff
for( float const & zoomLevel : m_zoomLevels )
{
m_zoomingModel.addItem(QString("%1%").arg(zoomLevel * 100));
}
m_zoomingModel.setValue( m_zoomingModel.findText( "100%" ) );
connect( &m_zoomingModel, SIGNAL(dataChanged()),
this, SLOT(zoomingChanged()));
// zoom y
for (float const & zoomLevel : m_zoomYLevels)
{
m_zoomingYModel.addItem(QString("%1%").arg(zoomLevel * 100));
}
m_zoomingYModel.setValue(m_zoomingYModel.findText("100%"));
connect(&m_zoomingYModel, SIGNAL(dataChanged()),
this, SLOT(zoomingYChanged()));
// Set up quantization model
m_quantizeModel.addItem( tr( "Note lock" ) );
for (auto q : Quantizations) {
m_quantizeModel.addItem(QString("1/%1").arg(q));
}
m_quantizeModel.setValue( m_quantizeModel.findText( "1/16" ) );
connect( &m_quantizeModel, SIGNAL(dataChanged()),
this, SLOT(quantizeChanged()));
// Set up note length model
m_noteLenModel.addItem( tr( "Last note" ),
std::make_unique<PixmapLoader>( "edit_draw" ) );
const auto pixmaps = std::array<std::string, 11>{"whole", "half", "quarter", "eighth",
"sixteenth", "thirtysecond", "triplethalf",
"tripletquarter", "tripleteighth",
"tripletsixteenth", "tripletthirtysecond"};
for( int i = 0; i < NUM_EVEN_LENGTHS; ++i )
{
auto loader = std::make_unique<PixmapLoader>( "note_" + pixmaps[i] );
m_noteLenModel.addItem( "1/" + QString::number( 1 << i ), std::move(loader) );
}
for( int i = 0; i < NUM_TRIPLET_LENGTHS; ++i )
{
auto loader = std::make_unique<PixmapLoader>( "note_" + pixmaps[i+NUM_EVEN_LENGTHS] );
m_noteLenModel.addItem( "1/" + QString::number( (1 << i) * 3 ), std::move(loader) );
}
m_noteLenModel.setValue( 0 );
// Note length change can cause a redraw if Q is set to lock
connect( &m_noteLenModel, SIGNAL(dataChanged()),
this, SLOT(noteLengthChanged()));
// Set up key selection dropdown
m_keyModel.addItem(tr("No key"));
// Use piano roll note strings for key dropdown
for (const auto& noteString : s_noteStrings)
{
m_keyModel.addItem(noteString);
}
m_keyModel.setValue(0); // start with "No key"
connect(&m_keyModel, &ComboBoxModel::dataChanged, this, &PianoRoll::keyChanged);
// Set up scale model
const InstrumentFunctionNoteStacking::ChordTable& chord_table =
InstrumentFunctionNoteStacking::ChordTable::getInstance();
m_scaleModel.addItem( tr("No scale") );
for (const InstrumentFunctionNoteStacking::Chord& chord : chord_table.chords())
{
if( chord.isScale() )
{
m_scaleModel.addItem( chord.getName() );
}
}
m_scaleModel.setValue( 0 );
// connect scale change to key change so it auto-highlights with scale as well
connect(&m_scaleModel, &ComboBoxModel::dataChanged, this, &PianoRoll::keyChanged);
// change can update m_semiToneMarkerMenu
connect( &m_scaleModel, SIGNAL(dataChanged()),
this, SLOT(updateSemiToneMarkerMenu()));
// Set up chord model
m_chordModel.addItem( tr("No chord") );
for (const InstrumentFunctionNoteStacking::Chord& chord : chord_table.chords())
{
if( ! chord.isScale() )
{
m_chordModel.addItem( chord.getName() );
}
}
m_chordModel.setValue( 0 );
// change can update m_semiToneMarkerMenu
connect( &m_chordModel, SIGNAL(dataChanged()),
this, SLOT(updateSemiToneMarkerMenu()));
setFocusPolicy( Qt::StrongFocus );
setFocus();
setMouseTracking( true );
connect( &m_scaleModel, SIGNAL(dataChanged()),
this, SLOT(updateSemiToneMarkerMenu()));
connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)),
this, SLOT(update()));
//connection for selecion from timeline
connect( m_timeLine, SIGNAL(regionSelectedFromPixels(int,int)),
this, SLOT(selectRegionFromPixels(int,int)));
// Set up snap model
m_snapModel.addItem(tr("Nudge"));
m_snapModel.addItem(tr("Snap"));
m_snapModel.setValue(0);
changeSnapMode();
connect(&m_snapModel, SIGNAL(dataChanged()),
this, SLOT(changeSnapMode()));
m_stepRecorder.initialize();
// trigger a redraw if keymap definitions change (different keys may become disabled)
connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(update()));
}
void PianoRoll::reset()
{
m_lastNoteVolume = DefaultVolume;
m_lastNotePanning = DefaultPanning;
clearGhostClip();
}
void PianoRoll::showTextFloat(const QString &text, const QPoint &pos, int timeout)
{
s_textFloat->setText( text );
// show the float, offset slightly so as to not obscure anything
s_textFloat->moveGlobal( this, pos + QPoint(4, 16) );
if (timeout == -1)
{
s_textFloat->show();
}
else
{
s_textFloat->setVisibilityTimeOut( timeout );
}
}
void PianoRoll::showVolTextFloat(volume_t vol, const QPoint &pos, int timeout)
{
//! \todo display velocity for MIDI-based instruments
// possibly dBFS values too? not sure if it makes sense for note volumes...
showTextFloat( tr("Velocity: %1%").arg( vol ), pos, timeout );
}
void PianoRoll::showPanTextFloat(panning_t pan, const QPoint &pos, int timeout)
{
QString text;
if( pan < 0 )
{
text = tr("Panning: %1% left").arg( qAbs( pan ) );
}
else if( pan > 0 )
{
text = tr("Panning: %1% right").arg( qAbs( pan ) );
}
else
{
text = tr("Panning: center");
}
showTextFloat( text, pos, timeout );
}
void PianoRoll::changeNoteEditMode( int i )
{
m_noteEditMode = (NoteEditMode) i;
repaint();
}
void PianoRoll::markSemiTone(SemiToneMarkerAction i, bool fromMenu)
{
const int key = fromMenu
? getKey(mapFromGlobal(m_semiToneMarkerMenu->pos()).y())
: m_keyModel.value() - 1;
const InstrumentFunctionNoteStacking::Chord * chord = nullptr;
// if "No key" is selected, key is -1, unmark all semitones
// or if scale changed from toolbar to "No scale", unmark all semitones
if (!fromMenu && (key < 0 || m_scaleModel.value() == 0)) { i = SemiToneMarkerAction::UnmarkAll; }
switch(i)
{
case SemiToneMarkerAction::UnmarkAll:
m_markedSemiTones.clear();
break;
case SemiToneMarkerAction::MarkCurrentSemiTone:
{
QList<int>::iterator it = std::find( m_markedSemiTones.begin(), m_markedSemiTones.end(), key );
if( it != m_markedSemiTones.end() )
{
m_markedSemiTones.erase( it );
}
else
{
m_markedSemiTones.push_back( key );
}
break;
}
case SemiToneMarkerAction::MarkAllOctaveSemiTones:
{
QList<int> aok = getAllOctavesForKey(key);
if ( m_markedSemiTones.contains(key) )
{
// lets erase all of the ones that match this by octave
QList<int>::iterator i;
for (int octave : aok)
{
i = std::find(m_markedSemiTones.begin(), m_markedSemiTones.end(), octave);
if (i != m_markedSemiTones.end())
{
m_markedSemiTones.erase(i);
}
}
}
else
{
// we should add all of the ones that match this by octave
m_markedSemiTones.append(aok);
}
break;
}
case SemiToneMarkerAction::MarkCurrentScale:
chord = & InstrumentFunctionNoteStacking::ChordTable::getInstance()
.getScaleByName( m_scaleModel.currentText() );
case SemiToneMarkerAction::MarkCurrentChord:
{
if( ! chord )
{
chord = & InstrumentFunctionNoteStacking::ChordTable::getInstance()
.getChordByName( m_chordModel.currentText() );
}
if( chord->isEmpty() )
{
break;
}
else if( chord->isScale() )
{
m_markedSemiTones.clear();
}
const int first = chord->isScale() ? 0 : key;
const int last = chord->isScale() ? NumKeys : key + chord->last();
const int cap = (chord->isScale() || chord->last() == 0) ? trackOctaveSize() : chord->last();
for( int i = first; i <= last; i++ )
{
if( chord->hasSemiTone( ( i + cap - ( key % cap ) ) % cap ) )
{
m_markedSemiTones.push_back( i );
}
}
break;
}
case SemiToneMarkerAction::CopyAllNotesOnKey:
{
selectNotesOnKey();
break;
}
default:
;
}
std::sort( m_markedSemiTones.begin(), m_markedSemiTones.end(), std::greater<int>() );
QList<int>::iterator new_end = std::unique( m_markedSemiTones.begin(), m_markedSemiTones.end() );
m_markedSemiTones.erase( new_end, m_markedSemiTones.end() );
// until we move the mouse the window won't update, force redraw
update();
}
void PianoRoll::setGhostMidiClip( MidiClip* newMidiClip )
{
// Expects a pointer to a MIDI clip or nullptr.
m_ghostNotes.clear();
if( newMidiClip != nullptr )
{
for( Note *note : newMidiClip->notes() )
{
auto new_note = new Note(note->length(), note->pos(), note->key());
m_ghostNotes.push_back( new_note );
}
emit ghostClipSet( true );
}
}
void PianoRoll::loadGhostNotes( const QDomElement & de )
{
// Load ghost notes from DOM element.
if( de.isElement() )
{
QDomNode node = de.firstChild();
while( !node.isNull() )
{
auto n = new Note;
n->restoreState( node.toElement() );
n->setVolume(DefaultVolume);
m_ghostNotes.push_back( n );
node = node.nextSibling();
}
emit ghostClipSet( true );
}
}
void PianoRoll::clearGhostClip()
{
setGhostMidiClip( nullptr );
emit ghostClipSet( false );
update();
}
void PianoRoll::glueNotes()
{
if (hasValidMidiClip())
{
NoteVector selectedNotes = getSelectedNotes();
if (selectedNotes.empty())
{
TextFloat::displayMessage( tr( "Glue notes failed" ),
tr( "Please select notes to glue first." ),
embed::getIconPixmap( "glue", 24, 24 ),
3000 );
return;
}
// Make undo possible
m_midiClip->addJournalCheckPoint();
// Sort notes on key and then pos.
std::sort(selectedNotes.begin(), selectedNotes.end(),
[](const Note * note, const Note * compareNote) -> bool
{
if (note->key() == compareNote->key())
{
return note->pos() < compareNote->pos();
}
return note->key() < compareNote->key();
});
QList<Note *> noteToRemove;
NoteVector::iterator note = selectedNotes.begin();
auto nextNote = note+1;
NoteVector::iterator end = selectedNotes.end();
while (note != end && nextNote != end)
{
// key and position match for glue. The notes are already
// sorted so we don't need to test that nextNote is the same
// position or next in sequence.
if ((*note)->key() == (*nextNote)->key()
&& (*nextNote)->pos() <= (*note)->pos()
+ qMax(TimePos(0), (*note)->length()))
{
(*note)->setLength(qMax((*note)->length(),
TimePos((*nextNote)->endPos() - (*note)->pos())));
noteToRemove.push_back(*nextNote);
++nextNote;
}
// key or position doesn't match
else
{
note = nextNote;
nextNote = note+1;
}
}
// Remove old notes
for (int i = 0; i < noteToRemove.count(); ++i)
{
m_midiClip->removeNote(noteToRemove[i]);
}
update();
}
}
void PianoRoll::fitNoteLengths(bool fill)
{
if (!hasValidMidiClip()) { return; }
m_midiClip->addJournalCheckPoint();
m_midiClip->rearrangeAllNotes();
// Reference notes
const NoteVector& refNotes = m_midiClip->notes();
// Notes to edit
NoteVector notes = getSelectedNotes();
if (notes.empty())
{
notes = refNotes;
}
else if (!fill)
{
std::sort(notes.begin(), notes.end(), Note::lessThan);
}
if (fill)
{
std::sort(notes.begin(), notes.end(), [](Note* n1, Note* n2) { return n1->endPos() < n2->endPos(); });
}
int length;
auto ref = refNotes.begin();
for (Note* note : notes)
{
// Fast forward to next reference note
while (ref != refNotes.end() && (fill ? (*ref)->pos() < note->endPos() : (*ref)->pos() <= note->pos()))
{
ref++;
}
if (ref == refNotes.end())
{
if (!fill) { break; }
// Last notes stretch to end of last bar
length = notes.back()->endPos().nextFullBar() * TimePos::ticksPerBar() - note->pos();
}
else
{
length = (*ref)->pos() - note->pos();
}
if (fill ? note->length() < length : note->length() > length)
{
note->setLength(length);
}
}
update();
getGUI()->songEditor()->update();
Engine::getSong()->setModified();
}
void PianoRoll::constrainNoteLengths(bool constrainMax)
{
if (!hasValidMidiClip()) { return; }
m_midiClip->addJournalCheckPoint();
const NoteVector selectedNotes = getSelectedNotes();
const auto& notes = selectedNotes.empty() ? m_midiClip->notes() : selectedNotes;
TimePos bound = m_lenOfNewNotes; // will be length of last note
for (auto note : notes)
{
if (constrainMax ? note->length() > bound : note->length() < bound)
{
note->setLength(bound);
}
}
update();
getGUI()->songEditor()->update();
Engine::getSong()->setModified();
}
void PianoRoll::loadMarkedSemiTones(const QDomElement & de)
{
// clear marked semitones to prevent leftover marks
m_markedSemiTones.clear();
if (de.isElement())
{
QDomNode node = de.firstChild();
while (!node.isNull())
{
bool ok;
int key = node.toElement().attribute(
QString("key"), QString("-1")).toInt(&ok, 10);
if (ok && key >= 0)
{
m_markedSemiTones.append(key);
}
node = node.nextSibling();
}
}
// from markSemiTone, required otherwise marks will not show
std::sort(m_markedSemiTones.begin(), m_markedSemiTones.end(), std::greater<int>());
QList<int>::iterator new_end = std::unique(m_markedSemiTones.begin(), m_markedSemiTones.end());
m_markedSemiTones.erase(new_end, m_markedSemiTones.end());
}
void PianoRoll::setCurrentMidiClip( MidiClip* newMidiClip )
{
if( hasValidMidiClip() )
{
m_midiClip->instrumentTrack()->pianoModel()->disconnect(this);
m_midiClip->instrumentTrack()->firstKeyModel()->disconnect(this);
m_midiClip->instrumentTrack()->lastKeyModel()->disconnect(this);
m_midiClip->instrumentTrack()->microtuner()->keymapModel()->disconnect(this);
m_midiClip->instrumentTrack()->microtuner()->keyRangeImportModel()->disconnect(this);
m_midiClip->instrumentTrack()->disconnect( this );
m_midiClip->disconnect(this);
}
// force the song-editor to stop playing if it played a MIDI clip before
if (Engine::getSong()->playMode() == Song::PlayMode::MidiClip)
{
Engine::getSong()->playMidiClip( nullptr );
}
if(m_stepRecorder.isRecording())
{
m_stepRecorder.stop();
}
// set new data
m_midiClip = newMidiClip;
m_currentPosition = 0;
m_currentNote = nullptr;
m_startKey = INITIAL_START_KEY;
m_stepRecorder.setCurrentMidiClip(newMidiClip);
if( ! hasValidMidiClip() )
{
//resizeEvent( NULL );
update();
emit currentMidiClipChanged();
return;
}
m_leftRightScroll->setValue( 0 );
// determine the central key so that we can scroll to it
int central_key = 0;
int total_notes = 0;
for( const Note *note : m_midiClip->notes() )
{
if( note->length() > 0 )
{
central_key += note->key();
++total_notes;
}
}
if (total_notes > 0)
{
central_key = central_key / total_notes - (NumKeys - m_totalKeysToScroll) / 2;
m_startKey = qBound(0, central_key, NumKeys);
}
// resizeEvent() does the rest for us (scrolling, range-checking
// of start-notes and so on...)
resizeEvent( nullptr );
// make sure to always get informed about the MIDI clip being destroyed
connect( m_midiClip, SIGNAL(destroyedMidiClip(lmms::MidiClip*)), this, SLOT(hideMidiClip(lmms::MidiClip*)));
connect( m_midiClip->instrumentTrack(), SIGNAL( midiNoteOn( const lmms::Note& ) ), this, SLOT( startRecordNote( const lmms::Note& ) ) );
connect( m_midiClip->instrumentTrack(), SIGNAL( midiNoteOff( const lmms::Note& ) ), this, SLOT( finishRecordNote( const lmms::Note& ) ) );
connect( m_midiClip, SIGNAL(dataChanged()), this, SLOT(update()));
connect( m_midiClip->instrumentTrack()->pianoModel(), SIGNAL(dataChanged()), this, SLOT(update()));
connect(m_midiClip->instrumentTrack()->firstKeyModel(), SIGNAL(dataChanged()), this, SLOT(update()));
connect(m_midiClip->instrumentTrack()->lastKeyModel(), SIGNAL(dataChanged()), this, SLOT(update()));
connect(m_midiClip->instrumentTrack()->microtuner()->keymapModel(), SIGNAL(dataChanged()), this, SLOT(update()));
connect(m_midiClip->instrumentTrack()->microtuner()->keyRangeImportModel(), SIGNAL(dataChanged()),
this, SLOT(update()));
update();
emit currentMidiClipChanged();
}
void PianoRoll::hideMidiClip( MidiClip* clip )
{
if( m_midiClip == clip )
{
setCurrentMidiClip( nullptr );
}
}
int PianoRoll::trackOctaveSize() const
{
if (!m_midiClip) { return KeysPerOctave; }
auto ut = m_midiClip->instrumentTrack()->microtuner();
return ut->enabled() ? ut->octaveSize() : KeysPerOctave;
}
void PianoRoll::selectRegionFromPixels( int xStart, int xEnd )
{
xStart -= m_whiteKeyWidth;
xEnd -= m_whiteKeyWidth;
// select an area of notes
int posTicks = xStart * TimePos::ticksPerBar() / m_ppb +
m_currentPosition;
int keyNum = 0;
m_selectStartTick = posTicks;
m_selectedTick = 0;
m_selectStartKey = keyNum;
m_selectedKeys = 1;
// change size of selection
// get tick in which the cursor is posated
posTicks = xEnd * TimePos::ticksPerBar() / m_ppb +
m_currentPosition;
keyNum = 120;
m_selectedTick = posTicks - m_selectStartTick;
if( (int) m_selectStartTick + m_selectedTick < 0 )
{
m_selectedTick = -static_cast<int>(
m_selectStartTick );
}
m_selectedKeys = keyNum - m_selectStartKey;
if( keyNum <= m_selectStartKey )
{
--m_selectedKeys;
}
computeSelectedNotes( false );
}
void PianoRoll::drawNoteRect( QPainter & p, int x, int y,
int width, const Note * n, const QColor & noteCol, const QColor & noteTextColor,
const QColor & selCol, const int noteOpc, const bool borders, bool drawNoteName )
{
++x;
++y;
width -= 2;
if( width <= 0 )
{
width = 2;
}
// Volume
auto const volumeRange = static_cast<float>(MaxVolume - MinVolume);
auto const volumeSpan = static_cast<float>(n->getVolume() - MinVolume);
float const volumeRatio = volumeSpan / volumeRange;
int volVal = qMin( 255, 100 + static_cast<int>( volumeRatio * 155.0f) );
// Panning
auto const panningRange = static_cast<float>(PanningRight - PanningLeft);
auto const leftPanSpan = static_cast<float>(PanningRight - n->getPanning());
auto const rightPanSpan = static_cast<float>(n->getPanning() - PanningLeft);
float leftPercent = qMin<float>( 1.0f, leftPanSpan / panningRange * 2.0f );
float rightPercent = qMin<float>( 1.0f, rightPanSpan / panningRange * 2.0f );
QColor col{noteCol};
QPen pen;
if( n->selected() )
{
col = QColor( selCol );
}
const int borderWidth = borders ? 1 : 0;
const int noteHeight = m_keyLineHeight - 1 - borderWidth;
int noteWidth = width + 1 - borderWidth;
// adjust note to make it a bit faded if it has a lower volume
// in stereo using gradients
QColor lcol = QColor::fromHsv( col.hue(), col.saturation(),
static_cast<int>(volVal * leftPercent), noteOpc );
QColor rcol = QColor::fromHsv( col.hue(), col.saturation(),
static_cast<int>(volVal * rightPercent), noteOpc );
QLinearGradient gradient( x, y, x, y + noteHeight );
gradient.setColorAt( 0, rcol );
gradient.setColorAt( 1, lcol );
p.setBrush( gradient );
if ( borders )
{
p.setPen( col );
}
else
{
p.setPen( Qt::NoPen );
}
p.drawRect( x, y, noteWidth, noteHeight );
// Draw note key text
if (drawNoteName)
{
p.save();
int const noteTextHeight = static_cast<int>(noteHeight * 0.8);
if (noteTextHeight > 6)
{
QString noteKeyString = getNoteString(n->key());
QFont noteFont(p.font());
noteFont = adjustedToPixelSize(noteFont, noteTextHeight);
QFontMetrics fontMetrics(noteFont);
QSize textSize = fontMetrics.size(Qt::TextSingleLine, noteKeyString);
int const distanceToBorder = 2;
int const xOffset = borderWidth + distanceToBorder;
// noteTextHeight, textSize are not suitable for determining vertical spacing,
// capHeight() can be used for this, but requires Qt 5.8.
// We use boundingRect() with QChar (the QString version returns wrong value).
QRect const boundingRect = fontMetrics.boundingRect(QChar::fromLatin1('H'));
int const yOffset = (noteHeight - boundingRect.top() - boundingRect.bottom()) / 2;
if (textSize.width() < noteWidth - xOffset)
{
p.setPen(noteTextColor);
p.setFont(noteFont);
QPoint textStart(x + xOffset, y + yOffset);
p.drawText(textStart, noteKeyString);
}
}
p.restore();
}
// draw the note endmark, to hint the user to resize
p.setBrush( col );
if( width > 2 )
{
const int endmarkWidth = 3 - borderWidth;
p.drawRect( x + noteWidth - endmarkWidth, y, endmarkWidth, noteHeight );
}
}
void PianoRoll::drawDetuningInfo( QPainter & _p, const Note * _n, int _x,
int _y ) const
{
int middle_y = _y + m_keyLineHeight / 2;
_p.setPen(m_noteColor);
_p.setClipRect(
m_whiteKeyWidth,
PR_TOP_MARGIN,
width() - m_whiteKeyWidth,
keyAreaBottom() - PR_TOP_MARGIN);
// Draw lines for the detuning automation, treating cubic hermit curves
// as straight lines for now. Also draw discrete jumps.
int old_x = 0;
int old_y = 0;
timeMap & map = _n->detuning()->automationClip()->getTimeMap();
for (timeMap::const_iterator it = map.begin(); it != map.end(); ++it)
{
// Current node values
int cur_ticks = POS(it);
int cur_x = _x + cur_ticks * m_ppb / TimePos::ticksPerBar();
const float cur_level = INVAL(it);
int cur_y = middle_y - cur_level * m_keyLineHeight;
// First line to represent the inValue of the first node
if (it == map.begin())
{
_p.drawLine(cur_x - 1, cur_y, cur_x + 1, cur_y);
_p.drawLine(cur_x, cur_y - 1, cur_x, cur_y + 1);
}
// All subsequent lines will take the outValue of the previous node
// and the inValue of the current node. It will also draw a vertical
// line if there was a discrete jump (from old_x,old_y to pre_x,pre_y)
else
{
// Previous node values (based on outValue). We just calculate
// the y level because the x will be the same as old_x.
const float pre_level = OUTVAL(it - 1);
int pre_y = middle_y - pre_level * m_keyLineHeight;
// Draws the line representing the discrete jump if there's one
if (old_y != pre_y)
{
_p.drawLine(old_x, old_y, old_x, pre_y);
}
// Now draw the lines representing the actual progression from one
// node to the other
switch (_n->detuning()->automationClip()->progressionType())
{
case AutomationClip::ProgressionType::Discrete:
_p.drawLine(old_x, pre_y, cur_x, pre_y);
_p.drawLine(cur_x, pre_y, cur_x, cur_y);
break;
case AutomationClip::ProgressionType::CubicHermite: /* TODO */
case AutomationClip::ProgressionType::Linear:
_p.drawLine(old_x, pre_y, cur_x, cur_y);
break;
}
// If we are in the last node and there's a discrete jump, we draw a
// vertical line representing it
if ((it + 1) == map.end())
{
const float last_level = OUTVAL(it);
if (cur_level != last_level)
{
int last_y = middle_y - last_level * m_keyLineHeight;
_p.drawLine(cur_x, cur_y, cur_x, last_y);
}
}
}
old_x = cur_x;
old_y = cur_y;
}
}
void PianoRoll::removeSelection()
{
m_selectStartTick = 0;
m_selectedTick = 0;
m_selectStartKey = 0;
m_selectedKeys = 0;
}
void PianoRoll::clearSelectedNotes()
{
if( m_midiClip != nullptr )
{
for( Note *note : m_midiClip->notes() )
{
note->setSelected( false );
}
}
}
void PianoRoll::shiftSemiTone(int amount) //Shift notes by amount semitones
{
if (!hasValidMidiClip()) { return; }
auto selectedNotes = getSelectedNotes();
//If no notes are selected, shift all of them, otherwise shift selection
if (selectedNotes.empty()) { shiftSemiTone(m_midiClip->notes(), amount); }
else { shiftSemiTone(selectedNotes, amount); }
}
void PianoRoll::shiftSemiTone(const NoteVector& notes, int amount)
{
m_midiClip->addJournalCheckPoint();
for (Note *note : notes) { note->setKey( note->key() + amount ); }
m_midiClip->rearrangeAllNotes();
m_midiClip->dataChanged();
//We modified the song
update();
getGUI()->songEditor()->update();
}
void PianoRoll::shiftPos(int amount) //Shift notes pos by amount
{
if (!hasValidMidiClip()) { return; }
auto selectedNotes = getSelectedNotes();
//If no notes are selected, shift all of them, otherwise shift selection
if (selectedNotes.empty()) { shiftPos(m_midiClip->notes(), amount); }
else { shiftPos(selectedNotes, amount); }
}
void PianoRoll::shiftPos(const NoteVector& notes, int amount)
{
m_midiClip->addJournalCheckPoint();
if (notes.empty()) {
return;
}
auto leftMostPos = notes.front()->pos();
//Limit leftwards shifts to prevent moving left of clip start
auto shiftAmount = (leftMostPos > -amount) ? amount : -leftMostPos;
if (shiftAmount == 0) { return; }
for (Note *note : notes) { note->setPos( note->pos() + shiftAmount ); }
m_midiClip->rearrangeAllNotes();
m_midiClip->updateLength();
m_midiClip->dataChanged();
// we modified the song
update();
getGUI()->songEditor()->update();
}
bool PianoRoll::isSelection() const // are any notes selected?
{
for( const Note *note : m_midiClip->notes() )
{
if( note->selected() )
{
return true;
}
}
return false;
}
int PianoRoll::selectionCount() const // how many notes are selected?
{
return getSelectedNotes().size();
}
void PianoRoll::keyPressEvent(QKeyEvent* ke)
{
if(m_stepRecorder.isRecording())
{
bool handled = m_stepRecorder.keyPressEvent(ke);
if(handled)
{
ke->accept();
update();
return;
}
}
if( hasValidMidiClip() && ke->modifiers() == Qt::NoModifier )
{
const int key_num = PianoView::getKeyFromKeyEvent( ke );
if (!ke->isAutoRepeat() && key_num > -1)
{
m_midiClip->instrumentTrack()->pianoModel()->handleKeyPress(key_num);
// if a chord is set, play all chord notes (simulate click on all):
playChordNotes(key_num);
ke->accept();
}
}
switch( ke->key() )
{
case Qt::Key_Up:
case Qt::Key_Down:
{
int direction = (ke->key() == Qt::Key_Up ? +1 : -1);
if( ( ke->modifiers() & Qt::ControlModifier ) && m_action == Action::None )
{
// shift selection by one octave
// if nothing selected, shift _everything_
if (hasValidMidiClip())
{
// An octave could potentially be greater or less than twelve semitones if the microtuner is in use.
const auto microtuner = m_midiClip->instrumentTrack()->microtuner();
if (microtuner->enabled())
{
shiftSemiTone(microtuner->octaveSize() * direction);
}
else
{
shiftSemiTone(12 * direction);
}
}
}
else if((ke->modifiers() & Qt::ShiftModifier) && m_action == Action::None)
{
// Move selected notes by one semitone
if (hasValidMidiClip())
{
shiftSemiTone( 1 * direction );
}
}
else
{
// scroll
m_topBottomScroll->setValue( m_topBottomScroll->value() -
cm_scrollAmtVert * direction );
// if they are moving notes around or resizing,
// recalculate the note/resize position
if( m_action == Action::MoveNote ||
m_action == Action::ResizeNote )
{
dragNotes(
m_lastMouseX,
m_lastMouseY,
ke->modifiers() & Qt::AltModifier,
ke->modifiers() & Qt::ShiftModifier,
ke->modifiers() & Qt::ControlModifier
);
}
}
ke->accept();
break;
}
case Qt::Key_Right:
case Qt::Key_Left:
{
int direction = (ke->key() == Qt::Key_Right ? +1 : -1);
if( ke->modifiers() & Qt::ControlModifier && m_action == Action::None )
{
// Move selected notes by one bar to the left
if (hasValidMidiClip())
{
shiftPos( direction * TimePos::ticksPerBar() );
}
}
else if( ke->modifiers() & Qt::ShiftModifier && m_action == Action::None)
{
// move notes
if (hasValidMidiClip())
{
bool quantized = ! ( ke->modifiers() & Qt::AltModifier );
int amt = quantized ? quantization() : 1;
shiftPos( direction * amt );
}
}
else if( ke->modifiers() & Qt::AltModifier)
{
// switch to editing a clip adjacent to this one in the song editor
if (hasValidMidiClip())
{
MidiClip * c = direction > 0 ? m_midiClip->nextMidiClip()
: m_midiClip->previousMidiClip();
if(c != nullptr)
{
setCurrentMidiClip(c);
}
}
}
else
{
// scroll
m_leftRightScroll->setValue( m_leftRightScroll->value() +
direction * cm_scrollAmtHoriz );
// if they are moving notes around or resizing,
// recalculate the note/resize position
if( m_action == Action::MoveNote ||
m_action == Action::ResizeNote )
{
dragNotes(
m_lastMouseX,
m_lastMouseY,
ke->modifiers() & Qt::AltModifier,
ke->modifiers() & Qt::ShiftModifier,
ke->modifiers() & Qt::ControlModifier
);
}
}
ke->accept();
break;
}
case Qt::Key_A:
if( ke->modifiers() & Qt::ControlModifier )
{
ke->accept();
if (ke->modifiers() & Qt::ShiftModifier)
{
// Ctrl + Shift + A = deselect all notes
clearSelectedNotes();
}
else
{
// Ctrl + A = select all notes
selectAll();
}
update();
}
break;
case Qt::Key_Escape:
// On the Knife mode, ESC cancels it
if (m_editMode == EditMode::Knife)
{
cancelKnifeAction();
}
else
{
// Same as Ctrl + Shift + A
clearSelectedNotes();
}
break;
case Qt::Key_Backspace:
case Qt::Key_Delete:
deleteSelectedNotes();
ke->accept();
break;
case Qt::Key_Home:
m_timeLine->pos().setTicks( 0 );
m_timeLine->updatePosition();
ke->accept();
break;
case Qt::Key_0:
case Qt::Key_1:
case Qt::Key_2:
case Qt::Key_3:
case Qt::Key_4:
case Qt::Key_5:
case Qt::Key_6:
case Qt::Key_7:
case Qt::Key_8:
case Qt::Key_9:
{
int len = 1 + ke->key() - Qt::Key_0;
if( len == 10 )
{
len = 0;
}
if( ke->modifiers() & ( Qt::ControlModifier | Qt::KeypadModifier ) )
{
m_noteLenModel.setValue( len );
ke->accept();
}
else if( ke->modifiers() & Qt::AltModifier )
{
m_quantizeModel.setValue( len );
ke->accept();
}
break;
}
case Qt::Key_Control:
// Ctrl will not enter selection mode if we are
// in Knife mode, but unquantize it
if (m_editMode == EditMode::Knife)
{
break;
}
// Enter selection mode if:
// -> this window is active
// -> shift is not pressed
// (<S-C-drag> is shortcut for sticky note resize)
if ( !( ke->modifiers() & Qt::ShiftModifier ) && isActiveWindow() )
{
m_ctrlMode = m_editMode;
m_editMode = EditMode::Select;
setCursor( Qt::ArrowCursor );
ke->accept();
}
break;
default:
break;
}
update();
}
void PianoRoll::keyReleaseEvent(QKeyEvent* ke )
{
if( hasValidMidiClip() && ke->modifiers() == Qt::NoModifier )
{
const int key_num = PianoView::getKeyFromKeyEvent( ke );
if (!ke->isAutoRepeat() && key_num > -1)
{
m_midiClip->instrumentTrack()->pianoModel()->handleKeyRelease(key_num);
// if a chord is set, simulate click release on all chord notes
pauseChordNotes(key_num);
ke->accept();
}
}
switch( ke->key() )
{
case Qt::Key_Control:
if (m_editMode == EditMode::Knife)
{
break;
}
computeSelectedNotes( ke->modifiers() & Qt::ShiftModifier);
m_editMode = m_ctrlMode;
update();
break;
// update after undo/redo
case Qt::Key_Z:
case Qt::Key_R:
if( hasValidMidiClip() && ke->modifiers() == Qt::ControlModifier )
{
update();
}
break;
}
update();
}
void PianoRoll::leaveEvent(QEvent * e )
{
QWidget::leaveEvent( e );
s_textFloat->hide();
update(); // cleaning inner mouse-related graphics
}
int PianoRoll::noteEditTop() const
{
return keyAreaBottom() + NOTE_EDIT_RESIZE_BAR;
}
int PianoRoll::noteEditBottom() const
{
return height() - PR_BOTTOM_MARGIN;
}
int PianoRoll::noteEditRight() const
{
return width() - PR_RIGHT_MARGIN;
}
int PianoRoll::noteEditLeft() const
{
return m_whiteKeyWidth;
}
int PianoRoll::keyAreaTop() const
{
return PR_TOP_MARGIN;
}
int PianoRoll::keyAreaBottom() const
{
return height() - PR_BOTTOM_MARGIN - m_notesEditHeight;
}
void PianoRoll::mousePressEvent(QMouseEvent * me )
{
m_startedWithShift = me->modifiers() & Qt::ShiftModifier;
if( ! hasValidMidiClip() )
{
return;
}
// -- Knife
if (m_editMode == EditMode::Knife && me->button() == Qt::LeftButton)
{
NoteVector n;
Note* note = noteUnderMouse();
if (note)
{
n.push_back(note);
updateKnifePos(me);
// Call splitNotes for the note
m_midiClip->splitNotes(n, TimePos(m_knifeTickPos));
}
update();
return;
}
if( m_editMode == EditMode::Detuning && noteUnderMouse() )
{
static QPointer<AutomationClip> detuningClip = nullptr;
if (detuningClip.data() != nullptr)
{
detuningClip->disconnect(this);
}
Note* n = noteUnderMouse();
if (n->detuning() == nullptr)
{
n->createDetuning();
}
detuningClip = n->detuning()->automationClip();
connect(detuningClip.data(), SIGNAL(dataChanged()), this, SLOT(update()));
getGUI()->automationEditor()->setGhostMidiClip(m_midiClip);
getGUI()->automationEditor()->open(detuningClip);
return;
}
// if holding control, go to selection mode unless shift is also pressed
if( me->modifiers() & Qt::ControlModifier && m_editMode != EditMode::Select )
{
m_ctrlMode = m_editMode;
m_editMode = EditMode::Select;
setCursor( Qt::ArrowCursor );
update();
}
// keep track of the point where the user clicked down
if( me->button() == Qt::LeftButton )
{
m_moveStartX = me->x();
m_moveStartY = me->y();
}
if(me->button() == Qt::LeftButton &&
me->y() > keyAreaBottom() && me->y() < noteEditTop())
{
// resizing the note edit area
m_action = Action::ResizeNoteEditArea;
return;
}
if( me->y() > PR_TOP_MARGIN )
{
bool edit_note = ( me->y() > noteEditTop() );
int key_num = getKey( me->y() );
int x = me->x();
if (x > m_whiteKeyWidth)
{
// set, move or resize note
x -= m_whiteKeyWidth;
// get tick in which the user clicked
int pos_ticks = x * TimePos::ticksPerBar() / m_ppb +
m_currentPosition;
// get note-vector of current MIDI clip
const NoteVector & notes = m_midiClip->notes();
// will be our iterator in the following loop
auto it = notes.rbegin();
// loop through whole note-vector...
while (it != notes.rend())
{
Note *note = *it;
TimePos len = note->length();
if( len < 0 )
{
len = 4;
}
// and check whether the user clicked on an
// existing note or an edit-line
if( pos_ticks >= note->pos() &&
len > 0 &&
(
( ! edit_note &&
pos_ticks <= note->pos() + len &&
note->key() == key_num )
||
( edit_note &&
pos_ticks <= note->pos() +
NOTE_EDIT_LINE_WIDTH * TimePos::ticksPerBar() / m_ppb )
)
)
{
break;
}
++it;
}
// first check whether the user clicked in note-edit-
// area
if( edit_note )
{
m_midiClip->addJournalCheckPoint();
// scribble note edit changes
mouseMoveEvent( me );
return;
}
// left button??
else if( me->button() == Qt::LeftButton &&
m_editMode == EditMode::Draw )
{
// whether this action creates new note(s) or not
bool is_new_note = false;
Note * created_new_note = nullptr;
// did it reach end of vector because
// there's no note??
if (it == notes.rend())
{
is_new_note = true;
m_midiClip->addJournalCheckPoint();
// then set new note
// clear selection and select this new note
clearSelectedNotes();
// +32 to quanitize the note correctly when placing notes with
// the mouse. We do this here instead of in note.quantized
// because live notes should still be quantized at the half.
TimePos note_pos( pos_ticks - ( quantization() / 2 ) );
TimePos note_len( newNoteLen() );
Note new_note( note_len, note_pos, key_num );
new_note.setSelected( true );
new_note.setPanning( m_lastNotePanning );
new_note.setVolume( m_lastNoteVolume );
created_new_note = m_midiClip->addNote( new_note );
const InstrumentFunctionNoteStacking::Chord & chord = InstrumentFunctionNoteStacking::ChordTable::getInstance()
.getChordByName( m_chordModel.currentText() );
if( ! chord.isEmpty() )
{
// if a chord is selected, create following notes in chord
// or arpeggio mode
const bool arpeggio = me->modifiers() & Qt::ShiftModifier;
for( int i = 1; i < chord.size(); i++ )
{
if( arpeggio )
{
note_pos += note_len;
}
Note new_note( note_len, note_pos, key_num + chord[i] );
new_note.setSelected( true );
new_note.setPanning( m_lastNotePanning );
new_note.setVolume( m_lastNoteVolume );
m_midiClip->addNote( new_note );
}
}
// reset it so that it can be used for
// ops (move, resize) after this
// code-block
it = notes.rbegin();
while (it != notes.rend() && *it != created_new_note)
{
++it;
}
}
Note *current_note = *it;
m_currentNote = current_note;
m_lastNotePanning = current_note->getPanning();
m_lastNoteVolume = current_note->getVolume();
m_lenOfNewNotes = current_note->length();
// remember which key and tick we started with
m_mouseDownKey = m_startKey;
m_mouseDownTick = m_currentPosition;
//If clicked on an unselected note, remove selection and select that new note
if (!m_currentNote->selected())
{
clearSelectedNotes();
m_currentNote->setSelected( true );
}
auto selectedNotes = getSelectedNotes();
m_moveBoundaryLeft = selectedNotes.front()->pos().getTicks();
m_moveBoundaryRight = selectedNotes.front()->endPos();
m_moveBoundaryBottom = selectedNotes.front()->key();
m_moveBoundaryTop = m_moveBoundaryBottom;
//Figure out the bounding box of all the selected notes
for (Note *note: selectedNotes)
{
// remember note starting positions
note->setOldKey( note->key() );
note->setOldPos( note->pos() );
note->setOldLength( note->length() );
m_moveBoundaryLeft = qMin(note->pos().getTicks(), (tick_t) m_moveBoundaryLeft);
m_moveBoundaryRight = qMax((int) note->endPos(), m_moveBoundaryRight);
m_moveBoundaryBottom = qMin(note->key(), m_moveBoundaryBottom);
m_moveBoundaryTop = qMax(note->key(), m_moveBoundaryTop);
}
// clicked at the "tail" of the note?
if( pos_ticks * m_ppb / TimePos::ticksPerBar() >
m_currentNote->endPos() * m_ppb / TimePos::ticksPerBar() - RESIZE_AREA_WIDTH
&& m_currentNote->length() > 0 )
{
m_midiClip->addJournalCheckPoint();
// then resize the note
m_action = Action::ResizeNote;
//Calculate the minimum length we should allow when resizing
//each note, and let all notes use the smallest one found
m_minResizeLen = quantization();
for (Note *note : selectedNotes)
{
//Notes from the pattern editor can have a negative length, so
//change their length to the displayed one before resizing
if (note->oldLength() <= 0) { note->setOldLength(4); }
//Let the note be sized down by quantized increments, stopping
//when the next step down would result in a negative length
int thisMin = note->oldLength() % quantization();
//The initial value for m_minResizeLen is the minimum length of
//a note divisible by the current Q. Therefore we ignore notes
//where thisMin == 0 when checking for a new minimum
if (thisMin > 0 && thisMin < m_minResizeLen) { m_minResizeLen = thisMin; }
}
// set resize-cursor
setCursor( Qt::SizeHorCursor );
}
else
{
if( ! created_new_note )
{
m_midiClip->addJournalCheckPoint();
}
// otherwise move it
m_action = Action::MoveNote;
// set move-cursor
setCursor( Qt::SizeAllCursor );
// if they're holding shift, copy all selected notes
if( ! is_new_note && me->modifiers() & Qt::ShiftModifier )
{
for (Note *note: selectedNotes)
{
Note *newNote = m_midiClip->addNote(*note, false);
newNote->setSelected(false);
}
if (!selectedNotes.empty())
{
// added new notes, so must update engine, song, etc
Engine::getSong()->setModified();
update();
getGUI()->songEditor()->update();
}
}
// play the note
testPlayNote( m_currentNote );
}
Engine::getSong()->setModified();
}
else if( ( me->buttons() == Qt::RightButton &&
m_editMode == EditMode::Draw ) ||
m_editMode == EditMode::Erase )
{
// erase single note
m_mouseDownRight = true;
if (it != notes.rend())
{
m_midiClip->addJournalCheckPoint();
m_midiClip->removeNote( *it );
Engine::getSong()->setModified();
}
}
else if( me->button() == Qt::LeftButton &&
m_editMode == EditMode::Select )
{
// select an area of notes
m_selectStartTick = pos_ticks;
m_selectedTick = 0;
m_selectStartKey = key_num;
m_selectedKeys = 1;
m_action = Action::SelectNotes;
// call mousemove to fix glitch where selection
// appears in wrong spot on mousedown
mouseMoveEvent( me );
}
update();
}
else if( me->y() < keyAreaBottom() )
{
// reference to last key needed for both
// right click (used for copy all keys on note)
// and for playing the key when left-clicked
m_lastKey = key_num;
// clicked on keyboard on the left
if( me->buttons() == Qt::RightButton )
{
// right click - tone marker contextual menu
m_pianoKeySelected = getKey( me->y() );
m_semiToneMarkerMenu->popup( mapToGlobal( QPoint( me->x(), me->y() ) ) );
}
else if( me->buttons() == Qt::LeftButton )
{
// left click - play the note
int v = ((float) x) / ((float) m_whiteKeyWidth) * MidiDefaultVelocity;
m_midiClip->instrumentTrack()->pianoModel()->handleKeyPress(key_num, v);
// if a chord is set, play the chords notes as well:
playChordNotes(key_num, v);
}
}
else
{
if( me->buttons() == Qt::LeftButton )
{
// clicked in the box below the keys to the left of note edit area
m_noteEditMode = (NoteEditMode)(((int)m_noteEditMode)+1);
if( m_noteEditMode == NoteEditMode::Count )
{
m_noteEditMode = (NoteEditMode) 0;
}
repaint();
}
else if( me->buttons() == Qt::RightButton )
{
// pop menu asking which one they want to edit
m_noteEditMenu->popup( mapToGlobal( QPoint( me->x(), me->y() ) ) );
}
}
}
}
void PianoRoll::mouseDoubleClickEvent(QMouseEvent * me )
{
if( ! hasValidMidiClip() )
{
return;
}
// if they clicked in the note edit area, enter value for the volume bar
if( me->x() > noteEditLeft() && me->x() < noteEditRight()
&& me->y() > noteEditTop() && me->y() < noteEditBottom() )
{
// get values for going through notes
int pixel_range = 4;
int x = me->x() - m_whiteKeyWidth;
const int ticks_start = ( x-pixel_range/2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
const int ticks_end = ( x+pixel_range/2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
const int ticks_middle = x * TimePos::ticksPerBar() / m_ppb + m_currentPosition;
// go through notes to figure out which one we want to change
bool altPressed = me->modifiers() & Qt::AltModifier;
NoteVector nv;
for ( Note * i : m_midiClip->notes() )
{
if( i->withinRange( ticks_start, ticks_end ) || ( i->selected() && !altPressed ) )
{
nv.push_back(i);
}
}
// make sure we're on a note
if( nv.size() > 0 )
{
const Note * closest = nullptr;
int closest_dist = 9999999;
// if we caught multiple notes and we're not editing a
// selection, find the closest...
if( nv.size() > 1 && !isSelection() )
{
for ( const Note * i : nv )
{
const int dist = qAbs( i->pos().getTicks() - ticks_middle );
if( dist < closest_dist ) { closest = i; closest_dist = dist; }
}
// ... then remove all notes from the vector that aren't on the same exact time
auto it = nv.begin();
while (it != nv.end())
{
const Note *note = *it;
if( note->pos().getTicks() != closest->pos().getTicks() )
{
it = nv.erase( it );
}
else
{
it++;
}
}
}
enterValue( &nv );
}
}
else
{
QWidget::mouseDoubleClickEvent(me);
}
}
void PianoRoll::testPlayNote( Note * n )
{
m_lastKey = n->key();
if( ! n->isPlaying() && ! m_recording && ! m_stepRecorder.isRecording())
{
n->setIsPlaying( true );
const int baseVelocity = m_midiClip->instrumentTrack()->midiPort()->baseVelocity();
m_midiClip->instrumentTrack()->pianoModel()->handleKeyPress(n->key(), n->midiVelocity(baseVelocity));
// if a chord is set, play the chords notes as well:
playChordNotes(n->key(), n->midiVelocity(baseVelocity));
MidiEvent event( MidiMetaEvent, -1, n->key(), panningToMidi( n->getPanning() ) );
event.setMetaEvent( MidiNotePanning );
m_midiClip->instrumentTrack()->processInEvent( event, 0 );
}
}
void PianoRoll::pauseTestNotes( bool pause )
{
for (Note *note : m_midiClip->notes())
{
if( note->isPlaying() )
{
if( pause )
{
// stop note
m_midiClip->instrumentTrack()->pianoModel()->handleKeyRelease( note->key() );
// if a chord was set, stop the chords notes as well:
pauseChordNotes(note->key());
}
else
{
// start note
note->setIsPlaying( false );
testPlayNote( note );
}
}
}
}
void PianoRoll::playChordNotes(int key, int velocity)
{
// if a chord is set, play the chords notes beside the base note.
Piano *pianoModel = m_midiClip->instrumentTrack()->pianoModel();
const InstrumentFunctionNoteStacking::Chord & chord =
InstrumentFunctionNoteStacking::ChordTable::getInstance().getChordByName(
m_chordModel.currentText());
if (!chord.isEmpty())
{
for (int i = 1; i < chord.size(); ++i)
{
pianoModel->handleKeyPress(key + chord[i], velocity);
}
}
}
void PianoRoll::pauseChordNotes(int key)
{
// if a chord was set, stop the chords notes beside the base note.
Piano *pianoModel = m_midiClip->instrumentTrack()->pianoModel();
const InstrumentFunctionNoteStacking::Chord & chord =
InstrumentFunctionNoteStacking::ChordTable::getInstance().getChordByName(
m_chordModel.currentText());
if (!chord.isEmpty())
{
for (int i = 1; i < chord.size(); ++i)
{
pianoModel->handleKeyRelease(key + chord[i]);
}
}
}
void PianoRoll::setKnifeAction()
{
if (m_editMode != EditMode::Knife)
{
m_knifeMode = m_editMode;
m_editMode = EditMode::Knife;
m_action = Action::Knife;
setCursor(Qt::ArrowCursor);
update();
}
}
void PianoRoll::cancelKnifeAction()
{
m_editMode = m_knifeMode;
m_action = Action::None;
update();
}
void PianoRoll::testPlayKey( int key, int velocity, int pan )
{
Piano *pianoModel = m_midiClip->instrumentTrack()->pianoModel();
// turn off old key
pianoModel->handleKeyRelease( m_lastKey );
// if a chord was set, stop the chords notes as well
pauseChordNotes(m_lastKey);
// remember which one we're playing
m_lastKey = key;
// play new key
pianoModel->handleKeyPress( key, velocity );
// and if a chord is set, play chord notes:
playChordNotes(key, velocity);
}
void PianoRoll::computeSelectedNotes(bool shift)
{
if( m_selectStartTick == 0 &&
m_selectedTick == 0 &&
m_selectStartKey == 0 &&
m_selectedKeys == 0 )
{
// don't bother, there's no selection
return;
}
// setup selection-vars
int sel_pos_start = m_selectStartTick;
int sel_pos_end = m_selectStartTick+m_selectedTick;
if( sel_pos_start > sel_pos_end )
{
qSwap<int>( sel_pos_start, sel_pos_end );
}
int sel_key_start = m_selectStartKey - m_startKey + 1;
int sel_key_end = sel_key_start + m_selectedKeys;
if( sel_key_start > sel_key_end )
{
qSwap<int>( sel_key_start, sel_key_end );
}
//int y_base = noteEditTop() - 1;
if( hasValidMidiClip() )
{
for( Note *note : m_midiClip->notes() )
{
// make a new selection unless they're holding shift
if( ! shift )
{
note->setSelected( false );
}
int len_ticks = note->length();
if( len_ticks == 0 )
{
continue;
}
else if( len_ticks < 0 )
{
len_ticks = 4;
}
const int key = note->key() - m_startKey + 1;
int pos_ticks = note->pos();
// if the selection even barely overlaps the note
if( key > sel_key_start &&
key <= sel_key_end &&
pos_ticks + len_ticks > sel_pos_start &&
pos_ticks < sel_pos_end )
{
// remove from selection when holding shift
bool selected = shift && note->selected();
note->setSelected( ! selected);
}
}
}
removeSelection();
update();
}
void PianoRoll::mouseReleaseEvent( QMouseEvent * me )
{
bool mustRepaint = false;
s_textFloat->hide();
// Quit knife mode if we pressed and released the right mouse button
if (m_editMode == EditMode::Knife && me->button() == Qt::RightButton)
{
cancelKnifeAction();
}
if( me->button() & Qt::LeftButton )
{
mustRepaint = true;
if( m_action == Action::SelectNotes && m_editMode == EditMode::Select )
{
// select the notes within the selection rectangle and
// then destroy the selection rectangle
computeSelectedNotes(
me->modifiers() & Qt::ShiftModifier );
}
else if( m_action == Action::MoveNote )
{
// we moved one or more notes so they have to be
// moved properly according to new starting-
// time in the note-array of clip
m_midiClip->rearrangeAllNotes();
}
if( m_action == Action::MoveNote || m_action == Action::ResizeNote )
{
// if we only moved one note, deselect it so we can
// edit the notes in the note edit area
if( selectionCount() == 1 )
{
clearSelectedNotes();
}
}
}
if( me->button() & Qt::RightButton )
{
m_mouseDownRight = false;
mustRepaint = true;
}
if( hasValidMidiClip() )
{
// turn off all notes that are playing
for ( Note *note : m_midiClip->notes() )
{
if( note->isPlaying() )
{
m_midiClip->instrumentTrack()->pianoModel()->
handleKeyRelease( note->key() );
pauseChordNotes(note->key());
note->setIsPlaying( false );
}
}
// stop playing keys that we let go of
m_midiClip->instrumentTrack()->pianoModel()->
handleKeyRelease( m_lastKey );
pauseChordNotes(m_lastKey);
}
m_currentNote = nullptr;
if (m_action != Action::Knife)
{
m_action = Action::None;
}
if( m_editMode == EditMode::Draw )
{
setCursor( Qt::ArrowCursor );
}
if( mustRepaint )
{
repaint();
}
}
void PianoRoll::mouseMoveEvent( QMouseEvent * me )
{
if( ! hasValidMidiClip() )
{
update();
return;
}
if( m_action == Action::None && me->buttons() == 0 )
{
// When cursor is between note editing area and volume/panning
// area show vertical size cursor.
if( me->y() > keyAreaBottom() && me->y() < noteEditTop() )
{
setCursor( Qt::SizeVerCursor );
return;
}
}
else if( m_action == Action::ResizeNoteEditArea )
{
// Don't try to show more keys than the full keyboard, bail if trying to
if (m_pianoKeysVisible == NumKeys && me->y() > m_moveStartY)
{
return;
}
int newHeight = height() - me->y();
if (me->y() < KEY_AREA_MIN_HEIGHT)
{
newHeight = height() - KEY_AREA_MIN_HEIGHT -
PR_TOP_MARGIN - PR_BOTTOM_MARGIN; // - NOTE_EDIT_RESIZE_BAR
}
// change m_notesEditHeight and then repaint
m_notesEditHeight = qMax(NOTE_EDIT_MIN_HEIGHT, newHeight);
m_userSetNotesEditHeight = m_notesEditHeight;
m_stepRecorderWidget.setBottomMargin(PR_BOTTOM_MARGIN + m_notesEditHeight);
updateScrollbars();
updatePositionLineHeight();
repaint();
return;
}
// Update Knife position if we are on knife mode
if (m_editMode == EditMode::Knife)
{
updateKnifePos(me);
}
if( me->y() > PR_TOP_MARGIN || m_action != Action::None )
{
bool edit_note = ( me->y() > noteEditTop() )
&& m_action != Action::SelectNotes;
int key_num = getKey( me->y() );
int x = me->x();
// see if they clicked on the keyboard on the left
if (x < m_whiteKeyWidth && m_action == Action::None
&& ! edit_note && key_num != m_lastKey
&& me->buttons() & Qt::LeftButton )
{
// clicked on a key, play the note
testPlayKey(key_num, ((float) x) / ((float) m_whiteKeyWidth) * MidiDefaultVelocity, 0);
update();
return;
}
x -= m_whiteKeyWidth;
if( me->buttons() & Qt::LeftButton
&& m_editMode == EditMode::Draw
&& (m_action == Action::MoveNote || m_action == Action::ResizeNote ) )
{
// handle moving notes and resizing them
bool replay_note = key_num != m_lastKey
&& m_action == Action::MoveNote;
if( replay_note || ( m_action == Action::MoveNote && ( me->modifiers() & Qt::ShiftModifier ) && ! m_startedWithShift ) )
{
pauseTestNotes();
}
dragNotes(
me->x(),
me->y(),
me->modifiers() & Qt::AltModifier,
me->modifiers() & Qt::ShiftModifier,
me->modifiers() & Qt::ControlModifier
);
if( replay_note && m_action == Action::MoveNote && ! ( ( me->modifiers() & Qt::ShiftModifier ) && ! m_startedWithShift ) )
{
pauseTestNotes( false );
}
}
else if( m_editMode != EditMode::Erase &&
( edit_note || m_action == Action::ChangeNoteProperty ) &&
( me->buttons() & Qt::LeftButton || me->buttons() & Qt::MiddleButton
|| ( me->buttons() & Qt::RightButton && me->modifiers() & Qt::ShiftModifier ) ) )
{
// editing note properties
// Change notes within a certain pixel range of where
// the mouse cursor is
int pixel_range = 14;
// convert to ticks so that we can check which notes
// are in the range
int ticks_start = ( x-pixel_range/2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
int ticks_end = ( x+pixel_range/2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
// get note-vector of current MIDI clip
const NoteVector & notes = m_midiClip->notes();
// determine what volume/panning to set note to
// if middle-click, set to defaults
volume_t vol = DefaultVolume;
panning_t pan = DefaultPanning;
if( me->buttons() & Qt::LeftButton )
{
vol = qBound<int>( MinVolume,
MinVolume +
( ( (float)noteEditBottom() ) - ( (float)me->y() ) ) /
( (float)( noteEditBottom() - noteEditTop() ) ) *
( MaxVolume - MinVolume ),
MaxVolume );
pan = qBound<int>( PanningLeft,
PanningLeft +
( (float)( noteEditBottom() - me->y() ) ) /
( (float)( noteEditBottom() - noteEditTop() ) ) *
( (float)( PanningRight - PanningLeft ) ),
PanningRight);
}
if( m_noteEditMode == NoteEditMode::Volume )
{
m_lastNoteVolume = vol;
showVolTextFloat( vol, me->pos() );
}
else if( m_noteEditMode == NoteEditMode::Panning )
{
m_lastNotePanning = pan;
showPanTextFloat( pan, me->pos() );
}
// When alt is pressed we only edit the note under the cursor
bool altPressed = me->modifiers() & Qt::AltModifier;
// We iterate from last note in MIDI clip to the first,
// chronologically
auto it = notes.rbegin();
while (it != notes.rend())
{
Note* n = *it;
bool isUnderPosition = n->withinRange( ticks_start, ticks_end );
// Play note under the cursor
if ( isUnderPosition ) { testPlayNote( n ); }
// If note is:
// Under the cursor, when there is no selection
// Selected, and alt is not pressed
// Under the cursor, selected, and alt is pressed
if ( ( isUnderPosition && !isSelection() ) ||
( n->selected() && !altPressed ) ||
( isUnderPosition && n->selected() && altPressed )
)
{
if( m_noteEditMode == NoteEditMode::Volume )
{
n->setVolume( vol );
const int baseVelocity = m_midiClip->instrumentTrack()->midiPort()->baseVelocity();
m_midiClip->instrumentTrack()->processInEvent( MidiEvent( MidiKeyPressure, -1, n->key(), n->midiVelocity( baseVelocity ) ) );
}
else if( m_noteEditMode == NoteEditMode::Panning )
{
n->setPanning( pan );
MidiEvent evt( MidiMetaEvent, -1, n->key(), panningToMidi( pan ) );
evt.setMetaEvent( MidiNotePanning );
m_midiClip->instrumentTrack()->processInEvent( evt );
}
}
else if( n->isPlaying() && !isSelection() )
{
// mouse not over this note, stop playing it.
m_midiClip->instrumentTrack()->pianoModel()->handleKeyRelease( n->key() );
pauseChordNotes(n->key());
n->setIsPlaying( false );
}
++it;
}
// Emit MIDI clip has changed
m_midiClip->dataChanged();
}
else if( me->buttons() == Qt::NoButton && m_editMode == EditMode::Draw )
{
// set move- or resize-cursor
// get tick in which the cursor is posated
int pos_ticks = ( x * TimePos::ticksPerBar() ) /
m_ppb + m_currentPosition;
// get note-vector of current MIDI clip
const NoteVector & notes = m_midiClip->notes();
// will be our iterator in the following loop
auto it = notes.rbegin();
// loop through whole note-vector...
while (it != notes.rend())
{
Note *note = *it;
// and check whether the cursor is over an
// existing note
if( pos_ticks >= note->pos() &&
pos_ticks <= note->pos() +
note->length() &&
note->key() == key_num &&
note->length() > 0 )
{
break;
}
++it;
}
// did it reach end of vector because there's
// no note??
if (it != notes.rend())
{
Note *note = *it;
// x coordinate of the right edge of the note
int noteRightX = ( note->pos() + note->length() -
m_currentPosition) * m_ppb/TimePos::ticksPerBar();
// cursor at the "tail" of the note?
bool atTail = note->length() > 0 && x > noteRightX -
RESIZE_AREA_WIDTH;
Qt::CursorShape cursorShape = atTail ? Qt::SizeHorCursor :
Qt::SizeAllCursor;
setCursor( cursorShape );
}
else
{
// the cursor is over no note, so restore cursor
setCursor( Qt::ArrowCursor );
}
}
else if( me->buttons() & Qt::LeftButton &&
m_editMode == EditMode::Select &&
m_action == Action::SelectNotes )
{
// change size of selection
// get tick in which the cursor is posated
int pos_ticks = x * TimePos::ticksPerBar() / m_ppb +
m_currentPosition;
m_selectedTick = pos_ticks - m_selectStartTick;
if( (int) m_selectStartTick + m_selectedTick < 0 )
{
m_selectedTick = -static_cast<int>(
m_selectStartTick );
}
m_selectedKeys = key_num - m_selectStartKey;
if( key_num <= m_selectStartKey )
{
--m_selectedKeys;
}
}
else if( ( m_editMode == EditMode::Draw && me->buttons() & Qt::RightButton )
|| ( m_editMode == EditMode::Erase && me->buttons() ) )
{
// holding down right-click to delete notes or holding down
// any key if in erase mode
// get tick in which the user clicked
int pos_ticks = x * TimePos::ticksPerBar() / m_ppb +
m_currentPosition;
// get note-vector of current MIDI clip
const NoteVector & notes = m_midiClip->notes();
// will be our iterator in the following loop
auto it = notes.begin();
// loop through whole note-vector...
while( it != notes.end() )
{
Note *note = *it;
TimePos len = note->length();
if( len < 0 )
{
len = 4;
}
// and check whether the user clicked on an
// existing note or an edit-line
if( pos_ticks >= note->pos() &&
len > 0 &&
(
( ! edit_note &&
pos_ticks <= note->pos() + len &&
note->key() == key_num )
||
( edit_note &&
pos_ticks <= note->pos() +
NOTE_EDIT_LINE_WIDTH *
TimePos::ticksPerBar() /
m_ppb )
)
)
{
// delete this note
it = m_midiClip->removeNote(it);
Engine::getSong()->setModified();
}
else
{
++it;
}
}
}
else if (me->buttons() == Qt::NoButton && m_editMode != EditMode::Draw && m_editMode != EditMode::Knife)
{
// Is needed to restore cursor when it previously was set to
// Qt::SizeVerCursor (between keyAreaBottom and noteEditTop)
setCursor( Qt::ArrowCursor );
}
}
else
{
if( me->buttons() & Qt::LeftButton &&
m_editMode == EditMode::Select &&
m_action == Action::SelectNotes )
{
int x = me->x() - m_whiteKeyWidth;
if( x < 0 && m_currentPosition > 0 )
{
x = 0;
QCursor::setPos( mapToGlobal( QPoint(
m_whiteKeyWidth,
me->y() ) ) );
if( m_currentPosition >= 4 )
{
m_leftRightScroll->setValue(
m_currentPosition - 4 );
}
else
{
m_leftRightScroll->setValue( 0 );
}
}
else if (x > width() - m_whiteKeyWidth)
{
x = width() - m_whiteKeyWidth;
QCursor::setPos( mapToGlobal( QPoint( width(),
me->y() ) ) );
m_leftRightScroll->setValue( m_currentPosition +
4 );
}
// get tick in which the cursor is posated
int pos_ticks = x * TimePos::ticksPerBar()/ m_ppb +
m_currentPosition;
m_selectedTick = pos_ticks -
m_selectStartTick;
if( (int) m_selectStartTick + m_selectedTick <
0 )
{
m_selectedTick = -static_cast<int>(
m_selectStartTick );
}
int key_num = getKey( me->y() );
int visible_keys = ( height() - PR_TOP_MARGIN -
PR_BOTTOM_MARGIN -
m_notesEditHeight ) /
m_keyLineHeight + 2;
const int s_key = m_startKey - 1;
if( key_num <= s_key )
{
QCursor::setPos( mapToGlobal( QPoint( me->x(),
keyAreaBottom() ) ) );
m_topBottomScroll->setValue(
m_topBottomScroll->value() + 1 );
key_num = s_key;
}
else if( key_num >= s_key + visible_keys )
{
QCursor::setPos( mapToGlobal( QPoint( me->x(),
PR_TOP_MARGIN ) ) );
m_topBottomScroll->setValue(
m_topBottomScroll->value() - 1 );
key_num = s_key + visible_keys;
}
m_selectedKeys = key_num - m_selectStartKey;
if( key_num <= m_selectStartKey )
{
--m_selectedKeys;
}
}
setCursor( Qt::ArrowCursor );
}
m_lastMouseX = me->x();
m_lastMouseY = me->y();
update();
}
void PianoRoll::updateKnifePos(QMouseEvent* me)
{
// Calculate the TimePos from the mouse
int mouseViewportPos = me->x() - m_whiteKeyWidth;
int mouseTickPos = mouseViewportPos * TimePos::ticksPerBar() / m_ppb + m_currentPosition;
// If ctrl is not pressed, quantize the position
if (!(me->modifiers() & Qt::ControlModifier))
{
mouseTickPos = floor(mouseTickPos / quantization()) * quantization();
}
m_knifeTickPos = mouseTickPos;
}
void PianoRoll::dragNotes(int x, int y, bool alt, bool shift, bool ctrl)
{
// dragging one or more notes around
// convert pixels to ticks and keys
int off_x = x - m_moveStartX;
int off_ticks = off_x * TimePos::ticksPerBar() / m_ppb;
int off_key = getKey( y ) - getKey( m_moveStartY );
// handle scroll changes while dragging
off_ticks -= m_mouseDownTick - m_currentPosition;
off_key -= m_mouseDownKey - m_startKey;
// get note-vector of current MIDI clip
const NoteVector & notes = m_midiClip->notes();
if (m_action == Action::MoveNote)
{
// Calculate the offset for either Nudge or Snap modes
int noteOffset = off_ticks;
if (m_gridMode == GridMode::Snap && quantization () > 1)
{
// Get the mouse timeline absolute position
TimePos mousePos(m_currentNote->oldPos().getTicks() + off_ticks);
// We create a mousePos that is relative to the end of the note instead
// of the beginning. That's to see if we will snap the beginning or end
// of the note
TimePos mousePosEnd(mousePos);
mousePosEnd += m_currentNote->oldLength();
// Now we quantize the mouse position to snap it to the grid
TimePos mousePosQ = mousePos.quantize(static_cast<float>(quantization()) / DefaultTicksPerBar);
TimePos mousePosEndQ = mousePosEnd.quantize(static_cast<float>(quantization()) / DefaultTicksPerBar);
bool snapEnd = abs(mousePosEndQ - mousePosEnd) < abs(mousePosQ - mousePos);
// Set the offset
noteOffset = snapEnd
? mousePosEndQ.getTicks() - m_currentNote->oldPos().getTicks() - m_currentNote->oldLength().getTicks()
: mousePosQ.getTicks() - m_currentNote->oldPos().getTicks();
}
else if (m_gridMode == GridMode::Nudge)
{
// if they're not holding alt, quantize the offset
if (!alt)
{
noteOffset = floor(off_ticks / quantization()) * quantization();
}
}
// Make sure notes won't go outside boundary conditions
if (m_moveBoundaryLeft + noteOffset < 0)
{
noteOffset = -m_moveBoundaryLeft;
}
if (m_moveBoundaryTop + off_key >= NumKeys)
{
off_key = -m_moveBoundaryTop + NumKeys - 1;
}
if (m_moveBoundaryBottom + off_key < 0)
{
off_key = -m_moveBoundaryBottom;
}
// Apply offset to all selected notes
for (Note *note : getSelectedNotes())
{
// Quick resize is only enabled on Nudge mode, since resizing the note
// while in Snap mode breaks the calculation of the note offset
if (shift && ! m_startedWithShift && m_gridMode == GridMode::Nudge)
{
// quick resize, toggled by holding shift after starting a note move, but not before
int ticks_new = note->oldLength().getTicks() + noteOffset;
if( ticks_new <= 0 )
{
ticks_new = 1;
}
note->setLength( TimePos( ticks_new ) );
m_lenOfNewNotes = note->length();
}
else
{
// moving note
// Final position of the note
TimePos posTicks(note->oldPos().getTicks() + noteOffset);
int key_num = note->oldKey() + off_key;
note->setPos(posTicks);
note->setKey(key_num);
}
}
}
else if (m_action == Action::ResizeNote)
{
// When resizing notes:
// If shift is not pressed, resize the selected notes but do not rearrange them
// If shift is pressed we resize and rearrange only the selected notes
// If shift + ctrl then we also rearrange all posterior notes (sticky)
// If shift is pressed but only one note is selected, apply sticky
// Quantize the resizing if alt is not pressed
if (!alt)
{
off_ticks = floor(off_ticks / quantization()) * quantization();
}
auto selectedNotes = getSelectedNotes();
if (shift)
{
// Algorithm:
// Relative to the starting point of the left-most selected note,
// all selected note start-points and *endpoints* (not length) should be scaled by a calculated factor.
// This factor is such that the endpoint of the note whose handle is being dragged should lie under the cursor.
// first, determine the start-point of the left-most selected note:
int stretchStartTick = -1;
for (const Note *note : selectedNotes)
{
if (stretchStartTick < 0 || note->oldPos().getTicks() < stretchStartTick)
{
stretchStartTick = note->oldPos().getTicks();
}
}
// determine the ending tick of the right-most selected note
const Note *posteriorNote = nullptr;
for (const Note *note : selectedNotes)
{
if (posteriorNote == nullptr ||
note->oldPos().getTicks() + note->oldLength().getTicks() >
posteriorNote->oldPos().getTicks() + posteriorNote->oldLength().getTicks())
{
posteriorNote = note;
}
}
int posteriorEndTick = posteriorNote->pos().getTicks() + posteriorNote->length().getTicks();
// end-point of the note whose handle is being dragged:
int stretchEndTick = m_currentNote->oldPos().getTicks() + m_currentNote->oldLength().getTicks();
// Calculate factor by which to scale the start-point and end-point of all selected notes
float scaleFactor = (float)(stretchEndTick - stretchStartTick + off_ticks) / qMax(1, stretchEndTick - stretchStartTick);
scaleFactor = qMax(0.0f, scaleFactor);
// process all selected notes & determine how much the endpoint of the right-most note was shifted
int posteriorDeltaThisFrame = 0;
for (Note *note : selectedNotes)
{
// scale relative start and end positions by scaleFactor
int newStart = stretchStartTick + scaleFactor *
(note->oldPos().getTicks() - stretchStartTick);
int newEnd = stretchStartTick + scaleFactor *
(note->oldPos().getTicks()+note->oldLength().getTicks() - stretchStartTick);
// if not holding alt, quantize the offsets
if (!alt)
{
// quantize start time
int oldStart = note->oldPos().getTicks();
int startDiff = newStart - oldStart;
startDiff = floor(startDiff / quantization()) * quantization();
newStart = oldStart + startDiff;
// quantize end time
int oldEnd = oldStart + note->oldLength().getTicks();
int endDiff = newEnd - oldEnd;
endDiff = floor(endDiff / quantization()) * quantization();
newEnd = oldEnd + endDiff;
}
int newLength = qMax(1, newEnd-newStart);
if (note == posteriorNote)
{
posteriorDeltaThisFrame = (newStart+newLength) -
(note->pos().getTicks() + note->length().getTicks());
}
note->setLength( TimePos(newLength) );
note->setPos( TimePos(newStart) );
m_lenOfNewNotes = note->length();
}
if (ctrl || selectionCount() == 1)
{
// if holding ctrl or only one note is selected, reposition posterior notes
for (Note *note : notes)
{
if (!note->selected() && note->pos().getTicks() >= posteriorEndTick)
{
int newStart = note->pos().getTicks() + posteriorDeltaThisFrame;
note->setPos( TimePos(newStart) );
}
}
}
}
else
{
// shift is not pressed; stretch length of selected notes but not their position
int minLength = alt ? 1 : m_minResizeLen.getTicks();
if (m_gridMode == GridMode::Snap)
{
// Calculate the end point of the note being dragged
TimePos oldEndPoint = m_currentNote->oldPos() + m_currentNote->oldLength();
// Quantize that position
TimePos quantizedEndPoint = Note::quantized(oldEndPoint, quantization());
// Add that difference to the offset from the resize
off_ticks += quantizedEndPoint - oldEndPoint;
}
for (Note *note : selectedNotes)
{
int newLength = qMax(minLength, note->oldLength() + off_ticks);
note->setLength(TimePos(newLength));
m_lenOfNewNotes = note->length();
}
}
}
m_midiClip->updateLength();
m_midiClip->dataChanged();
Engine::getSong()->setModified();
}
void PianoRoll::paintEvent(QPaintEvent * pe )
{
bool drawNoteNames = ConfigManager::inst()->value( "ui", "printnotelabels").toInt();
QStyleOption opt;
opt.initFrom( this );
QPainter p( this );
style()->drawPrimitive( QStyle::PE_Widget, &opt, &p, this );
QBrush bgColor = p.background();
// fill with bg color
p.fillRect( 0, 0, width(), height(), bgColor );
// set font-size to 80% of key line height
QFont f = p.font();
int keyFontSize = m_keyLineHeight * 0.8;
p.setFont(adjustedToPixelSize(f, keyFontSize));
QFontMetrics fontMetrics(p.font());
// G-1 is one of the widest; plus one pixel margin for the shadow
QRect const boundingRect = fontMetrics.boundingRect(QString("G-1")) + QMargins(0, 0, 1, 0);
// Order of drawing
// - vertical quantization lines
// - piano roll + horizontal key lines
// - alternating bar colors
// - vertical beat lines
// - vertical bar lines
// - marked semitones
// - note editing
// - notes
// - selection frame
// - highlight hovered note
// - note edit area resize bar
// - cursor mode icon
if (hasValidMidiClip())
{
int pianoAreaHeight = keyAreaBottom() - keyAreaTop();
m_pianoKeysVisible = pianoAreaHeight / m_keyLineHeight;
int partialKeyVisible = pianoAreaHeight % m_keyLineHeight;
// check if we're below the minimum key area size
if (m_pianoKeysVisible * m_keyLineHeight < KEY_AREA_MIN_HEIGHT)
{
m_pianoKeysVisible = KEY_AREA_MIN_HEIGHT / m_keyLineHeight;
partialKeyVisible = KEY_AREA_MIN_HEIGHT % m_keyLineHeight;
// if we have a partial key, just show it
if (partialKeyVisible > 0)
{
m_pianoKeysVisible += 1;
partialKeyVisible = 0;
}
// have to modifiy the notes edit area height instead
m_notesEditHeight = height() - (m_pianoKeysVisible * m_keyLineHeight)
- PR_TOP_MARGIN - PR_BOTTOM_MARGIN;
}
// check if we're trying to show more keys than available
else if (m_pianoKeysVisible >= NumKeys)
{
m_pianoKeysVisible = NumKeys;
// have to modify the notes edit area height instead
m_notesEditHeight = height() - (NumKeys * m_keyLineHeight) -
PR_TOP_MARGIN - PR_BOTTOM_MARGIN;
partialKeyVisible = 0;
}
int topKey = std::clamp(m_startKey + m_pianoKeysVisible - 1, 0, NumKeys - 1);
int topNote = topKey % KeysPerOctave;
// if not resizing the note edit area, we can change m_notesEditHeight
if (m_action != Action::ResizeNoteEditArea && partialKeyVisible != 0)
{
// calculate the height change adding and subtracting the partial key
int noteAreaPlus = (m_notesEditHeight + partialKeyVisible) - m_userSetNotesEditHeight;
int noteAreaMinus = m_userSetNotesEditHeight - (m_notesEditHeight - partialKeyVisible);
// if adding the partial key to height is more distant from the set height
// we want to subtract the partial key
if (noteAreaPlus > noteAreaMinus)
{
m_notesEditHeight -= partialKeyVisible;
// since we're adding a partial key, we add one to the number visible
m_pianoKeysVisible += 1;
}
// otherwise we add height
else { m_notesEditHeight += partialKeyVisible; }
}
int x, q = quantization(), tick;
// draw vertical quantization lines
// If we're over 100% zoom, we allow all quantization level grids
if (m_zoomingModel.value() <= 3)
{
// we're under 100% zoom
// allow quantization grid up to 1/24 for triplets
if (q % 3 != 0 && q < 8) { q = 8; }
// allow quantization grid up to 1/32 for normal notes
else if (q < 6) { q = 6; }
}
auto xCoordOfTick = [=](int tick) {
return m_whiteKeyWidth + (
(tick - m_currentPosition) * m_ppb / TimePos::ticksPerBar()
);
};
p.setPen(m_lineColor);
for (tick = m_currentPosition - m_currentPosition % q,
x = xCoordOfTick(tick);
x <= width();
tick += q, x = xCoordOfTick(tick))
{
p.drawLine(x, keyAreaTop(), x, noteEditBottom());
}
// draw horizontal grid lines and piano notes
p.setClipRect(0, keyAreaTop(), width(), keyAreaBottom() - keyAreaTop());
// the first grid line from the top Y position
int grid_line_y = keyAreaTop() + m_keyLineHeight - 1;
// lambda function for returning the height of a key
auto keyHeight = [&](
const int key
) -> int
{
switch (prKeyOrder[key % KeysPerOctave])
{
case KeyType::WhiteBig:
return m_whiteKeyBigHeight;
case KeyType::WhiteSmall:
return m_whiteKeySmallHeight;
case KeyType::Black:
return m_blackKeyHeight;
}
return 0; // should never happen
};
// lambda function for returning the distance to the top of a key
auto gridCorrection = [&](
const int key
) -> int
{
const int keyCode = key % KeysPerOctave;
switch (prKeyOrder[keyCode])
{
case KeyType::WhiteBig:
return m_whiteKeySmallHeight;
case KeyType::WhiteSmall:
// These two keys need to adjust up small height instead of only key line height
if (static_cast<Key>(keyCode) == Key::C || static_cast<Key>(keyCode) == Key::F)
{
return m_whiteKeySmallHeight;
}
case KeyType::Black:
return m_blackKeyHeight;
}
return 0; // should never happen
};
auto keyWidth = [&](
const int key
) -> int
{
switch (prKeyOrder[key % KeysPerOctave])
{
case KeyType::WhiteSmall:
case KeyType::WhiteBig:
return m_whiteKeyWidth;
case KeyType::Black:
return m_blackKeyWidth;
}
return 0; // should never happen
};
// lambda function to draw a key
auto drawKey = [&](
const int key,
const int yb)
{
const bool mapped = m_midiClip->instrumentTrack()->isKeyMapped(key);
const bool pressed = m_midiClip->instrumentTrack()->pianoModel()->isKeyPressed(key);
const int keyCode = key % KeysPerOctave;
const int yt = yb - gridCorrection(key);
const int kh = keyHeight(key);
const int kw = keyWidth(key);
// set key colors
p.setPen(QColor(0, 0, 0));
switch (prKeyOrder[keyCode])
{
case KeyType::WhiteSmall:
case KeyType::WhiteBig:
if (mapped)
{
if (pressed) { p.setBrush(m_whiteKeyActiveBackground); }
else { p.setBrush(m_whiteKeyInactiveBackground); }
}
else
{
p.setBrush(m_whiteKeyDisabledBackground);
}
break;
case KeyType::Black:
if (mapped)
{
if (pressed) { p.setBrush(m_blackKeyActiveBackground); }
else { p.setBrush(m_blackKeyInactiveBackground); }
}
else
{
p.setBrush(m_blackKeyDisabledBackground);
}
}
// draw key
p.drawRect(PIANO_X, yt, kw, kh);
// draw note name
if (static_cast<Key>(keyCode) == Key::C || (drawNoteNames && Piano::isWhiteKey(key)))
{
// small font sizes have 1 pixel offset instead of 2
auto zoomOffset = m_zoomYLevels[m_zoomingYModel.value()] > 1.0f ? 2 : 1;
QString noteString = getNoteString(key);
QRect textRect(
m_whiteKeyWidth - boundingRect.width() - 2,
yb - m_keyLineHeight + zoomOffset,
boundingRect.width(),
boundingRect.height()
);
p.setPen(pressed ? m_whiteKeyActiveTextShadow : m_whiteKeyInactiveTextShadow);
p.drawText(textRect.adjusted(0, 1, 1, 0), Qt::AlignRight | Qt::AlignHCenter, noteString);
p.setPen(pressed ? m_whiteKeyActiveTextColor : m_whiteKeyInactiveTextColor);
// if (static_cast<Key>(keyCode) == Key::C) { p.setPen(textColor()); }
// else { p.setPen(textColorLight()); }
p.drawText(textRect, Qt::AlignRight | Qt::AlignHCenter, noteString);
}
};
// lambda for drawing the horizontal grid line
auto drawHorizontalLine = [&](
const int key,
const int y
)
{
if (static_cast<Key>(key % KeysPerOctave) == Key::C) { p.setPen(m_beatLineColor); }
else { p.setPen(m_lineColor); }
p.drawLine(m_whiteKeyWidth, y, width(), y);
};
// correct y offset of the top key
switch (prKeyOrder[topNote])
{
case KeyType::WhiteSmall:
case KeyType::WhiteBig:
break;
case KeyType::Black:
// draw extra white key
drawKey(topKey + 1, grid_line_y - m_keyLineHeight);
}
// loop through visible keys
const int lastKey = qMax(0, topKey - m_pianoKeysVisible);
for (int key = topKey; key > lastKey; --key)
{
bool whiteKey = Piano::isWhiteKey(key);
if (whiteKey)
{
drawKey(key, grid_line_y);
drawHorizontalLine(key, grid_line_y);
grid_line_y += m_keyLineHeight;
}
else
{
// draw next white key
drawKey(key - 1, grid_line_y + m_keyLineHeight);
drawHorizontalLine(key - 1, grid_line_y + m_keyLineHeight);
// draw black key over previous and next white key
drawKey(key, grid_line_y);
drawHorizontalLine(key, grid_line_y);
// drew two grid keys so skip ahead properly
grid_line_y += m_keyLineHeight + m_keyLineHeight;
// capture double key draw
--key;
}
}
// don't draw over keys
p.setClipRect(m_whiteKeyWidth, keyAreaTop(), width(), noteEditBottom() - keyAreaTop());
// draw alternating shading on bars
float timeSignature =
static_cast<float>(Engine::getSong()->getTimeSigModel().getNumerator()) /
static_cast<float>(Engine::getSong()->getTimeSigModel().getDenominator());
float zoomFactor = m_zoomLevels[m_zoomingModel.value()];
//the bars which disappears at the left side by scrolling
int leftBars = m_currentPosition * zoomFactor / TimePos::ticksPerBar();
//iterates the visible bars and draw the shading on uneven bars
for (int x = m_whiteKeyWidth, barCount = leftBars;
x < width() + m_currentPosition * zoomFactor / timeSignature;
x += m_ppb, ++barCount)
{
if ((barCount + leftBars) % 2 != 0)
{
p.fillRect(x - m_currentPosition * zoomFactor / timeSignature,
PR_TOP_MARGIN,
m_ppb,
height() - (PR_BOTTOM_MARGIN + PR_TOP_MARGIN),
m_backgroundShade);
}
}
// draw vertical beat lines
int ticksPerBeat = DefaultTicksPerBar /
Engine::getSong()->getTimeSigModel().getDenominator();
p.setPen(m_beatLineColor);
for(tick = m_currentPosition - m_currentPosition % ticksPerBeat,
x = xCoordOfTick( tick );
x <= width();
tick += ticksPerBeat, x = xCoordOfTick(tick))
{
p.drawLine(x, PR_TOP_MARGIN, x, noteEditBottom());
}
// draw vertical bar lines
p.setPen(m_barLineColor);
for(tick = m_currentPosition - m_currentPosition % TimePos::ticksPerBar(),
x = xCoordOfTick( tick );
x <= width();
tick += TimePos::ticksPerBar(), x = xCoordOfTick(tick))
{
p.drawLine(x, PR_TOP_MARGIN, x, noteEditBottom());
}
// draw marked semitones after the grid
for(x = 0; x < m_markedSemiTones.size(); ++x)
{
const int key_num = m_markedSemiTones.at(x);
const int y = keyAreaBottom() - 1 - m_keyLineHeight *
(key_num - m_startKey + 1);
if(y >= keyAreaBottom() - 1) { break; }
p.fillRect(m_whiteKeyWidth + 1,
y,
width() - 10,
m_keyLineHeight + 1,
m_markedSemitoneColor);
}
}
// reset MIDI clip
p.setClipRect(0, 0, width(), height());
// erase the area below the piano, because there might be keys that
// should be only half-visible
p.fillRect( QRect( 0, keyAreaBottom(),
m_whiteKeyWidth, noteEditBottom() - keyAreaBottom()), bgColor);
// display note editing info
f.setBold(false);
p.setFont(adjustedToPixelSize(f, SMALL_FONT_SIZE));
p.setPen(m_noteModeColor);
p.drawText( QRect( 0, keyAreaBottom(),
m_whiteKeyWidth, noteEditBottom() - keyAreaBottom()),
Qt::AlignCenter | Qt::TextWordWrap,
m_nemStr.at(static_cast<int>(m_noteEditMode)) + ":" );
// set clipping area, because we are not allowed to paint over
// keyboard...
p.setClipRect(
m_whiteKeyWidth,
PR_TOP_MARGIN,
width() - m_whiteKeyWidth,
height() - PR_TOP_MARGIN - PR_BOTTOM_MARGIN);
// following code draws all notes in visible area
// and the note editing stuff (volume, panning, etc)
// setup selection-vars
int sel_pos_start = m_selectStartTick;
int sel_pos_end = m_selectStartTick+m_selectedTick;
if( sel_pos_start > sel_pos_end )
{
qSwap<int>( sel_pos_start, sel_pos_end );
}
int sel_key_start = m_selectStartKey - m_startKey + 1;
int sel_key_end = sel_key_start + m_selectedKeys;
if( sel_key_start > sel_key_end )
{
qSwap<int>( sel_key_start, sel_key_end );
}
int y_base = keyAreaBottom() - 1;
if( hasValidMidiClip() )
{
p.setClipRect(
m_whiteKeyWidth,
PR_TOP_MARGIN,
width() - m_whiteKeyWidth,
height() - PR_TOP_MARGIN);
const int topKey = qBound(0, m_startKey + m_pianoKeysVisible - 1, NumKeys - 1);
const int bottomKey = topKey - m_pianoKeysVisible;
QPolygonF editHandles;
// Return a note's Y position on the grid
auto noteYPos = [&](const int key)
{
return (topKey - key) * m_keyLineHeight + keyAreaTop() - 1;
};
// -- Begin ghost MIDI clip
if( !m_ghostNotes.empty() )
{
for( const Note *note : m_ghostNotes )
{
int len_ticks = note->length();
if( len_ticks == 0 )
{
continue;
}
else if( len_ticks < 0 )
{
len_ticks = 4;
}
int pos_ticks = note->pos();
int note_width = len_ticks * m_ppb / TimePos::ticksPerBar();
const int x = ( pos_ticks - m_currentPosition ) *
m_ppb / TimePos::ticksPerBar();
// skip this note if not in visible area at all
if (!(x + note_width >= 0 && x <= width() - m_whiteKeyWidth))
{
continue;
}
// is the note in visible area?
if (note->key() > bottomKey && note->key() <= topKey)
{
// we've done and checked all, let's draw the note
drawNoteRect(
p, x + m_whiteKeyWidth, noteYPos(note->key()), note_width,
note, m_ghostNoteColor, m_ghostNoteTextColor, m_selectedNoteColor,
m_ghostNoteOpacity, m_ghostNoteBorders, drawNoteNames);
}
}
}
// -- End ghost MIDI clip
for( const Note *note : m_midiClip->notes() )
{
int len_ticks = note->length();
if( len_ticks == 0 )
{
continue;
}
else if( len_ticks < 0 )
{
len_ticks = 4;
}
int pos_ticks = note->pos();
int note_width = len_ticks * m_ppb / TimePos::ticksPerBar();
const int x = ( pos_ticks - m_currentPosition ) *
m_ppb / TimePos::ticksPerBar();
// skip this note if not in visible area at all
if (!(x + note_width >= 0 && x <= width() - m_whiteKeyWidth))
{
continue;
}
// is the note in visible area?
if (note->key() > bottomKey && note->key() <= topKey)
{
// We've done and checked all, let's draw the note with
// the appropriate color
const auto fillColor = note->type() == Note::Type::Regular ? m_noteColor : m_stepNoteColor;
drawNoteRect(
p, x + m_whiteKeyWidth, noteYPos(note->key()), note_width,
note, fillColor, m_noteTextColor, m_selectedNoteColor,
m_noteOpacity, m_noteBorders, drawNoteNames
);
}
// draw note editing stuff
int editHandleTop = 0;
if( m_noteEditMode == NoteEditMode::Volume )
{
QColor color = m_barColor.lighter(30 + (note->getVolume() * 90 / MaxVolume));
if( note->selected() )
{
color = m_selectedNoteColor;
}
p.setPen( QPen( color, NOTE_EDIT_LINE_WIDTH ) );
editHandleTop = noteEditBottom() -
( (float)( note->getVolume() - MinVolume ) ) /
( (float)( MaxVolume - MinVolume ) ) *
( (float)( noteEditBottom() - noteEditTop() ) );
p.drawLine( QLineF ( noteEditLeft() + x + 0.5, editHandleTop + 0.5,
noteEditLeft() + x + 0.5, noteEditBottom() + 0.5 ) );
}
else if( m_noteEditMode == NoteEditMode::Panning )
{
QColor color = m_noteColor;
if( note->selected() )
{
color = m_selectedNoteColor;
}
p.setPen( QPen( color, NOTE_EDIT_LINE_WIDTH ) );
editHandleTop = noteEditBottom() -
( (float)( note->getPanning() - PanningLeft ) ) /
( (float)( (PanningRight - PanningLeft ) ) ) *
( (float)( noteEditBottom() - noteEditTop() ) );
p.drawLine( QLine( noteEditLeft() + x, noteEditTop() +
( (float)( noteEditBottom() - noteEditTop() ) ) / 2.0f,
noteEditLeft() + x , editHandleTop ) );
}
editHandles << QPoint ( x + noteEditLeft(),
editHandleTop );
if( note->hasDetuningInfo() )
{
drawDetuningInfo(p, note, x + m_whiteKeyWidth, noteYPos(note->key()));
p.setClipRect(
m_whiteKeyWidth,
PR_TOP_MARGIN,
width() - m_whiteKeyWidth,
height() - PR_TOP_MARGIN);
}
}
// -- Knife tool (draw cut line)
if (m_action == Action::Knife)
{
auto xCoordOfTick = [this](int tick) {
return m_whiteKeyWidth + (
(tick - m_currentPosition) * m_ppb / TimePos::ticksPerBar());
};
Note* n = noteUnderMouse();
if (n)
{
const int key = n->key() - m_startKey + 1;
int y = y_base - key * m_keyLineHeight;
int x = xCoordOfTick(m_knifeTickPos);
if (x > xCoordOfTick(n->pos()) &&
x < xCoordOfTick(n->pos() + n->length()))
{
p.setPen(QPen(m_knifeCutLineColor, 1));
p.drawLine(x, y, x, y + m_keyLineHeight);
setCursor(Qt::BlankCursor);
}
else
{
setCursor(Qt::ArrowCursor);
}
}
else
{
setCursor(Qt::ArrowCursor);
}
}
// -- End knife tool
//draw current step recording notes
for( const Note *note : m_stepRecorder.getCurStepNotes() )
{
int len_ticks = note->length();
if( len_ticks == 0 )
{
continue;
}
int pos_ticks = note->pos();
int note_width = len_ticks * m_ppb / TimePos::ticksPerBar();
const int x = ( pos_ticks - m_currentPosition ) *
m_ppb / TimePos::ticksPerBar();
// skip this note if not in visible area at all
if (!(x + note_width >= 0 && x <= width() - m_whiteKeyWidth))
{
continue;
}
// is the note in visible area?
if (note->key() > bottomKey && note->key() <= topKey)
{
// we've done and checked all, let's draw the note
drawNoteRect(
p, x + m_whiteKeyWidth, noteYPos(note->key()), note_width,
note, m_stepRecorder.curStepNoteColor(), m_noteTextColor, m_selectedNoteColor,
m_noteOpacity, m_noteBorders, drawNoteNames);
}
}
p.setPen(QPen(m_noteColor, NOTE_EDIT_LINE_WIDTH + 2));
p.drawPoints( editHandles );
}
else
{
QFont f = font();
f.setBold(true);
p.setFont(f);
p.setPen( QApplication::palette().color( QPalette::Active,
QPalette::BrightText ) );
p.drawText(m_whiteKeyWidth + 20, PR_TOP_MARGIN + 40,
tr( "Please open a clip by double-clicking "
"on it!" ) );
}
p.setClipRect(
m_whiteKeyWidth,
PR_TOP_MARGIN,
width() - m_whiteKeyWidth,
height() - PR_TOP_MARGIN - m_notesEditHeight - PR_BOTTOM_MARGIN);
// now draw selection-frame
int x = ( ( sel_pos_start - m_currentPosition ) * m_ppb ) /
TimePos::ticksPerBar();
int w = ( ( ( sel_pos_end - m_currentPosition ) * m_ppb ) /
TimePos::ticksPerBar() ) - x;
int y = (int) y_base - sel_key_start * m_keyLineHeight;
int h = (int) y_base - sel_key_end * m_keyLineHeight - y;
p.setPen(m_selectedNoteColor);
p.setBrush( Qt::NoBrush );
p.drawRect(x + m_whiteKeyWidth, y, w, h);
// TODO: Get this out of paint event
int l = ( hasValidMidiClip() )? (int) m_midiClip->length() : 0;
// reset scroll-range
if( m_leftRightScroll->maximum() != l )
{
m_leftRightScroll->setRange( 0, l );
m_leftRightScroll->setPageStep( l );
}
// set line colors
auto editAreaCol = QColor(m_lineColor);
auto currentKeyCol = QColor(m_beatLineColor);
editAreaCol.setAlpha( 64 );
currentKeyCol.setAlpha( 64 );
// horizontal line for the key under the cursor
if(hasValidMidiClip() && getGUI()->pianoRoll()->hasFocus())
{
int key_num = getKey( mapFromGlobal( QCursor::pos() ).y() );
p.fillRect( 10, keyAreaBottom() + 3 - m_keyLineHeight *
( key_num - m_startKey + 1 ), width() - 10, m_keyLineHeight - 7, currentKeyCol );
}
// bar to resize note edit area
p.setClipRect( 0, 0, width(), height() );
p.fillRect( QRect( 0, keyAreaBottom(),
width()-PR_RIGHT_MARGIN, NOTE_EDIT_RESIZE_BAR ), editAreaCol );
if (getGUI()->pianoRoll()->hasFocus())
{
const QPixmap * cursor = nullptr;
// draw current edit-mode-icon below the cursor
switch( m_editMode )
{
case EditMode::Draw:
if( m_mouseDownRight )
{
cursor = &m_toolErase;
}
else if( m_action == Action::MoveNote )
{
cursor = &m_toolMove;
}
else
{
cursor = &m_toolDraw;
}
break;
case EditMode::Erase:
cursor = &m_toolErase;
break;
case EditMode::Select:
cursor = &m_toolSelect;
break;
case EditMode::Detuning:
cursor = &m_toolOpen;
break;
case EditMode::Knife:
cursor = &m_toolKnife;
break;
}
QPoint mousePosition = mapFromGlobal( QCursor::pos() );
if( cursor != nullptr && mousePosition.y() > keyAreaTop() && mousePosition.x() > noteEditLeft())
{
p.drawPixmap( mousePosition + QPoint( 8, 8 ), *cursor );
}
}
}
void PianoRoll::updateScrollbars()
{
m_leftRightScroll->setGeometry(
m_whiteKeyWidth,
height() - SCROLLBAR_SIZE,
width() - m_whiteKeyWidth,
SCROLLBAR_SIZE
);
m_topBottomScroll->setGeometry(
width() - SCROLLBAR_SIZE,
PR_TOP_MARGIN,
SCROLLBAR_SIZE,
height() - PR_TOP_MARGIN - SCROLLBAR_SIZE
);
int pianoAreaHeight = keyAreaBottom() - PR_TOP_MARGIN;
int numKeysVisible = pianoAreaHeight / m_keyLineHeight;
m_totalKeysToScroll = qMax(0, NumKeys - numKeysVisible);
m_topBottomScroll->setRange(0, m_totalKeysToScroll);
if (m_startKey > m_totalKeysToScroll)
{
m_startKey = qMax(0, m_totalKeysToScroll);
}
m_topBottomScroll->setValue(m_totalKeysToScroll - m_startKey);
}
// responsible for moving/resizing scrollbars after window-resizing
void PianoRoll::resizeEvent(QResizeEvent* re)
{
updatePositionLineHeight();
updateScrollbars();
m_timeLine->setFixedWidth(width());
update();
}
void PianoRoll::adjustLeftRightScoll(int value)
{
m_leftRightScroll->setValue(m_leftRightScroll->value() -
value * 0.3f / m_zoomLevels[m_zoomingModel.value()]);
}
void PianoRoll::wheelEvent(QWheelEvent * we )
{
we->accept();
// handle wheel events for note edit area - for editing note vol/pan with mousewheel
if(position(we).x() > noteEditLeft() && position(we).x() < noteEditRight()
&& position(we).y() > noteEditTop() && position(we).y() < noteEditBottom())
{
if (!hasValidMidiClip()) {return;}
// get values for going through notes
int pixel_range = 8;
int x = position(we).x() - m_whiteKeyWidth;
int ticks_start = ( x - pixel_range / 2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
int ticks_end = ( x + pixel_range / 2 ) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
// When alt is pressed we only edit the note under the cursor
bool altPressed = we->modifiers() & Qt::AltModifier;
// go through notes to figure out which one we want to change
NoteVector nv;
for ( Note * i : m_midiClip->notes() )
{
if( i->withinRange( ticks_start, ticks_end ) || ( i->selected() && !altPressed ) )
{
nv.push_back(i);
}
}
if( nv.size() > 0 )
{
const int step = (we->angleDelta().y() > 0 ? 1 : -1) * (we->inverted() ? -1 : 1);
if( m_noteEditMode == NoteEditMode::Volume )
{
for ( Note * n : nv )
{
volume_t vol = qBound<int>( MinVolume, n->getVolume() + step, MaxVolume );
n->setVolume( vol );
}
bool allVolumesEqual = std::all_of( nv.begin(), nv.end(),
[nv](const Note *note)
{
return note->getVolume() == nv[0]->getVolume();
});
if ( allVolumesEqual )
{
// show the volume hover-text only if all notes have the
// same volume
showVolTextFloat(nv[0]->getVolume(), position(we), 1000);
}
}
else if( m_noteEditMode == NoteEditMode::Panning )
{
for ( Note * n : nv )
{
panning_t pan = qBound<int>( PanningLeft, n->getPanning() + step, PanningRight );
n->setPanning( pan );
}
bool allPansEqual = std::all_of( nv.begin(), nv.end(),
[nv](const Note *note)
{
return note->getPanning() == nv[0]->getPanning();
});
if ( allPansEqual )
{
// show the pan hover-text only if all notes have the same
// panning
showPanTextFloat( nv[0]->getPanning(), position( we ), 1000 );
}
}
update();
}
}
// not in note edit area, so handle scrolling/zooming and quantization change
else
if( we->modifiers() & Qt::ControlModifier && we->modifiers() & Qt::AltModifier )
{
int q = m_quantizeModel.value();
if((we->angleDelta().x() + we->angleDelta().y()) > 0) // alt + scroll becomes horizontal scroll on KDE
{
q--;
}
else if((we->angleDelta().x() + we->angleDelta().y()) < 0) // alt + scroll becomes horizontal scroll on KDE
{
q++;
}
q = qBound( 0, q, m_quantizeModel.size() - 1 );
m_quantizeModel.setValue( q );
}
else if( we->modifiers() & Qt::ControlModifier && we->modifiers() & Qt::ShiftModifier )
{
int l = m_noteLenModel.value();
if(we->angleDelta().y() > 0)
{
l--;
}
else if(we->angleDelta().y() < 0)
{
l++;
}
l = qBound( 0, l, m_noteLenModel.size() - 1 );
m_noteLenModel.setValue( l );
}
else if( we->modifiers() & Qt::ControlModifier )
{
int z = m_zoomingModel.value();
if(we->angleDelta().y() > 0)
{
z++;
}
else if(we->angleDelta().y() < 0)
{
z--;
}
z = qBound( 0, z, m_zoomingModel.size() - 1 );
int x = (position(we).x() - m_whiteKeyWidth) * TimePos::ticksPerBar();
// ticks based on the mouse x-position where the scroll wheel was used
int ticks = x / m_ppb;
// what would be the ticks in the new zoom level on the very same mouse x
int newTicks = x / (DEFAULT_PR_PPB * m_zoomLevels[z]);
// scroll so the tick "selected" by the mouse x doesn't move on the screen
m_leftRightScroll->setValue(m_leftRightScroll->value() + ticks - newTicks);
// update combobox with zooming-factor
m_zoomingModel.setValue( z );
}
// FIXME: Reconsider if determining orientation is necessary in Qt6.
else if(abs(we->angleDelta().x()) > abs(we->angleDelta().y())) // scrolling is horizontal
{
adjustLeftRightScoll(we->angleDelta().x());
}
else if(we->modifiers() & Qt::ShiftModifier)
{
adjustLeftRightScoll(we->angleDelta().y());
}
else
{
m_topBottomScroll->setValue(m_topBottomScroll->value() -
we->angleDelta().y() / 30);
}
}
void PianoRoll::focusOutEvent( QFocusEvent * )
{
if( hasValidMidiClip() )
{
for( int i = 0; i < NumKeys; ++i )
{
m_midiClip->instrumentTrack()->pianoModel()->midiEventProcessor()->processInEvent( MidiEvent( MidiNoteOff, -1, i, 0 ) );
m_midiClip->instrumentTrack()->pianoModel()->setKeyState( i, false );
}
}
if (m_editMode == EditMode::Knife) {
m_editMode = m_knifeMode;
m_action = Action::None;
} else {
m_editMode = m_ctrlMode;
}
update();
}
void PianoRoll::focusInEvent( QFocusEvent * ev )
{
if ( hasValidMidiClip() )
{
// Assign midi device
m_midiClip->instrumentTrack()->autoAssignMidiDevice(true);
}
QWidget::focusInEvent(ev);
}
int PianoRoll::getKey(int y) const
{
// handle case that very top pixel maps to next key above
if (y - keyAreaTop() <= 1) { y = keyAreaTop() + 2; }
int key_num = qBound(
0,
// add + 1 to stay within the grid lines
((keyAreaBottom() - y + 1) / m_keyLineHeight) + m_startKey,
NumKeys - 1
);
return key_num;
}
QList<int> PianoRoll::getAllOctavesForKey( int keyToMirror ) const
{
QList<int> keys;
int trackKeysPerOctave = trackOctaveSize();
for (int i = keyToMirror % trackKeysPerOctave; i < NumKeys; i += trackKeysPerOctave)
{
keys.append(i);
}
return keys;
}
Song::PlayMode PianoRoll::desiredPlayModeForAccompany() const
{
if (m_midiClip->getTrack()->trackContainer() == Engine::patternStore())
{
return Song::PlayMode::Pattern;
}
return Song::PlayMode::Song;
}
void PianoRoll::play()
{
if( ! hasValidMidiClip() )
{
return;
}
if( Engine::getSong()->playMode() != Song::PlayMode::MidiClip )
{
Engine::getSong()->playMidiClip( m_midiClip );
}
else
{
Engine::getSong()->togglePause();
}
}
void PianoRoll::record()
{
if( Engine::getSong()->isPlaying() )
{
stop();
}
if( m_recording || ! hasValidMidiClip() )
{
return;
}
m_midiClip->addJournalCheckPoint();
m_recording = true;
Engine::getSong()->playMidiClip( m_midiClip, false );
}
void PianoRoll::recordAccompany()
{
if( Engine::getSong()->isPlaying() )
{
stop();
}
if( m_recording || ! hasValidMidiClip() )
{
return;
}
m_midiClip->addJournalCheckPoint();
m_recording = true;
if( m_midiClip->getTrack()->trackContainer() == Engine::getSong() )
{
Engine::getSong()->playSong();
}
else
{
Engine::getSong()->playPattern();
}
}
bool PianoRoll::toggleStepRecording()
{
if(m_stepRecorder.isRecording())
{
m_stepRecorder.stop();
}
else
{
if(hasValidMidiClip())
{
if(Engine::getSong()->isPlaying())
{
m_stepRecorder.start(0, newNoteLen());
}
else
{
m_stepRecorder.start(
Engine::getSong()->getPlayPos(
Song::PlayMode::MidiClip), newNoteLen());
}
}
}
return m_stepRecorder.isRecording();;
}
void PianoRoll::stop()
{
Engine::getSong()->stop();
m_recording = false;
m_scrollBack = m_timeLine->autoScroll() != TimeLineWidget::AutoScrollState::Disabled;
}
void PianoRoll::startRecordNote(const Note & n )
{
if(hasValidMidiClip())
{
if( m_recording &&
Engine::getSong()->isPlaying() &&
(Engine::getSong()->playMode() == desiredPlayModeForAccompany() ||
Engine::getSong()->playMode() == Song::PlayMode::MidiClip ))
{
TimePos sub;
if( Engine::getSong()->playMode() == Song::PlayMode::Song )
{
sub = m_midiClip->startPosition();
}
Note n1( 1, Engine::getSong()->getPlayPos(
Engine::getSong()->playMode() ) - sub,
n.key(), n.getVolume(), n.getPanning() );
if( n1.pos() >= 0 )
{
m_recordingNotes << n1;
}
}
else if (m_stepRecorder.isRecording())
{
m_stepRecorder.notePressed(n);
}
}
}
void PianoRoll::finishRecordNote(const Note & n )
{
if(hasValidMidiClip())
{
if( m_recording &&
Engine::getSong()->isPlaying() &&
( Engine::getSong()->playMode() ==
desiredPlayModeForAccompany() ||
Engine::getSong()->playMode() ==
Song::PlayMode::MidiClip ) )
{
for( QList<Note>::Iterator it = m_recordingNotes.begin();
it != m_recordingNotes.end(); ++it )
{
if( it->key() == n.key() )
{
Note n1(n.length(), it->pos(),
it->key(), it->getVolume(),
it->getPanning(), n.detuning());
if (m_doAutoQuantization)
{
n1.quantizeLength(quantization());
n1.quantizePos(quantization());
}
m_midiClip->addNote(n1, false);
update();
m_recordingNotes.erase( it );
break;
}
}
}
else if (m_stepRecorder.isRecording())
{
m_stepRecorder.noteReleased(n);
}
}
}
void PianoRoll::horScrolled(int new_pos )
{
m_currentPosition = new_pos;
m_stepRecorderWidget.setCurrentPosition(m_currentPosition);
emit positionChanged( m_currentPosition );
update();
}
void PianoRoll::verScrolled( int new_pos )
{
// revert value
m_startKey = qMax(0, m_totalKeysToScroll - new_pos);
update();
}
void PianoRoll::setEditMode(int mode)
{
m_ctrlMode = m_editMode = (EditMode) mode;
}
void PianoRoll::selectAll()
{
if( ! hasValidMidiClip() )
{
return;
}
// if first_time = true, we HAVE to set the vars for select
bool first_time = true;
for( const Note *note : m_midiClip->notes() )
{
int len_ticks = static_cast<int>( note->length() ) > 0 ?
static_cast<int>( note->length() ) : 1;
const int key = note->key();
int pos_ticks = note->pos();
if( key <= m_selectStartKey || first_time )
{
// if we move start-key down, we have to add
// the difference between old and new start-key
// to m_selectedKeys, otherwise the selection
// is just moved down...
m_selectedKeys += m_selectStartKey
- ( key - 1 );
m_selectStartKey = key - 1;
}
if( key >= m_selectedKeys + m_selectStartKey ||
first_time )
{
m_selectedKeys = key - m_selectStartKey;
}
if( pos_ticks < m_selectStartTick ||
first_time )
{
m_selectStartTick = pos_ticks;
}
if( pos_ticks + len_ticks >
m_selectStartTick + m_selectedTick ||
first_time )
{
m_selectedTick = pos_ticks +
len_ticks -
m_selectStartTick;
}
first_time = false;
}
}
// returns vector with pointers to all selected notes
NoteVector PianoRoll::getSelectedNotes() const
{
NoteVector selectedNotes;
if (hasValidMidiClip())
{
for( Note *note : m_midiClip->notes() )
{
if( note->selected() )
{
selectedNotes.push_back( note );
}
}
}
return selectedNotes;
}
// selects all notess associated with m_lastKey
void PianoRoll::selectNotesOnKey()
{
if (hasValidMidiClip()) {
for (Note * note : m_midiClip->notes()) {
if (note->key() == m_lastKey) {
note->setSelected(true);
}
}
}
}
void PianoRoll::enterValue( NoteVector* nv )
{
if( m_noteEditMode == NoteEditMode::Volume )
{
bool ok;
int new_val;
new_val = QInputDialog::getInt( this, "Piano roll: note velocity",
tr( "Please enter a new value between %1 and %2:" ).
arg( MinVolume ).arg( MaxVolume ),
(*nv)[0]->getVolume(),
MinVolume, MaxVolume, 1, &ok );
if( ok )
{
for ( Note * n : *nv )
{
n->setVolume( new_val );
}
m_lastNoteVolume = new_val;
}
}
else if( m_noteEditMode == NoteEditMode::Panning )
{
bool ok;
int new_val;
new_val = QInputDialog::getInt( this, "Piano roll: note panning",
tr( "Please enter a new value between %1 and %2:" ).
arg( PanningLeft ).arg( PanningRight ),
(*nv)[0]->getPanning(),
PanningLeft, PanningRight, 1, &ok );
if( ok )
{
for ( Note * n : *nv )
{
n->setPanning( new_val );
}
m_lastNotePanning = new_val;
}
}
}
void PianoRoll::updateYScroll()
{
m_topBottomScroll->setGeometry(width() - SCROLLBAR_SIZE, PR_TOP_MARGIN,
SCROLLBAR_SIZE,
height() - PR_TOP_MARGIN -
SCROLLBAR_SIZE);
const int visible_space = keyAreaBottom() - keyAreaTop();
m_totalKeysToScroll = qMax(0, NumKeys - 1 - visible_space / m_keyLineHeight);
m_topBottomScroll->setRange(0, m_totalKeysToScroll);
if(m_startKey > m_totalKeysToScroll)
{
m_startKey = m_totalKeysToScroll;
}
m_topBottomScroll->setValue(m_totalKeysToScroll - m_startKey);
}
void PianoRoll::copyToClipboard( const NoteVector & notes ) const
{
// For copyString() and MimeType enum class
using namespace Clipboard;
DataFile dataFile( DataFile::Type::ClipboardData );
QDomElement note_list = dataFile.createElement( "note-list" );
dataFile.content().appendChild( note_list );
TimePos start_pos( notes.front()->pos().getBar(), 0 );
for( const Note *note : notes )
{
Note clip_note( *note );
clip_note.setPos( clip_note.pos( start_pos ) );
clip_note.saveState( dataFile, note_list );
}
copyString( dataFile.toString(), MimeType::Default );
}
void PianoRoll::copySelectedNotes()
{
NoteVector selected_notes = getSelectedNotes();
if( ! selected_notes.empty() )
{
copyToClipboard( selected_notes );
}
}
void PianoRoll::cutSelectedNotes()
{
if( ! hasValidMidiClip() )
{
return;
}
NoteVector selected_notes = getSelectedNotes();
if( ! selected_notes.empty() )
{
m_midiClip->addJournalCheckPoint();
copyToClipboard( selected_notes );
Engine::getSong()->setModified();
for( Note *note : selected_notes )
{
// note (the memory of it) is also deleted by
// MidiClip::removeNote(...) so we don't have to do that
m_midiClip->removeNote( note );
}
}
update();
getGUI()->songEditor()->update();
}
void PianoRoll::pasteNotes()
{
// For getString() and MimeType enum class
using namespace Clipboard;
if( ! hasValidMidiClip() )
{
return;
}
QString value = getString( MimeType::Default );
if( ! value.isEmpty() )
{
DataFile dataFile( value.toUtf8() );
QDomNodeList list = dataFile.elementsByTagName( Note::classNodeName() );
// remove selection and select the newly pasted notes
clearSelectedNotes();
if( ! list.isEmpty() )
{
m_midiClip->addJournalCheckPoint();
}
for( int i = 0; ! list.item( i ).isNull(); ++i )
{
// create the note
Note cur_note;
cur_note.restoreState( list.item( i ).toElement() );
cur_note.setPos( cur_note.pos() + Note::quantized( m_timeLine->pos(), quantization() ) );
// select it
cur_note.setSelected( true );
// add to MIDI clip
m_midiClip->addNote( cur_note, false );
}
// we only have to do the following lines if we pasted at
// least one note...
Engine::getSong()->setModified();
update();
getGUI()->songEditor()->update();
}
}
//Return false if no notes are deleted
bool PianoRoll::deleteSelectedNotes()
{
if (!hasValidMidiClip()) { return false; }
auto selectedNotes = getSelectedNotes();
if (selectedNotes.empty()) { return false; }
m_midiClip->addJournalCheckPoint();
for (Note* note: selectedNotes) { m_midiClip->removeNote( note ); }
Engine::getSong()->setModified();
update();
getGUI()->songEditor()->update();
return true;
}
void PianoRoll::autoScroll( const TimePos & t )
{
const int w = width() - m_whiteKeyWidth;
if (m_timeLine->autoScroll() == TimeLineWidget::AutoScrollState::Stepped)
{
if (t > m_currentPosition + w * TimePos::ticksPerBar() / m_ppb)
{
m_leftRightScroll->setValue(t.getBar() * TimePos::ticksPerBar());
}
else if (t < m_currentPosition)
{
TimePos t2 = std::max(t - w * TimePos::ticksPerBar() *
TimePos::ticksPerBar() / m_ppb, static_cast<tick_t>(0));
m_leftRightScroll->setValue(t2.getBar() * TimePos::ticksPerBar());
}
}
else if (m_timeLine->autoScroll() == TimeLineWidget::AutoScrollState::Continuous)
{
m_leftRightScroll->setValue(std::max(t.getTicks() - w * TimePos::ticksPerBar() / m_ppb / 2, 0));
}
m_scrollBack = false;
}
void PianoRoll::updatePosition(const TimePos & t)
{
if ((Engine::getSong()->isPlaying()
&& Engine::getSong()->playMode() == Song::PlayMode::MidiClip
&& m_timeLine->autoScroll() != TimeLineWidget::AutoScrollState::Disabled
) || m_scrollBack)
{
autoScroll(t);
}
// ticks relative to m_currentPosition
// < 0 = outside viewport left
// > width = outside viewport right
const int pos = (static_cast<int>(m_timeLine->pos()) - m_currentPosition) * m_ppb / TimePos::ticksPerBar();
// if pos is within visible range, show it
if (pos >= 0 && pos <= width() - m_whiteKeyWidth)
{
m_positionLine->show();
// adjust pos for piano keys width and self line width (align to rightmost of line)
m_positionLine->move(pos + m_whiteKeyWidth - (m_positionLine->width() - 1), keyAreaTop());
}
else
{
m_positionLine->hide();
}
}
void PianoRoll::updatePositionLineHeight()
{
m_positionLine->setFixedHeight(keyAreaBottom() - keyAreaTop());
}
void PianoRoll::updatePositionAccompany( const TimePos & t )
{
Song * s = Engine::getSong();
if( m_recording && hasValidMidiClip() &&
s->playMode() != Song::PlayMode::MidiClip )
{
TimePos pos = t;
if (s->playMode() != Song::PlayMode::Pattern)
{
pos -= m_midiClip->startPosition();
}
if( (int) pos > 0 )
{
s->getPlayPos( Song::PlayMode::MidiClip ).setTicks( pos );
autoScroll( pos );
}
}
}
void PianoRoll::updatePositionStepRecording( const TimePos & t )
{
if( m_stepRecorder.isRecording() )
{
autoScroll( t );
}
}
void PianoRoll::zoomingChanged()
{
m_ppb = m_zoomLevels[m_zoomingModel.value()] * DEFAULT_PR_PPB;
assert( m_ppb > 0 );
m_timeLine->setPixelsPerBar( m_ppb );
m_stepRecorderWidget.setPixelsPerBar( m_ppb );
m_positionLine->zoomChange(m_zoomLevels[m_zoomingModel.value()]);
update();
}
void PianoRoll::zoomingYChanged()
{
m_keyLineHeight = m_zoomYLevels[m_zoomingYModel.value()] * DEFAULT_KEY_LINE_HEIGHT;
m_whiteKeySmallHeight = qFloor(m_keyLineHeight * 1.5);
m_whiteKeyBigHeight = m_keyLineHeight * 2;
m_blackKeyHeight = m_keyLineHeight; //round(m_keyLineHeight * 1.3333);
updateYScroll();
update();
}
void PianoRoll::quantizeChanged()
{
update();
}
void PianoRoll::noteLengthChanged()
{
m_stepRecorder.setStepsLength(newNoteLen());
update();
}
void PianoRoll::keyChanged()
{
markSemiTone(SemiToneMarkerAction::MarkCurrentScale, false);
}
int PianoRoll::quantization() const
{
if( m_quantizeModel.value() == 0 )
{
if( m_noteLenModel.value() > 0 )
{
return newNoteLen();
}
else
{
return DefaultTicksPerBar / 16;
}
}
return DefaultTicksPerBar / Quantizations[m_quantizeModel.value() - 1];
}
void PianoRoll::quantizeNotes(QuantizeAction mode)
{
if( ! hasValidMidiClip() )
{
return;
}
m_midiClip->addJournalCheckPoint();
NoteVector notes = getSelectedNotes();
if( notes.empty() )
{
for( Note* n : m_midiClip->notes() )
{
notes.push_back( n );
}
}
for( Note* n : notes )
{
if( n->length() == TimePos( 0 ) )
{
continue;
}
Note copy(*n);
m_midiClip->removeNote( n );
if (mode == QuantizeAction::Both || mode == QuantizeAction::Pos)
{
copy.quantizePos(quantization());
}
if (mode == QuantizeAction::Both || mode == QuantizeAction::Length)
{
copy.quantizeLength(quantization());
}
m_midiClip->addNote(copy, false);
}
update();
getGUI()->songEditor()->update();
Engine::getSong()->setModified();
}
void PianoRoll::updateSemiToneMarkerMenu()
{
const InstrumentFunctionNoteStacking::ChordTable& chord_table =
InstrumentFunctionNoteStacking::ChordTable::getInstance();
const InstrumentFunctionNoteStacking::Chord& scale =
chord_table.getScaleByName( m_scaleModel.currentText() );
const InstrumentFunctionNoteStacking::Chord& chord =
chord_table.getChordByName( m_chordModel.currentText() );
emit semiToneMarkerMenuScaleSetEnabled( ! scale.isEmpty() );
emit semiToneMarkerMenuChordSetEnabled( ! chord.isEmpty() );
}
TimePos PianoRoll::newNoteLen() const
{
if( m_noteLenModel.value() == 0 )
{
return m_lenOfNewNotes;
}
QString text = m_noteLenModel.currentText();
return DefaultTicksPerBar / text.right( text.length() - 2 ).toInt();
}
bool PianoRoll::mouseOverNote()
{
return hasValidMidiClip() && noteUnderMouse() != nullptr;
}
Note * PianoRoll::noteUnderMouse()
{
QPoint pos = mapFromGlobal( QCursor::pos() );
if (pos.x() <= m_whiteKeyWidth
|| pos.x() > width() - SCROLLBAR_SIZE
|| pos.y() < PR_TOP_MARGIN
|| pos.y() > keyAreaBottom() )
{
return nullptr;
}
int key_num = getKey( pos.y() );
int pos_ticks = (pos.x() - m_whiteKeyWidth) *
TimePos::ticksPerBar() / m_ppb + m_currentPosition;
// loop through whole note-vector...
for( Note* const& note : m_midiClip->notes() )
{
// and check whether the cursor is over an
// existing note
if( pos_ticks >= note->pos()
&& pos_ticks <= note->endPos()
&& note->key() == key_num
&& note->length() > 0 )
{
return note;
}
}
return nullptr;
}
void PianoRoll::changeSnapMode()
{
// GridMode::Nudge,
// GridMode::Snap,
// GridMode::Free - to be implemented
m_gridMode = static_cast<GridMode>(m_snapModel.value());
}
PianoRollWindow::PianoRollWindow() :
Editor(true, true),
m_editor(new PianoRoll())
{
setCentralWidget( m_editor );
m_playAction->setToolTip(tr( "Play/pause current clip (Space)" ) );
m_recordAction->setToolTip(tr( "Record notes from MIDI-device/channel-piano" ) );
m_recordAccompanyAction->setToolTip( tr( "Record notes from MIDI-device/channel-piano while playing song or pattern track" ) );
m_toggleStepRecordingAction->setToolTip( tr( "Record notes from MIDI-device/channel-piano, one step at the time" ) );
m_stopAction->setToolTip( tr( "Stop playing of current clip (Space)" ) );
DropToolBar *notesActionsToolBar = addDropToolBarToTop( tr( "Edit actions" ) );
// init edit-buttons at the top
auto editModeGroup = new ActionGroup(this);
QAction* drawAction = editModeGroup->addAction( embed::getIconPixmap( "edit_draw" ), tr( "Draw mode (Shift+D)" ) );
QAction* eraseAction = editModeGroup->addAction( embed::getIconPixmap( "edit_erase" ), tr("Erase mode (Shift+E)" ) );
QAction* selectAction = editModeGroup->addAction( embed::getIconPixmap( "edit_select" ), tr( "Select mode (Shift+S)" ) );
QAction* pitchBendAction = editModeGroup->addAction( embed::getIconPixmap( "automation" ), tr("Pitch Bend mode (Shift+T)" ) );
drawAction->setChecked( true );
drawAction->setShortcut( Qt::SHIFT | Qt::Key_D );
eraseAction->setShortcut( Qt::SHIFT | Qt::Key_E );
selectAction->setShortcut( Qt::SHIFT | Qt::Key_S );
pitchBendAction->setShortcut( Qt::SHIFT | Qt::Key_T );
connect( editModeGroup, SIGNAL(triggered(int)), m_editor, SLOT(setEditMode(int)));
// Quantize combo button
auto quantizeButton = new QToolButton(notesActionsToolBar);
auto quantizeButtonMenu = new QMenu(quantizeButton);
auto quantizeAction = new QAction(embed::getIconPixmap("quantize"), tr("Quantize"), this);
auto quantizePosAction = new QAction(tr("Quantize positions"), this);
auto quantizeLengthAction = new QAction(tr("Quantize lengths"), this);
connect(quantizeAction, &QAction::triggered, [this](){ m_editor->quantizeNotes(); });
connect(quantizePosAction, &QAction::triggered, [this](){ m_editor->quantizeNotes(PianoRoll::QuantizeAction::Pos); });
connect(quantizeLengthAction, &QAction::triggered, [this](){ m_editor->quantizeNotes(PianoRoll::QuantizeAction::Length); });
quantizeButton->setPopupMode(QToolButton::MenuButtonPopup);
quantizeButton->setDefaultAction(quantizeAction);
quantizeButton->setMenu(quantizeButtonMenu);
quantizeButtonMenu->addAction(quantizePosAction);
quantizeButtonMenu->addAction(quantizeLengthAction);
notesActionsToolBar->addAction( drawAction );
notesActionsToolBar->addAction( eraseAction );
notesActionsToolBar->addAction( selectAction );
notesActionsToolBar->addAction( pitchBendAction );
notesActionsToolBar->addSeparator();
notesActionsToolBar->addWidget(quantizeButton);
// -- File actions
DropToolBar* fileActionsToolBar = addDropToolBarToTop(tr("File actions"));
// -- File ToolButton
m_fileToolsButton = new QToolButton(m_toolBar);
m_fileToolsButton->setIcon(embed::getIconPixmap("file"));
m_fileToolsButton->setPopupMode(QToolButton::InstantPopup);
// Import / export
auto importAction = new QAction(embed::getIconPixmap("project_import"), tr("Import clip"), m_fileToolsButton);
auto exportAction = new QAction(embed::getIconPixmap("project_export"), tr("Export clip"), m_fileToolsButton);
m_fileToolsButton->addAction(importAction);
m_fileToolsButton->addAction(exportAction);
fileActionsToolBar->addWidget(m_fileToolsButton);
connect(importAction, SIGNAL(triggered()), this, SLOT(importMidiClip()));
connect(exportAction, SIGNAL(triggered()), this, SLOT(exportMidiClip()));
// -- End File actions
// Copy + paste actions
DropToolBar *copyPasteActionsToolBar = addDropToolBarToTop( tr( "Copy paste controls" ) );
auto cutAction = new QAction(embed::getIconPixmap("edit_cut"), tr("Cut (%1+X)").arg(UI_CTRL_KEY), this);
auto copyAction = new QAction(embed::getIconPixmap("edit_copy"), tr("Copy (%1+C)").arg(UI_CTRL_KEY), this);
auto pasteAction = new QAction(embed::getIconPixmap("edit_paste"), tr("Paste (%1+V)").arg(UI_CTRL_KEY), this);
cutAction->setShortcut( Qt::CTRL | Qt::Key_X );
copyAction->setShortcut( Qt::CTRL | Qt::Key_C );
pasteAction->setShortcut( Qt::CTRL | Qt::Key_V );
connect( cutAction, SIGNAL(triggered()), m_editor, SLOT(cutSelectedNotes()));
connect( copyAction, SIGNAL(triggered()), m_editor, SLOT(copySelectedNotes()));
connect( pasteAction, SIGNAL(triggered()), m_editor, SLOT(pasteNotes()));
copyPasteActionsToolBar->addAction( cutAction );
copyPasteActionsToolBar->addAction( copyAction );
copyPasteActionsToolBar->addAction( pasteAction );
DropToolBar *timeLineToolBar = addDropToolBarToTop( tr( "Timeline controls" ) );
m_editor->m_timeLine->addToolButtons( timeLineToolBar );
// -- Note modifier tools
auto noteToolsButton = new QToolButton(m_toolBar);
noteToolsButton->setIcon(embed::getIconPixmap("tool"));
noteToolsButton->setPopupMode(QToolButton::InstantPopup);
auto glueAction = new QAction(embed::getIconPixmap("glue"), tr("Glue"), noteToolsButton);
connect(glueAction, SIGNAL(triggered()), m_editor, SLOT(glueNotes()));
glueAction->setShortcut( Qt::SHIFT | Qt::Key_G );
auto knifeAction = new QAction(embed::getIconPixmap("edit_knife"), tr("Knife"), noteToolsButton);
connect(knifeAction, &QAction::triggered, m_editor, &PianoRoll::setKnifeAction);
knifeAction->setShortcut( Qt::SHIFT | Qt::Key_K );
auto fillAction = new QAction(embed::getIconPixmap("fill"), tr("Fill"), noteToolsButton);
connect(fillAction, &QAction::triggered, [this](){ m_editor->fitNoteLengths(true); });
fillAction->setShortcut(Qt::SHIFT | Qt::Key_F);
auto cutOverlapsAction = new QAction(embed::getIconPixmap("cut_overlaps"), tr("Cut overlaps"), noteToolsButton);
connect(cutOverlapsAction, &QAction::triggered, [this](){ m_editor->fitNoteLengths(false); });
cutOverlapsAction->setShortcut(Qt::SHIFT | Qt::Key_C);
auto minLengthAction = new QAction(embed::getIconPixmap("min_length"), tr("Min length as last"), noteToolsButton);
connect(minLengthAction, &QAction::triggered, [this](){ m_editor->constrainNoteLengths(false); });
auto maxLengthAction = new QAction(embed::getIconPixmap("max_length"), tr("Max length as last"), noteToolsButton);
connect(maxLengthAction, &QAction::triggered, [this](){ m_editor->constrainNoteLengths(true); });
noteToolsButton->addAction(glueAction);
noteToolsButton->addAction(knifeAction);
noteToolsButton->addAction(fillAction);
noteToolsButton->addAction(cutOverlapsAction);
noteToolsButton->addAction(minLengthAction);
noteToolsButton->addAction(maxLengthAction);
notesActionsToolBar->addWidget(noteToolsButton);
addToolBarBreak();
DropToolBar *zoomAndNotesToolBar = addDropToolBarToTop( tr( "Zoom and note controls" ) );
auto zoom_lbl = new QLabel(m_toolBar);
zoom_lbl->setPixmap( embed::getIconPixmap( "zoom_x" ) );
m_zoomingComboBox = new ComboBox( m_toolBar );
m_zoomingComboBox->setModel( &m_editor->m_zoomingModel );
m_zoomingComboBox->setFixedSize( 64, ComboBox::DEFAULT_HEIGHT );
m_zoomingComboBox->setToolTip( tr( "Horizontal zooming") );
auto zoom_y_lbl = new QLabel(m_toolBar);
zoom_y_lbl->setPixmap(embed::getIconPixmap("zoom_y"));
m_zoomingYComboBox = new ComboBox(m_toolBar);
m_zoomingYComboBox->setModel(&m_editor->m_zoomingYModel);
m_zoomingYComboBox->setFixedSize(64, ComboBox::DEFAULT_HEIGHT);
m_zoomingYComboBox->setToolTip(tr("Vertical zooming"));
// setup quantize-stuff
auto quantize_lbl = new QLabel(m_toolBar);
quantize_lbl->setPixmap( embed::getIconPixmap( "quantize" ) );
m_quantizeComboBox = new ComboBox( m_toolBar );
m_quantizeComboBox->setModel( &m_editor->m_quantizeModel );
m_quantizeComboBox->setFixedSize(85, ComboBox::DEFAULT_HEIGHT);
m_quantizeComboBox->setToolTip( tr( "Quantization") );
// setup note-len-stuff
auto note_len_lbl = new QLabel(m_toolBar);
note_len_lbl->setPixmap( embed::getIconPixmap( "note" ) );
m_noteLenComboBox = new ComboBox( m_toolBar );
m_noteLenComboBox->setModel( &m_editor->m_noteLenModel );
m_noteLenComboBox->setFixedSize( 105, ComboBox::DEFAULT_HEIGHT );
m_noteLenComboBox->setToolTip( tr( "Note length") );
// setup key-stuff
m_keyComboBox = new ComboBox(m_toolBar);
m_keyComboBox->setModel(&m_editor->m_keyModel);
m_keyComboBox->setFixedSize(72, ComboBox::DEFAULT_HEIGHT);
m_keyComboBox->setToolTip(tr("Key"));
// setup scale-stuff
auto scale_lbl = new QLabel(m_toolBar);
scale_lbl->setPixmap( embed::getIconPixmap( "scale" ) );
m_scaleComboBox = new ComboBox( m_toolBar );
m_scaleComboBox->setModel( &m_editor->m_scaleModel );
m_scaleComboBox->setFixedSize(155, ComboBox::DEFAULT_HEIGHT);
m_scaleComboBox->setToolTip( tr( "Scale") );
// setup chord-stuff
auto chord_lbl = new QLabel(m_toolBar);
chord_lbl->setPixmap( embed::getIconPixmap( "chord" ) );
m_chordComboBox = new ComboBox( m_toolBar );
m_chordComboBox->setModel( &m_editor->m_chordModel );
m_chordComboBox->setFixedSize(125, ComboBox::DEFAULT_HEIGHT);
m_chordComboBox->setToolTip( tr( "Chord" ) );
// setup snap-stuff
auto snapLbl = new QLabel(m_toolBar);
snapLbl->setPixmap(embed::getIconPixmap("gridmode"));
m_snapComboBox = new ComboBox(m_toolBar);
m_snapComboBox->setModel(&m_editor->m_snapModel);
m_snapComboBox->setFixedSize(96, ComboBox::DEFAULT_HEIGHT);
m_snapComboBox->setToolTip(tr("Snap mode"));
// -- Clear ghost MIDI clip button
m_clearGhostButton = new QPushButton( m_toolBar );
m_clearGhostButton->setIcon( embed::getIconPixmap( "clear_ghost_note" ) );
m_clearGhostButton->setToolTip( tr( "Clear ghost notes" ) );
m_clearGhostButton->setEnabled( false );
connect( m_clearGhostButton, SIGNAL(clicked()), m_editor, SLOT(clearGhostClip()));
connect( m_editor, SIGNAL(ghostClipSet(bool)), this, SLOT(ghostClipSet(bool)));
// Wrap label icons and comboboxes in a single widget so when
// the window is resized smaller in width it hides both
auto zoom_widget = new QWidget();
auto zoom_hbox = new QHBoxLayout();
zoom_hbox->setContentsMargins(0, 0, 0, 0);
zoom_hbox->addWidget(zoom_lbl);
zoom_hbox->addWidget(m_zoomingComboBox);
zoom_widget->setLayout(zoom_hbox);
zoomAndNotesToolBar->addWidget(zoom_widget);
auto zoomY_widget = new QWidget();
auto zoomY_hbox = new QHBoxLayout();
zoomY_hbox->setContentsMargins(0, 0, 0, 0);
zoomY_hbox->addWidget(zoom_y_lbl);
zoomY_hbox->addWidget(m_zoomingYComboBox);
zoomY_widget->setLayout(zoomY_hbox);
zoomAndNotesToolBar->addWidget(zoomY_widget);
auto quantize_widget = new QWidget();
auto quantize_hbox = new QHBoxLayout();
quantize_hbox->setContentsMargins(0, 0, 0, 0);
quantize_hbox->addWidget(quantize_lbl);
quantize_hbox->addWidget(m_quantizeComboBox);
quantize_widget->setLayout(quantize_hbox);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget(quantize_widget);
auto note_widget = new QWidget();
auto note_hbox = new QHBoxLayout();
note_hbox->setContentsMargins(0, 0, 0, 0);
note_hbox->addWidget(note_len_lbl);
note_hbox->addWidget(m_noteLenComboBox);
note_widget->setLayout(note_hbox);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget(note_widget);
auto scale_widget = new QWidget();
auto scale_hbox = new QHBoxLayout();
scale_hbox->setContentsMargins(0, 0, 0, 0);
scale_hbox->addWidget(scale_lbl);
// Add the key selection between scale label and key
scale_hbox->addWidget(m_keyComboBox);
scale_hbox->addWidget(m_scaleComboBox);
scale_widget->setLayout(scale_hbox);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget(scale_widget);
auto chord_widget = new QWidget();
auto chord_hbox = new QHBoxLayout();
chord_hbox->setContentsMargins(0, 0, 0, 0);
chord_hbox->addWidget(chord_lbl);
chord_hbox->addWidget(m_chordComboBox);
chord_widget->setLayout(chord_hbox);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget(chord_widget);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget( m_clearGhostButton );
auto snapWidget = new QWidget();
auto snapHbox = new QHBoxLayout();
snapHbox->setContentsMargins(0, 0, 0, 0);
snapHbox->addWidget(snapLbl);
snapHbox->addWidget(m_snapComboBox);
snapWidget->setLayout(snapHbox);
zoomAndNotesToolBar->addSeparator();
zoomAndNotesToolBar->addWidget(snapWidget);
// setup our actual window
setFocusPolicy( Qt::StrongFocus );
setFocus();
setWindowIcon( embed::getIconPixmap( "piano" ) );
setCurrentMidiClip( nullptr );
// Connections
connect( m_editor, SIGNAL(currentMidiClipChanged()), this, SIGNAL(currentMidiClipChanged()));
connect( m_editor, SIGNAL(currentMidiClipChanged()), this, SLOT(updateAfterMidiClipChange()));
}
const MidiClip* PianoRollWindow::currentMidiClip() const
{
return m_editor->currentMidiClip();
}
void PianoRollWindow::setGhostMidiClip( MidiClip* clip )
{
m_editor->setGhostMidiClip( clip );
}
void PianoRollWindow::setCurrentMidiClip( MidiClip* clip )
{
m_editor->setCurrentMidiClip( clip );
if ( clip )
{
setWindowTitle( tr( "Piano-Roll - %1" ).arg( clip->name() ) );
m_fileToolsButton->setEnabled(true);
connect( clip->instrumentTrack(), SIGNAL(nameChanged()), this, SLOT(updateAfterMidiClipChange()));
connect( clip, SIGNAL(dataChanged()), this, SLOT(updateAfterMidiClipChange()));
}
else
{
setWindowTitle( tr( "Piano-Roll - no clip" ) );
m_fileToolsButton->setEnabled(false);
}
}
bool PianoRollWindow::isRecording() const
{
return m_editor->isRecording();
}
int PianoRollWindow::quantization() const
{
return m_editor->quantization();
}
void PianoRollWindow::play()
{
m_editor->play();
}
void PianoRollWindow::stop()
{
m_editor->stop();
}
void PianoRollWindow::record()
{
stopStepRecording(); //step recording mode is mutually exclusive with other record modes
m_editor->record();
}
void PianoRollWindow::recordAccompany()
{
stopStepRecording(); //step recording mode is mutually exclusive with other record modes
m_editor->recordAccompany();
}
void PianoRollWindow::toggleStepRecording()
{
if(isRecording())
{
// step recording mode is mutually exclusive with other record modes
// stop them before starting step recording
stop();
}
m_editor->toggleStepRecording();
updateStepRecordingIcon();
}
void PianoRollWindow::stopRecording()
{
m_editor->stopRecording();
}
void PianoRollWindow::reset()
{
m_editor->reset();
}
void PianoRollWindow::saveSettings( QDomDocument & doc, QDomElement & de )
{
if( !m_editor->ghostNotes().empty() )
{
QDomElement ghostNotesRoot = doc.createElement( "ghostnotes" );
for( Note *note : m_editor->ghostNotes() )
{
QDomElement ghostNoteNode = doc.createElement( "ghostnote" );
ghostNoteNode.setAttribute( "len", note->length() );
ghostNoteNode.setAttribute( "key", note->key() );
ghostNoteNode.setAttribute( "pos", note->pos() );
ghostNotesRoot.appendChild(ghostNoteNode);
}
de.appendChild( ghostNotesRoot );
}
if (m_editor->m_markedSemiTones.length() > 0)
{
QDomElement markedSemiTonesRoot = doc.createElement("markedSemiTones");
for (int markedSemiTone : m_editor->m_markedSemiTones)
{
QDomElement semiToneNode = doc.createElement("semiTone");
semiToneNode.setAttribute("key", markedSemiTone);
markedSemiTonesRoot.appendChild(semiToneNode);
}
de.appendChild(markedSemiTonesRoot);
}
de.setAttribute("stopbehaviour", static_cast<int>(
Engine::getSong()->getTimeline(Song::PlayMode::MidiClip).stopBehaviour()));
MainWindow::saveWidgetState( this, de );
}
void PianoRollWindow::loadSettings( const QDomElement & de )
{
m_editor->loadGhostNotes( de.firstChildElement("ghostnotes") );
m_editor->loadMarkedSemiTones(de.firstChildElement("markedSemiTones"));
MainWindow::restoreWidgetState( this, de );
Engine::getSong()->getTimeline(Song::PlayMode::MidiClip).setStopBehaviour(
static_cast<Timeline::StopBehaviour>(de.attribute("stopbehaviour").toInt()));
// update margins here because we're later in the startup process
// We can't earlier because everything is still starting with the
// WHITE_KEY_WIDTH default
QMargins qm = m_editor->m_stepRecorderWidget.margins();
qm.setLeft(m_editor->m_whiteKeyWidth);
m_editor->m_stepRecorderWidget.setMargins(qm);
m_editor->m_timeLine->setXOffset(m_editor->m_whiteKeyWidth);
}
QSize PianoRollWindow::sizeHint() const
{
return { INITIAL_PIANOROLL_WIDTH, INITIAL_PIANOROLL_HEIGHT };
}
bool PianoRollWindow::hasFocus() const
{
return m_editor->hasFocus();
}
void PianoRollWindow::updateAfterMidiClipChange()
{
clipRenamed();
updateStepRecordingIcon(); //MIDI clip change turn step recording OFF - update icon accordingly
}
void PianoRollWindow::clipRenamed()
{
if ( currentMidiClip() )
{
setWindowTitle( tr( "Piano-Roll - %1" ).arg( currentMidiClip()->name() ) );
m_fileToolsButton->setEnabled(true);
}
else
{
setWindowTitle( tr( "Piano-Roll - no clip" ) );
m_fileToolsButton->setEnabled(false);
}
}
void PianoRollWindow::ghostClipSet( bool state )
{
m_clearGhostButton->setEnabled( state );
}
void PianoRollWindow::exportMidiClip()
{
FileDialog exportDialog(this, tr("Export clip"), "",
tr("XML clip file (*.xpt *.xptz)"));
exportDialog.setAcceptMode(FileDialog::AcceptSave);
if (exportDialog.exec() == QDialog::Accepted &&
!exportDialog.selectedFiles().isEmpty() &&
!exportDialog.selectedFiles().first().isEmpty())
{
QString suffix =
ConfigManager::inst()->value("app", "nommpz").toInt() == 0
? "xptz"
: "xpt";
exportDialog.setDefaultSuffix(suffix);
const QString fullPath = exportDialog.selectedFiles()[0];
DataFile dataFile(DataFile::Type::MidiClip);
m_editor->m_midiClip->saveSettings(dataFile, dataFile.content());
if (dataFile.writeFile(fullPath))
{
TextFloat::displayMessage(tr("Export clip success"),
tr("Clip saved to %1").arg(fullPath),
embed::getIconPixmap("project_export"), 4000);
}
}
}
void PianoRollWindow::importMidiClip()
{
// Overwrite confirmation.
if (!m_editor->m_midiClip->empty() &&
QMessageBox::warning(
nullptr,
tr("Import clip."),
tr("You are about to import a clip, this will "
"overwrite your current clip. Do you want to "
"continue?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes
) != QMessageBox::Yes)
{
return;
}
FileDialog importDialog(this, tr("Open clip"), "",
tr("XML clip file (*.xpt *.xptz)"));
importDialog.setFileMode(FileDialog::ExistingFile);
if (importDialog.exec() == QDialog::Accepted &&
!importDialog.selectedFiles().isEmpty())
{
const QString fullPath = importDialog.selectedFiles()[0];
DataFile dataFile(fullPath);
if (dataFile.head().isNull())
{
return;
}
TimePos pos = m_editor->m_midiClip->startPosition(); // Backup position in timeline.
m_editor->m_midiClip->loadSettings(dataFile.content());
m_editor->m_midiClip->movePosition(pos);
TextFloat::displayMessage(tr("Import clip success"),
tr("Imported clip %1!").arg(fullPath),
embed::getIconPixmap("project_import"), 4000);
}
}
void PianoRollWindow::focusInEvent( QFocusEvent * event )
{
// when the window is given focus, also give focus to the actual piano roll
m_editor->setFocus( event->reason() );
}
void PianoRollWindow::stopStepRecording()
{
if(m_editor->isStepRecording())
{
m_editor->toggleStepRecording();
updateStepRecordingIcon();
}
}
void PianoRollWindow::updateStepRecordingIcon()
{
if(m_editor->isStepRecording())
{
m_toggleStepRecordingAction->setIcon(embed::getIconPixmap("record_step_on"));
}
else
{
m_toggleStepRecordingAction->setIcon(embed::getIconPixmap("record_step_off"));
}
}
} // namespace gui
} // namespace lmms
| 142,639
|
C++
|
.cpp
| 4,468
| 28.424575
| 139
| 0.679994
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,992
|
PositionLine.cpp
|
LMMS_lmms/src/gui/editors/PositionLine.cpp
|
/*
* PositionLine.cpp
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PositionLine.h"
#include <QPainter>
#include "Song.h"
namespace lmms::gui
{
PositionLine::PositionLine(QWidget* parent) :
QWidget(parent),
m_hasTailGradient(false),
m_lineColor(0, 0, 0, 0)
{
resize(8, height());
setAttribute(Qt::WA_NoSystemBackground, true);
setAttribute(Qt::WA_TransparentForMouseEvents);
}
void PositionLine::paintEvent(QPaintEvent* pe)
{
QPainter p(this);
auto c = QColor(m_lineColor);
// If width is 1, we don't need a gradient
if (width() == 1)
{
c.setAlpha(153);
p.fillRect(rect(), c);
}
// If width > 1, we need the gradient
else
{
// Create the gradient trail behind the line
QLinearGradient gradient(rect().bottomLeft(), rect().bottomRight());
qreal w = (width() - 1.0) / width();
// If gradient is enabled, we're in focus and we're playing, enable gradient
if (m_hasTailGradient &&
Engine::getSong()->isPlaying() &&
(Engine::getSong()->playMode() == Song::PlayMode::Song ||
Engine::getSong()->playMode() == Song::PlayMode::MidiClip))
{
c.setAlpha(60);
gradient.setColorAt(w, c);
}
else
{
c.setAlpha(0);
gradient.setColorAt(w, c);
}
// Fill in the remaining parts
c.setAlpha(0);
gradient.setColorAt(0, c);
c.setAlpha(153);
gradient.setColorAt(1, c);
// Fill line
p.fillRect(rect(), gradient);
}
}
// NOTE: the move() implementation fixes a bug where the position line would appear
// in an unexpected location when positioned at the start of the track
void PositionLine::zoomChange(float zoom)
{
int playHeadPos = x() + width() - 1;
resize(std::max(8.0 * zoom, 1.0), height());
move(playHeadPos - width() + 1, y());
update();
}
} // namespace lmms::gui
| 2,584
|
C++
|
.cpp
| 86
| 27.662791
| 83
| 0.713825
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,993
|
AutomationEditor.cpp
|
LMMS_lmms/src/gui/editors/AutomationEditor.cpp
|
/*
* AutomationEditor.cpp - implementation of AutomationEditor which is used for
* actual setting of dynamic values
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2008-2013 Paul Giblock <pgib/at/users.sourceforge.net>
* Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AutomationEditor.h"
#include <QApplication>
#include <QInputDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QPainter>
#include <QPainterPath>
#include <QScrollBar>
#include <QStyleOption>
#include <QToolTip>
#include <cmath>
#include "SampleClip.h"
#include "SampleWaveform.h"
#ifndef __USE_XOPEN
#define __USE_XOPEN
#endif
#include "ActionGroup.h"
#include "AutomationNode.h"
#include "ComboBox.h"
#include "DeprecationHelper.h"
#include "DetuningHelper.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "Knob.h"
#include "MainWindow.h"
#include "MidiClip.h"
#include "PatternStore.h"
#include "PianoRoll.h"
#include "ProjectJournal.h"
#include "SampleBuffer.h"
#include "StringPairDrag.h"
#include "TextFloat.h"
#include "TimeLineWidget.h"
#include "debug.h"
#include "embed.h"
#include "FontHelper.h"
namespace lmms::gui
{
const std::array<float, 7> AutomationEditor::m_zoomXLevels =
{ 0.125f, 0.25f, 0.5f, 1.0f, 2.0f, 4.0f, 8.0f };
AutomationEditor::AutomationEditor() :
QWidget(),
m_zoomingXModel(),
m_zoomingYModel(),
m_quantizeModel(),
m_clip(nullptr),
m_minLevel( 0 ),
m_maxLevel( 0 ),
m_step( 1 ),
m_scrollLevel( 0 ),
m_bottomLevel( 0 ),
m_topLevel( 0 ),
m_currentPosition(),
m_action( Action::None ),
m_drawLastLevel( 0.0f ),
m_drawLastTick( 0 ),
m_ppb( DEFAULT_PPB ),
m_y_delta( DEFAULT_Y_DELTA ),
m_y_auto( true ),
m_editMode( EditMode::Draw ),
m_mouseDownLeft(false),
m_mouseDownRight( false ),
m_scrollBack( false ),
m_barLineColor(0, 0, 0),
m_beatLineColor(0, 0, 0),
m_lineColor(0, 0, 0),
m_graphColor(Qt::SolidPattern),
m_nodeInValueColor(0, 0, 0),
m_nodeOutValueColor(0, 0, 0),
m_nodeTangentLineColor(0, 0, 0),
m_scaleColor(Qt::SolidPattern),
m_crossColor(0, 0, 0),
m_backgroundShade(0, 0, 0),
m_ghostNoteColor(0, 0, 0)
{
connect( this, SIGNAL(currentClipChanged()),
this, SLOT(updateAfterClipChange()),
Qt::QueuedConnection );
connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)),
this, SLOT(update()));
setAttribute( Qt::WA_OpaquePaintEvent, true );
//keeps the direction of the widget, undepended on the locale
setLayoutDirection( Qt::LeftToRight );
m_tensionModel = new FloatModel(1.f, 0.f, 1.f, 0.01f);
connect( m_tensionModel, SIGNAL(dataChanged()),
this, SLOT(setTension()));
for (auto q : Quantizations) {
m_quantizeModel.addItem(QString("1/%1").arg(q));
}
connect( &m_quantizeModel, SIGNAL(dataChanged()),
this, SLOT(setQuantization()));
m_quantizeModel.setValue( m_quantizeModel.findText( "1/8" ) );
// add time-line
m_timeLine = new TimeLineWidget(VALUES_WIDTH, 0, m_ppb,
Engine::getSong()->getPlayPos(Song::PlayMode::AutomationClip),
Engine::getSong()->getTimeline(Song::PlayMode::AutomationClip),
m_currentPosition, Song::PlayMode::AutomationClip, this
);
connect(this, &AutomationEditor::positionChanged, m_timeLine, &TimeLineWidget::updatePosition);
connect( m_timeLine, SIGNAL( positionChanged( const lmms::TimePos& ) ),
this, SLOT( updatePosition( const lmms::TimePos& ) ) );
// init scrollbars
m_leftRightScroll = new QScrollBar( Qt::Horizontal, this );
m_leftRightScroll->setSingleStep( 1 );
connect( m_leftRightScroll, SIGNAL(valueChanged(int)), this,
SLOT(horScrolled(int)));
m_topBottomScroll = new QScrollBar( Qt::Vertical, this );
m_topBottomScroll->setSingleStep( 1 );
m_topBottomScroll->setPageStep( 20 );
connect( m_topBottomScroll, SIGNAL(valueChanged(int)), this,
SLOT(verScrolled(int)));
setCurrentClip(nullptr);
setMouseTracking( true );
setFocusPolicy( Qt::StrongFocus );
setFocus();
}
AutomationEditor::~AutomationEditor()
{
m_zoomingXModel.disconnect();
m_zoomingYModel.disconnect();
m_quantizeModel.disconnect();
m_tensionModel->disconnect();
delete m_tensionModel;
}
void AutomationEditor::setCurrentClip(AutomationClip * new_clip )
{
if (m_clip)
{
m_clip->disconnect(this);
}
m_clip = new_clip;
if (m_clip != nullptr)
{
connect(m_clip, SIGNAL(dataChanged()), this, SLOT(update()));
}
emit currentClipChanged();
}
void AutomationEditor::saveSettings(QDomDocument & doc, QDomElement & dom_parent)
{
MainWindow::saveWidgetState( parentWidget(), dom_parent );
}
void AutomationEditor::loadSettings( const QDomElement & dom_parent)
{
MainWindow::restoreWidgetState(parentWidget(), dom_parent);
}
void AutomationEditor::updateAfterClipChange()
{
m_currentPosition = 0;
if( !validClip() )
{
m_minLevel = m_maxLevel = m_scrollLevel = 0;
m_step = 1;
resizeEvent(nullptr);
return;
}
m_minLevel = m_clip->firstObject()->minValue<float>();
m_maxLevel = m_clip->firstObject()->maxValue<float>();
m_step = m_clip->firstObject()->step<float>();
centerTopBottomScroll();
m_tensionModel->setValue( m_clip->getTension() );
// resizeEvent() does the rest for us (scrolling, range-checking
// of levels and so on...)
resizeEvent(nullptr);
update();
}
void AutomationEditor::update()
{
QWidget::update();
// Note detuning?
if( m_clip && !m_clip->getTrack() )
{
getGUI()->pianoRoll()->update();
}
}
void AutomationEditor::keyPressEvent(QKeyEvent * ke )
{
switch( ke->key() )
{
case Qt::Key_Up:
m_topBottomScroll->setValue(
m_topBottomScroll->value() - 1 );
ke->accept();
break;
case Qt::Key_Down:
m_topBottomScroll->setValue(
m_topBottomScroll->value() + 1 );
ke->accept();
break;
case Qt::Key_Left:
if( ( m_timeLine->pos() -= 16 ) < 0 )
{
m_timeLine->pos().setTicks( 0 );
}
m_timeLine->updatePosition();
ke->accept();
break;
case Qt::Key_Right:
m_timeLine->pos() += 16;
m_timeLine->updatePosition();
ke->accept();
break;
case Qt::Key_Home:
m_timeLine->pos().setTicks( 0 );
m_timeLine->updatePosition();
ke->accept();
break;
default:
break;
}
}
void AutomationEditor::leaveEvent(QEvent * e )
{
while (QApplication::overrideCursor() != nullptr)
{
QApplication::restoreOverrideCursor();
}
QWidget::leaveEvent( e );
update();
}
void AutomationEditor::drawLine( int x0In, float y0, int x1In, float y1 )
{
int x0 = Note::quantized( x0In, AutomationClip::quantization() );
int x1 = Note::quantized( x1In, AutomationClip::quantization() );
int deltax = qAbs( x1 - x0 );
auto deltay = qAbs<float>(y1 - y0);
int x = x0;
float y = y0;
if( deltax < AutomationClip::quantization() )
{
return;
}
deltax /= AutomationClip::quantization();
float yscale = deltay / ( deltax );
int xstep = (x0 < x1 ? 1 : -1) * AutomationClip::quantization();
int ystep = y0 < y1 ? 1 : -1;
float lineAdjust = ystep * yscale;
for (int i = 0; i < deltax; ++i)
{
y = y0 + ( ystep * yscale * i ) + lineAdjust;
x += xstep;
m_clip->removeNode(TimePos(x));
m_clip->putValue( TimePos( x ), y );
}
}
bool AutomationEditor::fineTuneValue(timeMap::iterator node, bool editingOutValue)
{
if (node == m_clip->getTimeMap().end()) { return false; }
// Display dialog to edit the value
bool ok;
double value = QInputDialog::getDouble(
this,
tr("Edit Value"),
editingOutValue
? tr("New outValue")
: tr("New inValue"),
editingOutValue
? OUTVAL(node)
: INVAL(node),
m_clip->firstObject()->minValue<float>(),
m_clip->firstObject()->maxValue<float>(),
3,
&ok
);
// If dialog failed return false
if (!ok) { return false; }
// Set the new inValue/outValue
if (editingOutValue)
{
node.value().setOutValue(value);
}
else
{
// If the outValue is equal to the inValue we
// set both to the given value
if (OFFSET(node) == 0)
{
node.value().setOutValue(value);
}
node.value().setInValue(value);
}
Engine::getSong()->setModified();
return true;
}
void AutomationEditor::mousePressEvent( QMouseEvent* mouseEvent )
{
if( !validClip() )
{
return;
}
// Some helper lambda functions to avoid repetition of code
auto eraseNode = [this](timeMap::iterator node)
{
if (node != m_clip->getTimeMap().end())
{
m_clip->removeNode(POS(node));
Engine::getSong()->setModified();
}
};
auto resetNode = [this](timeMap::iterator node)
{
if (node != m_clip->getTimeMap().end())
{
node.value().resetOutValue();
Engine::getSong()->setModified();
}
};
auto resetTangent = [this](timeMap::iterator node)
{
if (node != m_clip->getTimeMap().end())
{
// Unlock the tangents from that node
node.value().setLockedTangents(false);
// Recalculate the tangents
m_clip->generateTangents(node, 1);
Engine::getSong()->setModified();
}
};
// If we clicked inside the AutomationEditor viewport (where the nodes are represented)
if (mouseEvent->y() > TOP_MARGIN && mouseEvent->x() >= VALUES_WIDTH)
{
float level = getLevel( mouseEvent->y() );
// Get the viewport X
int x = mouseEvent->x() - VALUES_WIDTH;
// Get tick in which the user clicked
int posTicks = (x * TimePos::ticksPerBar() / m_ppb) + m_currentPosition;
// Get the time map of current clip
timeMap & tm = m_clip->getTimeMap();
m_mouseDownLeft = (mouseEvent->button() == Qt::LeftButton);
m_mouseDownRight = (mouseEvent->button() == Qt::RightButton);
// Some actions require that we know if we clicked the inValue of
// a node, while others require that we know if we clicked the outValue
// of a node.
bool editingOutValue = (
m_editMode == EditMode::DrawOutValues
|| (m_editMode == EditMode::Erase && m_mouseDownRight)
);
timeMap::iterator clickedNode = getNodeAt(mouseEvent->x(), mouseEvent->y(), editingOutValue);
switch (m_editMode)
{
case EditMode::Draw:
{
m_clip->addJournalCheckPoint();
if (m_mouseDownLeft)
{
// If we are pressing shift, make a line of nodes from the last
// clicked position to this position
if (mouseEvent->modifiers() & Qt::ShiftModifier)
{
drawLine(m_drawLastTick, m_drawLastLevel,
posTicks, level);
// Update the last clicked position for the next time
m_drawLastTick = posTicks;
m_drawLastLevel = level;
// Changes the action to drawing a line of nodes
m_action = Action::DrawLine;
}
else // No shift, we are just creating/moving nodes
{
// Starts actually moving/draging the node
TimePos newTime = m_clip->setDragValue(
// The TimePos of either the clicked node or a new one
TimePos(
clickedNode == tm.end()
? posTicks
: POS(clickedNode)
),
level,
clickedNode == tm.end(),
mouseEvent->modifiers() & Qt::ControlModifier
);
// We need to update our iterator because we are either creating a new node
// or dragging an existing one. In the latter, setDragValue removes the node that
// is being dragged, so if we don't update it we have a bogus iterator
clickedNode = tm.find(newTime);
// Set the action to Action::MoveValue so moveMouseEvent() knows we are moving a node
m_action = Action::MoveValue;
// Calculate the offset from the place the mouse click happened in comparison
// to the center of the node
int alignedX = (POS(clickedNode) - m_currentPosition) * m_ppb / TimePos::ticksPerBar();
m_moveXOffset = x - alignedX - 1;
// Set move-cursor
QCursor c(Qt::SizeAllCursor);
QApplication::setOverrideCursor(c);
// Update the last clicked position so it can be used if we draw a line later
m_drawLastTick = posTicks;
m_drawLastLevel = level;
}
Engine::getSong()->setModified();
}
else if (m_mouseDownRight) // Right click on EditMode::Draw mode erases values
{
// Update the last clicked position so we remove all nodes from
// that point up to the point we release the mouse button
m_drawLastTick = posTicks;
// If we right-clicked a node, remove it
eraseNode(clickedNode);
m_action = Action::EraseValues;
}
break;
}
case EditMode::Erase:
{
m_clip->addJournalCheckPoint();
// On erase mode, left click removes nodes
if (m_mouseDownLeft)
{
// Update the last clicked position so we remove all nodes from
// that point up to the point we release the mouse button
m_drawLastTick = posTicks;
// If we right-clicked a node, remove it
eraseNode(clickedNode);
m_action = Action::EraseValues;
}
else if (m_mouseDownRight) // And right click resets outValues
{
// If we clicked an outValue reset it
resetNode(clickedNode);
// Update the last clicked position so we reset all outValues from
// that point up to the point we release the mouse button
m_drawLastTick = posTicks;
m_action = Action::ResetOutValues;
}
break;
}
case EditMode::DrawOutValues:
{
m_clip->addJournalCheckPoint();
// On this mode, left click sets the outValue
if (m_mouseDownLeft)
{
// If we clicked an outValue
if (clickedNode != tm.end())
{
m_draggedOutValueKey = POS(clickedNode);
clickedNode.value().setOutValue(level);
m_action = Action::MoveOutValue;
Engine::getSong()->setModified();
}
else // If we didn't click an outValue
{
// We check if the quantized position of the time we clicked has a
// node and set its outValue
TimePos quantizedPos = Note::quantized(
TimePos(posTicks),
m_clip->quantization()
);
clickedNode = tm.find(quantizedPos);
if (clickedNode != tm.end())
{
m_draggedOutValueKey = POS(clickedNode);
clickedNode.value().setOutValue(level);
m_action = Action::MoveOutValue;
Engine::getSong()->setModified();
}
}
}
else if (m_mouseDownRight) // Right click resets outValues
{
// If we clicked an outValue reset it
resetNode(clickedNode);
// Update the last clicked position so we reset all outValues from
// that point up to the point we release the mouse button
m_drawLastTick = posTicks;
m_action = Action::ResetOutValues;
}
break;
}
case EditMode::EditTangents:
{
if (!m_clip->canEditTangents())
{
update();
return;
}
m_clip->addJournalCheckPoint();
// Gets the closest node to the mouse click
timeMap::iterator node = getClosestNode(mouseEvent->x());
// Starts dragging a tangent
if (m_mouseDownLeft && node != tm.end())
{
// Lock the tangents from that node, so it can only be
// manually edited
node.value().setLockedTangents(true);
m_draggedTangentTick = POS(node);
// Are we dragging the out or in tangent?
m_draggedOutTangent = posTicks >= m_draggedTangentTick;
m_action = Action::MoveTangent;
}
// Resets node's tangent
else if (m_mouseDownRight)
{
// Resets tangent from node
resetTangent(node);
// Update the last clicked position so we reset all tangents from
// that point up to the point we release the mouse button
m_drawLastTick = posTicks;
m_action = Action::ResetTangents;
}
break;
}
}
update();
}
}
void AutomationEditor::mouseDoubleClickEvent(QMouseEvent * mouseEvent)
{
if (!validClip()) { return; }
// If we double clicked outside the AutomationEditor viewport return
if (mouseEvent->y() <= TOP_MARGIN || mouseEvent->x() < VALUES_WIDTH) { return; }
// Are we fine tuning the inValue or outValue?
const bool isOutVal = (m_editMode == EditMode::DrawOutValues);
timeMap::iterator clickedNode = getNodeAt(mouseEvent->x(), mouseEvent->y(), isOutVal);
switch (m_editMode)
{
case EditMode::Draw:
case EditMode::DrawOutValues:
if (fineTuneValue(clickedNode, isOutVal)) { update(); }
break;
default:
break;
}
}
void AutomationEditor::mouseReleaseEvent(QMouseEvent * mouseEvent )
{
bool mustRepaint = false;
if (mouseEvent->button() == Qt::LeftButton)
{
m_mouseDownLeft = false;
mustRepaint = true;
}
if (mouseEvent->button() == Qt::RightButton)
{
m_mouseDownRight = false;
mustRepaint = true;
}
if (m_editMode == EditMode::Draw)
{
if (m_action == Action::MoveValue)
{
// Actually apply the value of the node being dragged
m_clip->applyDragValue();
}
QApplication::restoreOverrideCursor();
}
m_action = Action::None;
if (mustRepaint) { repaint(); }
}
void AutomationEditor::mouseMoveEvent(QMouseEvent * mouseEvent )
{
if( !validClip() )
{
update();
return;
}
// If the mouse y position is inside the Automation Editor viewport
if (mouseEvent->y() > TOP_MARGIN)
{
float level = getLevel(mouseEvent->y());
// Get the viewport X position where the mouse is at
int x = mouseEvent->x() - VALUES_WIDTH;
// Get the X position in ticks
int posTicks = (x * TimePos::ticksPerBar() / m_ppb) + m_currentPosition;
switch (m_editMode)
{
case EditMode::Draw:
{
// We are dragging a node
if (m_mouseDownLeft)
{
if (m_action == Action::MoveValue)
{
// When we clicked the node, we might have clicked slightly off
// so we account for that offset for a smooth drag
x -= m_moveXOffset;
posTicks = (x * TimePos::ticksPerBar() / m_ppb) + m_currentPosition;
// If we moved the mouse past the beginning correct the position in ticks
posTicks = qMax(posTicks, 0);
m_drawLastTick = posTicks;
m_drawLastLevel = level;
// Updates the drag value of the moved node
m_clip->setDragValue(
TimePos(posTicks),
level,
true,
mouseEvent->modifiers() & Qt::ControlModifier
);
Engine::getSong()->setModified();
}
/* else if (m_action == Action::DrawLine)
{
// We are drawing a line. For now do nothing (as before), but later logic
// could be added here so the line is updated according to the new mouse position
// until the button is released
}*/
}
else if (m_mouseDownRight) // We are removing nodes
{
if (m_action == Action::EraseValues)
{
// If we moved the mouse past the beginning correct the position in ticks
posTicks = qMax(posTicks, 0);
// Removing automation nodes
// Removes all values from the last clicked tick up to the current position tick
m_clip->removeNodes(m_drawLastTick, posTicks);
Engine::getSong()->setModified();
}
}
break;
}
case EditMode::Erase:
{
// If we moved the mouse past the beginning correct the position in ticks
posTicks = qMax(posTicks, 0);
// Left button removes nodes
if (m_mouseDownLeft)
{
if (m_action == Action::EraseValues)
{
// Removing automation nodes
// Removes all values from the last clicked tick up to the current position tick
m_clip->removeNodes(m_drawLastTick, posTicks);
Engine::getSong()->setModified();
}
}
else if (m_mouseDownRight) // Right button resets outValues
{
if (m_action == Action::ResetOutValues)
{
// Reseting outValues
// Resets all values from the last clicked tick up to the current position tick
m_clip->resetNodes(m_drawLastTick, posTicks);
Engine::getSong()->setModified();
}
}
break;
}
case EditMode::DrawOutValues:
{
// If we moved the mouse past the beginning correct the position in ticks
posTicks = qMax(posTicks, 0);
// Left button moves outValues
if (m_mouseDownLeft)
{
if (m_action == Action::MoveOutValue)
{
// We are moving the outValue of the node
timeMap & tm = m_clip->getTimeMap();
timeMap::iterator it = tm.find(m_draggedOutValueKey);
// Safety check
if (it != tm.end())
{
it.value().setOutValue(level);
Engine::getSong()->setModified();
}
}
}
else if (m_mouseDownRight) // Right button resets them
{
if (m_action == Action::ResetOutValues)
{
// Reseting outValues
// Resets all values from the last clicked tick up to the current position tick
m_clip->resetNodes(m_drawLastTick, posTicks);
Engine::getSong()->setModified();
}
}
break;
}
case EditMode::EditTangents:
{
// If we moved the mouse past the beginning correct the position in ticks
posTicks = std::max(posTicks, 0);
if (m_mouseDownLeft && m_action == Action::MoveTangent)
{
timeMap& tm = m_clip->getTimeMap();
auto it = tm.find(m_draggedTangentTick);
// Safety check
if (it == tm.end())
{
update();
return;
}
// Calculate new tangent
float y = m_draggedOutTangent
? yCoordOfLevel(OUTVAL(it))
: yCoordOfLevel(INVAL(it));
float dy = m_draggedOutTangent
? y - mouseEvent->y()
: mouseEvent->y() - y;
float dx = std::abs(posTicks - POS(it));
float newTangent = dy / std::max(dx, 1.0f);
if (m_draggedOutTangent)
{
it.value().setOutTangent(newTangent);
}
else
{
it.value().setInTangent(newTangent);
}
}
else if (m_mouseDownRight && m_action == Action::ResetTangents)
{
// Resets all tangents from the last clicked tick up to the current position tick
m_clip->resetTangents(m_drawLastTick, posTicks);
Engine::getSong()->setModified();
}
break;
}
}
}
else // If the mouse Y position is above the AutomationEditor viewport
{
QApplication::restoreOverrideCursor();
}
update();
}
inline void AutomationEditor::drawCross( QPainter & p )
{
QPoint mouse_pos = mapFromGlobal( QCursor::pos() );
int grid_bottom = height() - SCROLLBAR_SIZE - 1;
float level = getLevel( mouse_pos.y() );
float cross_y = m_y_auto ?
grid_bottom - ( ( grid_bottom - TOP_MARGIN )
* ( level - m_minLevel )
/ (float)( m_maxLevel - m_minLevel ) ) :
grid_bottom - ( level - m_bottomLevel ) * m_y_delta;
p.setPen(m_crossColor);
p.drawLine( VALUES_WIDTH, (int) cross_y, width(), (int) cross_y );
p.drawLine( mouse_pos.x(), TOP_MARGIN, mouse_pos.x(), height() - SCROLLBAR_SIZE );
QPoint tt_pos = QCursor::pos();
tt_pos.ry() -= 51;
tt_pos.rx() += 26;
float scaledLevel = m_clip->firstObject()->scaledValue( level );
// Limit the scaled-level tooltip to the grid
if( mouse_pos.x() >= 0 &&
mouse_pos.x() <= width() - SCROLLBAR_SIZE &&
mouse_pos.y() >= 0 &&
mouse_pos.y() <= height() - SCROLLBAR_SIZE )
{
QToolTip::showText( tt_pos, QString::number( scaledLevel ), this );
}
}
inline void AutomationEditor::drawAutomationPoint(QPainter & p, timeMap::iterator it)
{
int x = xCoordOfTick(POS(it));
// Below (m_ppb * AutomationClip::quantization() / 576) is used because:
// 1 bar equals to 192/quantization() notes. Hence, to calculate the number of pixels
// per note we would have (m_ppb * 1 bar / (192/quantization()) notes per bar), or
// (m_ppb * quantization / 192). If we want 1/3 of the number of pixels per note we
// get (m_ppb * quantization() / 192*3) or (m_ppb * quantization() / 576)
const int outerRadius = qBound(3, (m_ppb * AutomationClip::quantization()) / 576, 5);
// Draw a circle for the outValue
int y = yCoordOfLevel(OUTVAL(it));
p.setPen(QPen(m_nodeOutValueColor.lighter(200)));
p.setBrush(QBrush(m_nodeOutValueColor));
p.drawEllipse(x - outerRadius, y - outerRadius, outerRadius * 2, outerRadius * 2);
// Draw a circle for the inValue
y = yCoordOfLevel(INVAL(it));
p.setPen(QPen(m_nodeInValueColor.lighter(200)));
p.setBrush(QBrush(m_nodeInValueColor));
p.drawEllipse(x - outerRadius, y - outerRadius, outerRadius * 2, outerRadius * 2);
}
inline void AutomationEditor::drawAutomationTangents(QPainter& p, timeMap::iterator it)
{
int x = xCoordOfTick(POS(it));
// The tangent value correlates the variation in the node value related to the increase
// in ticks. So to have a proportionate drawing of the tangent line, we need to find the
// relation between the number of pixels per tick and the number of pixels per value level.
float viewportHeight = (height() - SCROLLBAR_SIZE - 1) - TOP_MARGIN;
float pixelsPerTick = m_ppb / TimePos::ticksPerBar();
// std::abs just in case the topLevel is smaller than the bottomLevel for some reason
float pixelsPerLevel = std::abs(viewportHeight / (m_topLevel - m_bottomLevel));
float proportion = pixelsPerLevel / pixelsPerTick;
p.setPen(QPen(m_nodeTangentLineColor));
p.setBrush(QBrush(m_nodeTangentLineColor));
int y = yCoordOfLevel(INVAL(it));
int tx = x - 20;
int ty = y + 20 * INTAN(it) * proportion;
p.drawLine(x, y, tx, ty);
p.setBrush(QBrush(m_nodeTangentLineColor.darker(200)));
p.drawEllipse(tx - 3, ty - 3, 6, 6);
p.setBrush(QBrush(m_nodeTangentLineColor));
y = yCoordOfLevel(OUTVAL(it));
tx = x + 20;
ty = y - 20 * OUTTAN(it) * proportion;
p.drawLine(x, y, tx, ty);
p.setBrush(QBrush(m_nodeTangentLineColor.darker(200)));
p.drawEllipse(tx - 3, ty - 3, 6, 6);
}
void AutomationEditor::setGhostMidiClip(MidiClip* newMidiClip)
{
// Expects a pointer to a MIDI clip or nullptr.
m_ghostNotes = newMidiClip;
m_renderSample = false;
}
void AutomationEditor::setGhostSample(SampleClip* newGhostSample)
{
// Expects a pointer to a Sample buffer or nullptr.
m_ghostSample = newGhostSample;
m_renderSample = true;
}
void AutomationEditor::paintEvent(QPaintEvent * pe )
{
QStyleOption opt;
opt.initFrom( this );
QPainter p( this );
style()->drawPrimitive( QStyle::PE_Widget, &opt, &p, this );
// get foreground color
QColor fgColor = p.pen().brush().color();
// get background color and fill background
QBrush bgColor = p.background();
p.fillRect( 0, 0, width(), height(), bgColor );
p.setFont(adjustedToPixelSize(p.font(), DEFAULT_FONT_SIZE));
int grid_height = height() - TOP_MARGIN - SCROLLBAR_SIZE;
// start drawing at the bottom
int grid_bottom = height() - SCROLLBAR_SIZE - 1;
p.fillRect(0, TOP_MARGIN, VALUES_WIDTH, height() - TOP_MARGIN, m_scaleColor);
// print value numbers
int font_height = p.fontMetrics().height();
auto text_flags = (Qt::Alignment)(Qt::AlignRight | Qt::AlignVCenter);
if( validClip() )
{
if( m_y_auto )
{
auto y = std::array{grid_bottom, TOP_MARGIN + font_height / 2};
auto level = std::array{m_minLevel, m_maxLevel};
for( int i = 0; i < 2; ++i )
{
const QString & label = m_clip->firstObject()
->displayValue( level[i] );
p.setPen( QApplication::palette().color( QPalette::Active,
QPalette::Shadow ) );
p.drawText( 1, y[i] - font_height + 1,
VALUES_WIDTH - 10, 2 * font_height,
text_flags, label );
p.setPen( fgColor );
p.drawText( 0, y[i] - font_height,
VALUES_WIDTH - 10, 2 * font_height,
text_flags, label );
}
}
else
{
int level = (int) m_bottomLevel;
int printable = qMax( 1, 5 * DEFAULT_Y_DELTA
/ m_y_delta );
int module = level % printable;
if( module )
{
int inv_module = ( printable - module )
% printable;
level += inv_module;
}
for( ; level <= m_topLevel; level += printable )
{
const QString & label = m_clip->firstObject()
->displayValue( level );
int y = yCoordOfLevel(level);
p.setPen( QApplication::palette().color( QPalette::Active,
QPalette::Shadow ) );
p.drawText( 1, y - font_height + 1,
VALUES_WIDTH - 10, 2 * font_height,
text_flags, label );
p.setPen( fgColor );
p.drawText( 0, y - font_height,
VALUES_WIDTH - 10, 2 * font_height,
text_flags, label );
}
}
}
// set clipping area, because we are not allowed to paint over
// keyboard...
p.setClipRect( VALUES_WIDTH, TOP_MARGIN, width() - VALUES_WIDTH,
grid_height );
// draw vertical raster
if( m_clip )
{
int q;
int x_line_end = (int)( m_y_auto || m_topLevel < m_maxLevel ?
TOP_MARGIN :
grid_bottom - ( m_topLevel - m_bottomLevel ) * m_y_delta );
if( m_zoomingXModel.value() > 3 )
{
// If we're over 100% zoom, we allow all quantization level grids
q = AutomationClip::quantization();
}
else if( AutomationClip::quantization() % 3 != 0 )
{
// If we're under 100% zoom, we allow quantization grid up to 1/24 for triplets
// to ensure a dense doesn't fill out the background
q = AutomationClip::quantization() < 8 ? 8 : AutomationClip::quantization();
}
else {
// If we're under 100% zoom, we allow quantization grid up to 1/32 for normal notes
q = AutomationClip::quantization() < 6 ? 6 : AutomationClip::quantization();
}
// 3 independent loops, because quantization might not divide evenly into
// exotic denominators (e.g. 7/11 time), which are allowed ATM.
// First quantization grid...
for (int tick = m_currentPosition - m_currentPosition % q, x = xCoordOfTick(tick); x <= width();
tick += q, x = xCoordOfTick(tick))
{
p.setPen(m_lineColor);
p.drawLine( x, grid_bottom, x, x_line_end );
}
/// \todo move this horizontal line drawing code into the same loop as the value ticks?
if( m_y_auto )
{
QPen pen(m_beatLineColor);
pen.setStyle( Qt::DotLine );
p.setPen( pen );
float y_delta = ( grid_bottom - TOP_MARGIN ) / 8.0f;
for( int i = 1; i < 8; ++i )
{
int y = (int)( grid_bottom - i * y_delta );
p.drawLine( VALUES_WIDTH, y, width(), y );
}
}
else
{
for( int level = (int)m_bottomLevel; level <= m_topLevel; level++)
{
float y = yCoordOfLevel(static_cast<float>(level));
p.setPen(level % 10 == 0 ? m_beatLineColor : m_lineColor);
// draw level line
p.drawLine( VALUES_WIDTH, (int) y, width(), (int) y );
}
}
// alternating shades for better contrast
float timeSignature = static_cast<float>( Engine::getSong()->getTimeSigModel().getNumerator() )
/ static_cast<float>( Engine::getSong()->getTimeSigModel().getDenominator() );
float zoomFactor = m_zoomXLevels[m_zoomingXModel.value()];
//the bars which disappears at the left side by scrolling
int leftBars = m_currentPosition * zoomFactor / TimePos::ticksPerBar();
//iterates the visible bars and draw the shading on uneven bars
for( int x = VALUES_WIDTH, barCount = leftBars; x < width() + m_currentPosition * zoomFactor / timeSignature; x += m_ppb, ++barCount )
{
if( ( barCount + leftBars ) % 2 != 0 )
{
p.fillRect(
x - m_currentPosition * zoomFactor / timeSignature,
TOP_MARGIN,
m_ppb,
height() - (SCROLLBAR_SIZE + TOP_MARGIN),
m_backgroundShade
);
}
}
// Draw the beat grid
int ticksPerBeat = DefaultTicksPerBar /
Engine::getSong()->getTimeSigModel().getDenominator();
for (int tick = m_currentPosition - m_currentPosition % ticksPerBeat, x = xCoordOfTick(tick); x <= width();
tick += ticksPerBeat, x = xCoordOfTick(tick))
{
p.setPen(m_beatLineColor);
p.drawLine( x, grid_bottom, x, x_line_end );
}
// draw ghost sample
if (m_ghostSample != nullptr && m_ghostSample->sample().sampleSize() > 1 && m_renderSample)
{
int sampleFrames = m_ghostSample->sample().sampleSize();
int length = static_cast<float>(sampleFrames) / Engine::framesPerTick();
int editorHeight = grid_bottom - TOP_MARGIN;
int startPos = xCoordOfTick(0);
int sampleWidth = xCoordOfTick(length) - startPos;
int sampleHeight = std::min(editorHeight - SAMPLE_MARGIN, MAX_SAMPLE_HEIGHT);
int yOffset = (editorHeight - sampleHeight) / 2.0f + TOP_MARGIN;
p.setPen(m_ghostSampleColor);
const auto& sample = m_ghostSample->sample();
const auto waveform = SampleWaveform::Parameters{
sample.data(), sample.sampleSize(), sample.amplification(), sample.reversed()};
const auto rect = QRect(startPos, yOffset, sampleWidth, sampleHeight);
SampleWaveform::visualize(waveform, p, rect);
}
// draw ghost notes
if (m_ghostNotes != nullptr && !m_renderSample)
{
const NoteVector& notes = m_ghostNotes->notes();
int minKey = 128;
int maxKey = 0;
int detuningOffset = 0;
const Note* detuningNote = nullptr;
for (const Note* note : notes)
{
int noteKey = note->key();
if (note->detuning()->automationClip() == m_clip) {
detuningOffset = note->pos();
detuningNote = note;
}
maxKey = std::max(maxKey, noteKey);
minKey = std::min(minKey, noteKey);
}
for (const Note* note : notes)
{
int lenTicks = note->length();
int notePos = note->pos();
// offset note if detuning
if (notePos+lenTicks < detuningOffset) { continue; }
notePos -= detuningOffset;
// remove/change after #5902
if (lenTicks == 0) { continue; }
else if (lenTicks < 0) { lenTicks = 4; }
int note_width = lenTicks * m_ppb / TimePos::ticksPerBar();
int keyRange = maxKey - minKey;
if (keyRange < MIN_NOTE_RANGE)
{
int padding = (MIN_NOTE_RANGE - keyRange) / 2.0f;
maxKey += padding;
minKey -= padding;
keyRange = MIN_NOTE_RANGE;
}
float absNoteHeight = static_cast<float>(note->key() - minKey) / (maxKey - minKey);
int graphHeight = grid_bottom - NOTE_HEIGHT - NOTE_MARGIN - TOP_MARGIN;
const int y = (graphHeight - graphHeight * absNoteHeight) + NOTE_HEIGHT / 2.0f + TOP_MARGIN;
const int x = xCoordOfTick(notePos);
if (note == detuningNote) {
p.fillRect(x, y, note_width, NOTE_HEIGHT, m_detuningNoteColor);
} else {
p.fillRect(x, y, note_width, NOTE_HEIGHT, m_ghostNoteColor);
}
}
}
// and finally bars
for (int tick = m_currentPosition - m_currentPosition % TimePos::ticksPerBar(), x = xCoordOfTick(tick);
x <= width(); tick += TimePos::ticksPerBar(), x = xCoordOfTick(tick))
{
p.setPen(m_barLineColor);
p.drawLine( x, grid_bottom, x, x_line_end );
}
}
// following code draws all visible values
if( validClip() )
{
//NEEDS Change in CSS
//int len_ticks = 4;
timeMap & time_map = m_clip->getTimeMap();
//Don't bother doing/rendering anything if there is no automation points
if( time_map.size() > 0 )
{
timeMap::iterator it = time_map.begin();
while( it+1 != time_map.end() )
{
// skip this section if it occurs completely before the
// visible area
int next_x = xCoordOfTick(POS(it+1));
if( next_x < 0 )
{
++it;
continue;
}
int x = xCoordOfTick(POS(it));
if( x > width() )
{
break;
}
float *values = m_clip->valuesAfter(POS(it));
// We are creating a path to draw a polygon representing the values between two
// nodes. When we have two nodes with discrete progression, we will basically have
// a rectangle with the outValue of the first node (that's why nextValue will match
// the outValue of the current node). When we have nodes with linear or cubic progression
// the value of the end of the shape between the two nodes will be the inValue of
// the next node.
float nextValue = m_clip->progressionType() == AutomationClip::ProgressionType::Discrete
? OUTVAL(it)
: INVAL(it + 1);
p.setRenderHints( QPainter::Antialiasing, true );
QPainterPath path;
path.moveTo(QPointF(xCoordOfTick(POS(it)), yCoordOfLevel(0)));
for (int i = 0; i < POS(it + 1) - POS(it); i++)
{
path.lineTo(QPointF(xCoordOfTick(POS(it) + i), yCoordOfLevel(values[i])));
}
path.lineTo(QPointF(xCoordOfTick(POS(it + 1)), yCoordOfLevel(nextValue)));
path.lineTo(QPointF(xCoordOfTick(POS(it + 1)), yCoordOfLevel(0)));
path.lineTo(QPointF(xCoordOfTick(POS(it)), yCoordOfLevel(0)));
p.fillPath(path, m_graphColor);
p.setRenderHints( QPainter::Antialiasing, false );
delete [] values;
// Draw circle
drawAutomationPoint(p, it);
// Draw tangents if necessary (only for manually edited tangents)
if (m_clip->canEditTangents() && LOCKEDTAN(it))
{
drawAutomationTangents(p, it);
}
++it;
}
for (
int i = POS(it), x = xCoordOfTick(i);
x <= width();
i++, x = xCoordOfTick(i)
)
{
// Draws the rectangle representing the value after the last node (for
// that reason we use outValue).
drawLevelTick(p, i, OUTVAL(it));
}
// Draw circle(the last one)
drawAutomationPoint(p, it);
// Draw tangents if necessary (only for manually edited tangents)
if (m_clip->canEditTangents() && LOCKEDTAN(it))
{
drawAutomationTangents(p, it);
}
}
}
else
{
QFont f = font();
f.setBold( true );
p.setFont(f);
p.setPen( QApplication::palette().color( QPalette::Active,
QPalette::BrightText ) );
p.drawText( VALUES_WIDTH + 20, TOP_MARGIN + 40,
width() - VALUES_WIDTH - 20 - SCROLLBAR_SIZE,
grid_height - 40, Qt::TextWordWrap,
tr( "Please open an automation clip by "
"double-clicking on it!" ) );
}
// TODO: Get this out of paint event
int l = validClip() ? (int) m_clip->length() : 0;
// reset scroll-range
if( m_leftRightScroll->maximum() != l )
{
m_leftRightScroll->setRange( 0, l );
m_leftRightScroll->setPageStep( l );
}
if(validClip() && GuiApplication::instance()->automationEditor()->m_editor->hasFocus())
{
drawCross( p );
}
const QPixmap * cursor = nullptr;
// draw current edit-mode-icon below the cursor
switch( m_editMode )
{
case EditMode::Draw:
{
if (m_action == Action::EraseValues) { cursor = &m_toolErase; }
else if (m_action == Action::MoveValue) { cursor = &m_toolMove; }
else { cursor = &m_toolDraw; }
break;
}
case EditMode::Erase:
{
cursor = &m_toolErase;
break;
}
case EditMode::DrawOutValues:
{
if (m_action == Action::ResetOutValues) { cursor = &m_toolErase; }
else if (m_action == Action::MoveOutValue) { cursor = &m_toolMove; }
else { cursor = &m_toolDrawOut; }
break;
}
case EditMode::EditTangents:
{
cursor = m_action == Action::MoveTangent ? &m_toolMove : &m_toolEditTangents;
break;
}
}
QPoint mousePosition = mapFromGlobal( QCursor::pos() );
if (cursor != nullptr && mousePosition.y() > TOP_MARGIN + SCROLLBAR_SIZE)
{
p.drawPixmap( mousePosition + QPoint( 8, 8 ), *cursor );
}
}
int AutomationEditor::xCoordOfTick(int tick )
{
return VALUES_WIDTH + ( ( tick - m_currentPosition )
* m_ppb / TimePos::ticksPerBar() );
}
float AutomationEditor::yCoordOfLevel(float level )
{
int grid_bottom = height() - SCROLLBAR_SIZE - 1;
if( m_y_auto )
{
return ( grid_bottom - ( grid_bottom - TOP_MARGIN ) * ( level - m_minLevel ) / ( m_maxLevel - m_minLevel ) );
}
else
{
return ( grid_bottom - ( level - m_bottomLevel ) * m_y_delta );
}
}
void AutomationEditor::drawLevelTick(QPainter & p, int tick, float value)
{
int grid_bottom = height() - SCROLLBAR_SIZE - 1;
const int x = xCoordOfTick( tick );
int rect_width = xCoordOfTick( tick+1 ) - x;
// is the level in visible area?
if( ( value >= m_bottomLevel && value <= m_topLevel )
|| ( value > m_topLevel && m_topLevel >= 0 )
|| ( value < m_bottomLevel && m_bottomLevel <= 0 ) )
{
const int y_start = yCoordOfLevel(value);
const int y_end = grid_bottom + (grid_bottom - TOP_MARGIN) * m_minLevel / (m_maxLevel - m_minLevel);
const int rect_height = m_y_auto ? y_end - y_start : value * m_y_delta;
QBrush currentColor = m_graphColor;
p.fillRect( x, y_start, rect_width, rect_height, currentColor );
}
#ifdef LMMS_DEBUG
else
{
printf("not in range\n");
}
#endif
}
// Center the vertical scroll position on the first object's inValue
void AutomationEditor::centerTopBottomScroll()
{
// default to the m_scrollLevel position
int pos = static_cast<int>(m_scrollLevel);
// If a clip exists...
if (m_clip)
{
// get time map of current clip
timeMap & time_map = m_clip->getTimeMap();
// If time_map is not empty...
if (!time_map.empty())
{
// set the position to the inverted value ((max + min) - value)
// If we set just (max - value), we're off by m_clip's minimum
pos = m_clip->getMax() + m_clip->getMin() - static_cast<int>(INVAL(time_map.begin()));
}
}
m_topBottomScroll->setValue(pos);
}
// responsible for moving/resizing scrollbars after window-resizing
void AutomationEditor::resizeEvent(QResizeEvent * re)
{
m_leftRightScroll->setGeometry( VALUES_WIDTH, height() - SCROLLBAR_SIZE,
width() - VALUES_WIDTH,
SCROLLBAR_SIZE );
int grid_height = height() - TOP_MARGIN - SCROLLBAR_SIZE;
m_topBottomScroll->setGeometry( width() - SCROLLBAR_SIZE, TOP_MARGIN,
SCROLLBAR_SIZE, grid_height );
int half_grid = grid_height / 2;
int total_pixels = (int)( ( m_maxLevel - m_minLevel ) * m_y_delta + 1 );
if( !m_y_auto && grid_height < total_pixels )
{
int min_scroll = (int)( m_minLevel + floorf( half_grid
/ (float)m_y_delta ) );
int max_scroll = (int)( m_maxLevel - (int)floorf( ( grid_height
- half_grid ) / (float)m_y_delta ) );
m_topBottomScroll->setRange( min_scroll, max_scroll );
}
else
{
m_topBottomScroll->setRange( (int) m_scrollLevel,
(int) m_scrollLevel );
}
centerTopBottomScroll();
m_timeLine->setFixedWidth(width());
updateTopBottomLevels();
update();
}
void AutomationEditor::adjustLeftRightScoll(int value)
{
m_leftRightScroll->setValue(m_leftRightScroll->value() -
value * 0.3f / m_zoomXLevels[m_zoomingXModel.value()]);
}
// TODO: Move this method up so it's closer to the other mouse events
void AutomationEditor::wheelEvent(QWheelEvent * we )
{
we->accept();
if( we->modifiers() & Qt::ControlModifier && we->modifiers() & Qt::ShiftModifier )
{
int y = m_zoomingYModel.value();
if(we->angleDelta().y() > 0)
{
y++;
}
else if(we->angleDelta().y() < 0)
{
y--;
}
y = qBound( 0, y, m_zoomingYModel.size() - 1 );
m_zoomingYModel.setValue( y );
}
else if( we->modifiers() & Qt::ControlModifier && we->modifiers() & Qt::AltModifier )
{
int q = m_quantizeModel.value();
if((we->angleDelta().x() + we->angleDelta().y()) > 0) // alt + scroll becomes horizontal scroll on KDE
{
q--;
}
else if((we->angleDelta().x() + we->angleDelta().y()) < 0) // alt + scroll becomes horizontal scroll on KDE
{
q++;
}
q = qBound( 0, q, m_quantizeModel.size() - 1 );
m_quantizeModel.setValue( q );
update();
}
else if( we->modifiers() & Qt::ControlModifier )
{
int x = m_zoomingXModel.value();
if(we->angleDelta().y() > 0)
{
x++;
}
else if(we->angleDelta().y() < 0)
{
x--;
}
x = qBound( 0, x, m_zoomingXModel.size() - 1 );
int mouseX = (position( we ).x() - VALUES_WIDTH)* TimePos::ticksPerBar();
// ticks based on the mouse x-position where the scroll wheel was used
int ticks = mouseX / m_ppb;
// what would be the ticks in the new zoom level on the very same mouse x
int newTicks = mouseX / (DEFAULT_PPB * m_zoomXLevels[x]);
// scroll so the tick "selected" by the mouse x doesn't move on the screen
m_leftRightScroll->setValue(m_leftRightScroll->value() + ticks - newTicks);
m_zoomingXModel.setValue( x );
}
// FIXME: Reconsider if determining orientation is necessary in Qt6.
else if(abs(we->angleDelta().x()) > abs(we->angleDelta().y())) // scrolling is horizontal
{
adjustLeftRightScoll(we->angleDelta().x());
}
else if(we->modifiers() & Qt::ShiftModifier)
{
adjustLeftRightScoll(we->angleDelta().y());
}
else
{
m_topBottomScroll->setValue(m_topBottomScroll->value() -
(we->angleDelta().x() + we->angleDelta().y()) / 30);
}
}
float AutomationEditor::getLevel(int y )
{
int level_line_y = height() - SCROLLBAR_SIZE - 1;
// pressed level
float level = std::roundf( ( m_bottomLevel + ( m_y_auto ?
( m_maxLevel - m_minLevel ) * ( level_line_y - y )
/ (float)( level_line_y - ( TOP_MARGIN + 2 ) ) :
( level_line_y - y ) / (float)m_y_delta ) ) / m_step ) * m_step;
// some range-checking-stuff
level = qBound(std::roundf(m_bottomLevel), level, std::roundf(m_topLevel));
return level;
}
inline bool AutomationEditor::inPatternEditor()
{
return (validClip() && m_clip->getTrack()->trackContainer() == Engine::patternStore());
}
void AutomationEditor::play()
{
if( !validClip() )
{
return;
}
if( !m_clip->getTrack() )
{
if( Engine::getSong()->playMode() != Song::PlayMode::MidiClip )
{
Engine::getSong()->stop();
Engine::getSong()->playMidiClip( getGUI()->pianoRoll()->currentMidiClip() );
}
else if( Engine::getSong()->isStopped() == false )
{
Engine::getSong()->togglePause();
}
else
{
Engine::getSong()->playMidiClip( getGUI()->pianoRoll()->currentMidiClip() );
}
}
else if (inPatternEditor())
{
Engine::patternStore()->play();
}
else
{
if( Engine::getSong()->isStopped() == true )
{
Engine::getSong()->playSong();
}
else
{
Engine::getSong()->togglePause();
}
}
}
void AutomationEditor::stop()
{
if( !validClip() )
{
return;
}
if (m_clip->getTrack() && inPatternEditor())
{
Engine::patternStore()->stop();
}
else
{
Engine::getSong()->stop();
}
m_scrollBack = true;
}
void AutomationEditor::horScrolled(int new_pos )
{
m_currentPosition = new_pos;
emit positionChanged( m_currentPosition );
update();
}
void AutomationEditor::verScrolled(int new_pos )
{
m_scrollLevel = new_pos;
updateTopBottomLevels();
update();
}
void AutomationEditor::setEditMode(AutomationEditor::EditMode mode)
{
if (m_editMode == mode)
return;
m_editMode = mode;
update();
}
void AutomationEditor::setEditMode(int mode)
{
setEditMode((AutomationEditor::EditMode) mode);
}
void AutomationEditor::setProgressionType(AutomationClip::ProgressionType type)
{
if (validClip())
{
m_clip->addJournalCheckPoint();
m_clip->setProgressionType(type);
Engine::getSong()->setModified();
update();
}
}
void AutomationEditor::setProgressionType(int type)
{
setProgressionType((AutomationClip::ProgressionType) type);
}
void AutomationEditor::setTension()
{
if ( m_clip )
{
m_clip->setTension( QString::number( m_tensionModel->value() ) );
update();
}
}
void AutomationEditor::updatePosition(const TimePos & t )
{
if( ( Engine::getSong()->isPlaying() &&
Engine::getSong()->playMode() ==
Song::PlayMode::AutomationClip ) ||
m_scrollBack == true )
{
const int w = width() - VALUES_WIDTH;
if( t > m_currentPosition + w * TimePos::ticksPerBar() / m_ppb )
{
m_leftRightScroll->setValue( t.getBar() *
TimePos::ticksPerBar() );
}
else if( t < m_currentPosition )
{
TimePos t_ = qMax( t - w * TimePos::ticksPerBar() *
TimePos::ticksPerBar() / m_ppb, 0 );
m_leftRightScroll->setValue( t_.getBar() *
TimePos::ticksPerBar() );
}
m_scrollBack = false;
}
}
void AutomationEditor::zoomingXChanged()
{
m_ppb = m_zoomXLevels[m_zoomingXModel.value()] * DEFAULT_PPB;
assert( m_ppb > 0 );
m_timeLine->setPixelsPerBar( m_ppb );
update();
}
void AutomationEditor::zoomingYChanged()
{
const QString & zfac = m_zoomingYModel.currentText();
m_y_auto = zfac == "Auto";
if( !m_y_auto )
{
m_y_delta = zfac.left( zfac.length() - 1 ).toInt()
* DEFAULT_Y_DELTA / 100;
}
#ifdef LMMS_DEBUG
assert( m_y_delta > 0 );
#endif
resizeEvent(nullptr);
}
void AutomationEditor::setQuantization()
{
AutomationClip::setQuantization(DefaultTicksPerBar / Quantizations[m_quantizeModel.value()]);
update();
}
void AutomationEditor::updateTopBottomLevels()
{
if( m_y_auto )
{
m_bottomLevel = m_minLevel;
m_topLevel = m_maxLevel;
return;
}
int total_pixels = (int)( ( m_maxLevel - m_minLevel ) * m_y_delta + 1 );
int grid_height = height() - TOP_MARGIN - SCROLLBAR_SIZE;
int half_grid = grid_height / 2;
if( total_pixels > grid_height )
{
int centralLevel = (int)( m_minLevel + m_maxLevel - m_scrollLevel );
m_bottomLevel = centralLevel - ( half_grid
/ (float)m_y_delta );
if( m_bottomLevel < m_minLevel )
{
m_bottomLevel = m_minLevel;
m_topLevel = m_minLevel + (int)floorf( grid_height
/ (float)m_y_delta );
}
else
{
m_topLevel = m_bottomLevel + (int)floorf( grid_height
/ (float)m_y_delta );
if( m_topLevel > m_maxLevel )
{
m_topLevel = m_maxLevel;
m_bottomLevel = m_maxLevel - (int)floorf(
grid_height / (float)m_y_delta );
}
}
}
else
{
m_bottomLevel = m_minLevel;
m_topLevel = m_maxLevel;
}
}
/**
* @brief Given a mouse coordinate, returns a timeMap::iterator that points to
* the first node inside a square of side "r" pixels from those
* coordinates. In simpler terms, returns the automation node on those
* coordinates.
* @param Int X coordinate
* @param Int Y coordinate
* @param Boolean. True to check if the outValue of the node was clicked instead
* (defaults to false)
* @param Int R distance in pixels
* @return timeMap::iterator with the clicked node, or timeMap.end() if none was clicked.
*/
AutomationEditor::timeMap::iterator AutomationEditor::getNodeAt(int x, int y, bool outValue /* = false */, int r /* = 5 */)
{
// Remove the VALUES_WIDTH from the x position, so we have the actual viewport x
x -= VALUES_WIDTH;
// Convert the x position to the position in ticks
int posTicks = (x * TimePos::ticksPerBar() / m_ppb) + m_currentPosition;
// Get our clip timeMap and create a iterator so we can check the nodes
timeMap & tm = m_clip->getTimeMap();
timeMap::iterator it = tm.begin();
// ticksOffset is the number of ticks that match "r" pixels
int ticksOffset = TimePos::ticksPerBar() * r / m_ppb;
while (it != tm.end())
{
// The node we are checking is past the coordinates already, so the others will be too
if (posTicks < POS(it) - ticksOffset) { break; }
// If the x coordinate is within "r" pixels of the node's position
// POS(it) - ticksOffset <= posTicks <= POS(it) + ticksOffset
if (posTicks <= POS(it) + ticksOffset)
{
// The y position of the node
float valueY = yCoordOfLevel(
outValue
? OUTVAL(it)
: INVAL(it)
);
// If the y coordinate is within "r" pixels of the node's value
if (y >= (valueY - r) && y <= (valueY + r))
{
return it;
}
}
++it;
}
return tm.end();
}
AutomationEditor::timeMap::iterator AutomationEditor::getClosestNode(int x)
{
// Remove the VALUES_WIDTH from the x position, so we have the actual viewport x
x -= VALUES_WIDTH;
// Convert the x position to the position in ticks
int posTicks = (x * TimePos::ticksPerBar() / m_ppb) + m_currentPosition;
// Get our pattern timeMap and create a iterator so we can check the nodes
timeMap& tm = m_clip->getTimeMap();
if (tm.isEmpty()) { return tm.end(); }
// Get the node with an equal or higher position
auto it = tm.lowerBound(posTicks);
// If there are no nodes equal or higher than the position return
// the one before it
if (it == tm.end())
{
--it;
return it;
}
// If the node returned is the first, return it
else if (it == tm.begin())
{
return it;
}
// Else return the closest node
else
{
// Distance from node to the right
int distanceRight = std::abs(POS(it) - posTicks);
// Distance from node to the left
int distanceLeft = std::abs(POS(--it) - posTicks);
if (distanceLeft >= distanceRight)
{
++it;
}
return it;
}
}
AutomationEditorWindow::AutomationEditorWindow() :
Editor(),
m_editor(new AutomationEditor())
{
setCentralWidget(m_editor);
// Play/stop buttons
m_playAction->setToolTip(tr( "Play/pause current clip (Space)" ));
m_stopAction->setToolTip(tr("Stop playing of current clip (Space)"));
// Edit mode buttons
DropToolBar *editActionsToolBar = addDropToolBarToTop(tr("Edit actions"));
auto editModeGroup = new ActionGroup(this);
m_drawAction = editModeGroup->addAction(embed::getIconPixmap("edit_draw"), tr("Draw mode (Shift+D)"));
m_drawAction->setShortcut(Qt::SHIFT | Qt::Key_D);
m_drawAction->setChecked(true);
m_eraseAction = editModeGroup->addAction(embed::getIconPixmap("edit_erase"), tr("Erase mode (Shift+E)"));
m_eraseAction->setShortcut(Qt::SHIFT | Qt::Key_E);
m_drawOutAction = editModeGroup->addAction(embed::getIconPixmap("edit_draw_outvalue"), tr("Draw outValues mode (Shift+C)"));
m_drawOutAction->setShortcut(Qt::SHIFT | Qt::Key_C);
m_editTanAction = editModeGroup->addAction(embed::getIconPixmap("edit_tangent"), tr("Edit tangents mode (Shift+T)"));
m_editTanAction->setShortcut(Qt::SHIFT | Qt::Key_T);
m_editTanAction->setEnabled(false);
m_flipYAction = new QAction(embed::getIconPixmap("flip_y"), tr("Flip vertically"), this);
m_flipXAction = new QAction(embed::getIconPixmap("flip_x"), tr("Flip horizontally"), this);
connect(editModeGroup, SIGNAL(triggered(int)), m_editor, SLOT(setEditMode(int)));
editActionsToolBar->addAction(m_drawAction);
editActionsToolBar->addAction(m_eraseAction);
editActionsToolBar->addAction(m_drawOutAction);
editActionsToolBar->addAction(m_editTanAction);
editActionsToolBar->addAction(m_flipXAction);
editActionsToolBar->addAction(m_flipYAction);
// Interpolation actions
DropToolBar *interpolationActionsToolBar = addDropToolBarToTop(tr("Interpolation controls"));
auto progression_type_group = new ActionGroup(this);
m_discreteAction = progression_type_group->addAction(
embed::getIconPixmap("progression_discrete"), tr("Discrete progression"));
m_discreteAction->setChecked(true);
m_linearAction = progression_type_group->addAction(
embed::getIconPixmap("progression_linear"), tr("Linear progression"));
m_cubicHermiteAction = progression_type_group->addAction(
embed::getIconPixmap("progression_cubic_hermite"), tr( "Cubic Hermite progression"));
connect(progression_type_group, SIGNAL(triggered(int)), this, SLOT(setProgressionType(int)));
// setup tension-stuff
m_tensionKnob = new Knob( KnobType::Small17, this, "Tension" );
m_tensionKnob->setModel(m_editor->m_tensionModel);
m_tensionKnob->setToolTip(tr("Tension value for spline"));
connect(m_cubicHermiteAction, SIGNAL(toggled(bool)), m_tensionKnob, SLOT(setEnabled(bool)));
interpolationActionsToolBar->addSeparator();
interpolationActionsToolBar->addAction(m_discreteAction);
interpolationActionsToolBar->addAction(m_linearAction);
interpolationActionsToolBar->addAction(m_cubicHermiteAction);
interpolationActionsToolBar->addSeparator();
interpolationActionsToolBar->addWidget( new QLabel( tr("Tension: "), interpolationActionsToolBar ));
interpolationActionsToolBar->addWidget( m_tensionKnob );
addToolBarBreak();
// Zoom controls
DropToolBar *zoomToolBar = addDropToolBarToTop(tr("Zoom controls"));
auto zoom_x_label = new QLabel(zoomToolBar);
zoom_x_label->setPixmap( embed::getIconPixmap( "zoom_x" ) );
m_zoomingXComboBox = new ComboBox( zoomToolBar );
m_zoomingXComboBox->setFixedSize( 80, ComboBox::DEFAULT_HEIGHT );
m_zoomingXComboBox->setToolTip( tr( "Horizontal zooming" ) );
for( float const & zoomLevel : m_editor->m_zoomXLevels )
{
m_editor->m_zoomingXModel.addItem(QString("%1%").arg(zoomLevel * 100));
}
m_editor->m_zoomingXModel.setValue( m_editor->m_zoomingXModel.findText( "100%" ) );
m_zoomingXComboBox->setModel( &m_editor->m_zoomingXModel );
connect( &m_editor->m_zoomingXModel, SIGNAL(dataChanged()),
m_editor, SLOT(zoomingXChanged()));
auto zoom_y_label = new QLabel(zoomToolBar);
zoom_y_label->setPixmap( embed::getIconPixmap( "zoom_y" ) );
m_zoomingYComboBox = new ComboBox( zoomToolBar );
m_zoomingYComboBox->setFixedSize( 80, ComboBox::DEFAULT_HEIGHT );
m_zoomingYComboBox->setToolTip( tr( "Vertical zooming" ) );
m_editor->m_zoomingYModel.addItem( "Auto" );
for( int i = 0; i < 7; ++i )
{
m_editor->m_zoomingYModel.addItem( QString::number( 25 << i ) + "%" );
}
m_editor->m_zoomingYModel.setValue( m_editor->m_zoomingYModel.findText( "Auto" ) );
m_zoomingYComboBox->setModel( &m_editor->m_zoomingYModel );
connect( &m_editor->m_zoomingYModel, SIGNAL(dataChanged()),
m_editor, SLOT(zoomingYChanged()));
zoomToolBar->addWidget( zoom_x_label );
zoomToolBar->addWidget( m_zoomingXComboBox );
zoomToolBar->addSeparator();
zoomToolBar->addWidget( zoom_y_label );
zoomToolBar->addWidget( m_zoomingYComboBox );
// Quantization controls
DropToolBar *quantizationActionsToolBar = addDropToolBarToTop(tr("Quantization controls"));
auto quantize_lbl = new QLabel(m_toolBar);
quantize_lbl->setPixmap( embed::getIconPixmap( "quantize" ) );
m_quantizeComboBox = new ComboBox( m_toolBar );
m_quantizeComboBox->setFixedSize( 60, ComboBox::DEFAULT_HEIGHT );
m_quantizeComboBox->setToolTip( tr( "Quantization" ) );
m_quantizeComboBox->setModel( &m_editor->m_quantizeModel );
quantizationActionsToolBar->addWidget( quantize_lbl );
quantizationActionsToolBar->addWidget( m_quantizeComboBox );
m_resetGhostNotes = new QPushButton(m_toolBar);
m_resetGhostNotes->setIcon(embed::getIconPixmap("clear_ghost_note"));
m_resetGhostNotes->setToolTip(tr("Clear ghost notes"));
m_resetGhostNotes->setEnabled(true);
connect(m_resetGhostNotes, &QPushButton::pressed, m_editor, &AutomationEditor::resetGhostNotes);
quantizationActionsToolBar->addSeparator();
quantizationActionsToolBar->addWidget(m_resetGhostNotes);
// Setup our actual window
setFocusPolicy(Qt::StrongFocus);
setFocus();
setWindowIcon( embed::getIconPixmap( "automation" ) );
setAcceptDrops( true );
m_toolBar->setAcceptDrops( true );
}
void AutomationEditorWindow::setCurrentClip(AutomationClip* clip)
{
// Disconnect our old clip
if (currentClip() != nullptr)
{
m_editor->m_clip->disconnect(this);
m_flipXAction->disconnect();
m_flipYAction->disconnect();
}
m_editor->setCurrentClip(clip);
// Set our window's title
if (clip == nullptr)
{
setWindowTitle( tr( "Automation Editor - no clip" ) );
return;
}
setWindowTitle( tr( "Automation Editor - %1" ).arg( m_editor->m_clip->name() ) );
switch(m_editor->m_clip->progressionType())
{
case AutomationClip::ProgressionType::Discrete:
m_discreteAction->setChecked(true);
m_tensionKnob->setEnabled(false);
break;
case AutomationClip::ProgressionType::Linear:
m_linearAction->setChecked(true);
m_tensionKnob->setEnabled(false);
break;
case AutomationClip::ProgressionType::CubicHermite:
m_cubicHermiteAction->setChecked(true);
m_tensionKnob->setEnabled(true);
break;
}
// Connect new clip
if (clip)
{
connect(clip, SIGNAL(dataChanged()), this, SLOT(update()));
connect( clip, SIGNAL(dataChanged()), this, SLOT(updateWindowTitle()));
connect(clip, SIGNAL(destroyed()), this, SLOT(clearCurrentClip()));
connect(m_flipXAction, SIGNAL(triggered()), clip, SLOT(flipX()));
connect(m_flipYAction, SIGNAL(triggered()), clip, SLOT(flipY()));
}
updateEditTanButton();
emit currentClipChanged();
}
const AutomationClip* AutomationEditorWindow::currentClip()
{
return m_editor->currentClip();
}
void AutomationEditorWindow::dropEvent( QDropEvent *_de )
{
QString type = StringPairDrag::decodeKey( _de );
QString val = StringPairDrag::decodeValue( _de );
if( type == "automatable_model" )
{
auto mod = dynamic_cast<AutomatableModel*>(Engine::projectJournal()->journallingObject(val.toInt()));
if (mod != nullptr)
{
bool added = m_editor->m_clip->addObject( mod );
if ( !added )
{
TextFloat::displayMessage( mod->displayName(),
tr( "Model is already connected "
"to this clip." ),
embed::getIconPixmap( "automation" ),
2000 );
}
setCurrentClip( m_editor->m_clip );
}
}
update();
}
void AutomationEditorWindow::dragEnterEvent( QDragEnterEvent *_dee )
{
if (! m_editor->validClip() ) {
return;
}
StringPairDrag::processDragEnterEvent( _dee, "automatable_model" );
}
void AutomationEditorWindow::open(AutomationClip* clip)
{
setCurrentClip(clip);
parentWidget()->show();
show();
setFocus();
}
QSize AutomationEditorWindow::sizeHint() const
{
return {INITIAL_WIDTH, INITIAL_HEIGHT};
}
void AutomationEditorWindow::clearCurrentClip()
{
m_editor->m_clip = nullptr;
setCurrentClip(nullptr);
}
void AutomationEditorWindow::focusInEvent(QFocusEvent * event)
{
m_editor->setFocus( event->reason() );
}
void AutomationEditorWindow::play()
{
m_editor->play();
setPauseIcon(Engine::getSong()->isPlaying());
}
void AutomationEditorWindow::stop()
{
m_editor->stop();
}
void AutomationEditorWindow::updateWindowTitle()
{
if (m_editor->m_clip == nullptr)
{
setWindowTitle( tr( "Automation Editor - no clip" ) );
return;
}
setWindowTitle( tr( "Automation Editor - %1" ).arg( m_editor->m_clip->name() ) );
}
void AutomationEditorWindow::setProgressionType(int progType)
{
m_editor->setProgressionType(progType);
updateEditTanButton();
}
void AutomationEditorWindow::updateEditTanButton()
{
auto progType = currentClip()->progressionType();
m_editTanAction->setEnabled(AutomationClip::supportsTangentEditing(progType));
if (!m_editTanAction->isEnabled() && m_editTanAction->isChecked()) { m_drawAction->trigger(); }
}
} // namespace lmms::gui
| 61,638
|
C++
|
.cpp
| 1,883
| 29.244291
| 136
| 0.687357
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,994
|
Phaser.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Phaser.cc
|
/*
Phaser.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
One simple mono phaser, 6 all-pass lines, the usual controls.
Another unit in the same vein with the filter modulation controlled by
a Lorenz fractal.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Phaser.h"
#include "Descriptor.h"
template <sample_func_t F>
void
PhaserI::one_cycle (int frames)
{
sample_t * s = ports[0];
if (rate != *ports[1])
{
rate = getport(1);
lfo.set_f (max (.001, rate * (double) blocksize), fs, lfo.get_phase());
}
double depth = getport(2);
double spread = 1 + getport(3);
double fb = getport(4);
sample_t * dst = ports[5];
while (frames)
{
if (remain == 0) remain = 32;
int n = min (remain, frames);
double d = delay.bottom + delay.range * (1. - fabs (lfo.get()));
for (int j = 5; j >= 0; --j)
{
ap[j].set (d);
d *= spread;
}
for (int i = 0; i < n; ++i)
{
sample_t x = s[i];
sample_t y = x + y0 * fb + normal;
for (int j = 5; j >= 0; --j)
y = ap[j].process (y);
y0 = y;
F (dst, i, x + y * depth, adding_gain);
}
s += n;
dst += n;
frames -= n;
remain -= n;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
PhaserI::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"rate (Hz)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 10}
}, {
"depth",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 1}
}, {
"spread",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, M_PI}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, .999}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<PhaserI>::setup()
{
UniqueID = 1775;
Label = "PhaserI";
Properties = HARD_RT;
Name = CAPS "PhaserI - Mono phaser";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
PhaserII::one_cycle (int frames)
{
sample_t * s = ports[0];
lorenz.set_rate (getport(1) * .08);
double depth = getport(2);
double spread = 1 + getport(3);
double fb = getport(4);
sample_t * dst = ports[5];
while (frames)
{
if (remain == 0) remain = 32;
int n = min (remain, frames);
double d = delay.bottom + delay.range * (.3 * lorenz.get());
for (int j = 5; j >= 0; --j)
{
ap[j].set (d);
d *= spread;
}
for (int i = 0; i < n; ++i)
{
sample_t x = s[i];
sample_t y = x + y0 * fb + normal;
for (int j = 5; j >= 0; --j)
y = ap[j].process (y);
y0 = y;
F (dst, i, x + y * depth, adding_gain);
}
s += n;
dst += n;
frames -= n;
remain -= n;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
PhaserII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"rate",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"depth",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 1}
}, {
"spread",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, M_PI * .5}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, .999}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<PhaserII>::setup()
{
UniqueID = 2586;
Label = "PhaserII";
Properties = HARD_RT;
Name = CAPS "PhaserII - Mono phaser modulated by a Lorenz fractal";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
| 4,278
|
C++
|
.cc
| 184
| 20.592391
| 78
| 0.592069
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
19,995
|
interface.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/interface.cc
|
/*
interface.cc
Copyright 2004-11 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
LADSPA descriptor factory, host interface.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
/*
LADSPA ID ranges 1761 - 1800 and 2581 - 2660
(2541 - 2580 donated to artemio@kdemail.net)
*/
// #include <sys/time.h>
#include "basics.h"
#include "Cabinet.h"
#include "Chorus.h"
#include "Phaser.h"
#include "Sin.h"
#include "Lorenz.h"
#include "Roessler.h"
#include "Reverb.h"
#include "Compress.h"
#include "Click.h"
#include "Eq.h"
#include "Clip.h"
#include "White.h"
#include "SweepVF.h"
#include "VCO.h"
#include "Amp.h"
#include "HRTF.h"
#include "Pan.h"
#include "Scape.h"
#include "ToneStack.h"
#include "Descriptor.h"
#define N 39
static DescriptorStub * descriptors [N];
/*static inline void
seed()
{
static struct timeval tv;
gettimeofday (&tv, 0);
srand (tv.tv_sec ^ tv.tv_usec);
}*/
extern "C" {
void caps_so_init()
{
DescriptorStub ** d = descriptors;
*d++ = new Descriptor<Eq>();
*d++ = new Descriptor<Eq2x2>();
*d++ = new Descriptor<Compress>();
*d++ = new Descriptor<Pan>();
*d++ = new Descriptor<Narrower>();
*d++ = new Descriptor<PreampIII>();
*d++ = new Descriptor<PreampIV>();
*d++ = new Descriptor<ToneStack>();
*d++ = new Descriptor<ToneStackLT>();
*d++ = new Descriptor<AmpIII>();
*d++ = new Descriptor<AmpIV>();
*d++ = new Descriptor<AmpV>();
*d++ = new Descriptor<AmpVTS>();
*d++ = new Descriptor<CabinetI>();
*d++ = new Descriptor<CabinetII>();
*d++ = new Descriptor<Clip>();
*d++ = new Descriptor<ChorusI>();
*d++ = new Descriptor<StereoChorusI>();
*d++ = new Descriptor<ChorusII>();
*d++ = new Descriptor<StereoChorusII>();
*d++ = new Descriptor<PhaserI>();
*d++ = new Descriptor<PhaserII>();
*d++ = new Descriptor<SweepVFI>();
*d++ = new Descriptor<SweepVFII>();
*d++ = new Descriptor<AutoWah>();
*d++ = new Descriptor<Scape>();
*d++ = new Descriptor<VCOs>();
*d++ = new Descriptor<VCOd>();
*d++ = new Descriptor<CEO>();
*d++ = new Descriptor<Sin>();
*d++ = new Descriptor<White>();
*d++ = new Descriptor<Lorenz>();
*d++ = new Descriptor<Roessler>();
*d++ = new Descriptor<JVRev>();
*d++ = new Descriptor<Plate>();
*d++ = new Descriptor<Plate2x2>();
*d++ = new Descriptor<Click>();
*d++ = new Descriptor<Dirac>();
*d++ = new Descriptor<HRTF>();
/* make sure N is correct */
assert (d - descriptors == N);
//seed();
}
void caps_so_fini()
{
for (ulong i = 0; i < N; ++i)
delete descriptors[i];
}
/* /////////////////////////////////////////////////////////////////////// */
const LADSPA_Descriptor *
ladspa_descriptor (unsigned long i)
{
if (i < N)
return descriptors[i];
return 0;
}
struct CapsSoInit
{
CapsSoInit() { caps_so_init(); }
~CapsSoInit() { caps_so_fini(); }
};
static CapsSoInit capsSoInit;
}; /* extern "C" */
| 3,534
|
C++
|
.cc
| 122
| 26.983607
| 77
| 0.667159
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,996
|
HRTF.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/HRTF.cc
|
/*
HRTF.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
high-order IIR filtering modeled after HRTF impulse responses
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "HRTF.h"
#include "Descriptor.h"
#include "elev0.h"
/* //////////////////////////////////////////////////////////////////////// */
void
HRTF::init()
{
h = 0;
}
void
HRTF::set_pan (int p)
{
n = 31;
pan = p;
if (p >= 0)
{
left.a = elev0[p].left.a;
left.b = elev0[p].left.b;
right.a = elev0[p].right.a;
right.b = elev0[p].right.b;
}
else
{
p = -p;
left.a = elev0[p].right.a;
left.b = elev0[p].right.b;
right.a = elev0[p].left.a;
right.b = elev0[p].left.b;
}
memset (left.y, 0, sizeof (left.y));
memset (right.y, 0, sizeof (right.y));
}
template <sample_func_t F>
void
HRTF::one_cycle (int frames)
{
sample_t * s = ports[0];
int p = (int) getport(1);
if (p != pan) set_pan (p);
sample_t * dl = ports[2];
sample_t * dr = ports[3];
double l, r;
for (int i = 0; i < frames; ++i)
{
x[h] = l = r = s[i] + normal;
l *= left.a[0];
r *= right.a[0];
for (int j = 1, z = h - 1; j < n; --z, ++j)
{
z &= 31;
l += left.a[j] * x[z];
l += left.b[j] * left.y[z];
r += right.a[j] * x[z];
r += right.b[j] * right.y[z];
}
left.y[h] = l;
right.y[h] = r;
h = (h + 1) & 31;
F (dl, i, l, adding_gain);
F (dr, i, r, adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
HRTF::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"pan",
INPUT | CONTROL,
{BOUNDED | INTEGER | DEFAULT_0, -36, 36}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<HRTF>::setup()
{
UniqueID = 1787;
Label = "HRTF";
Properties = HARD_RT;
Name = CAPS "HRTF - Head-related transfer function at elevation 0";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 2,744
|
C++
|
.cc
| 117
| 21.034188
| 78
| 0.601544
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
19,997
|
Clip.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Clip.cc
|
/*
Clip.cc
Copyright 2003-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
simple oversampled hard clipper
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Clip.h"
#include "Descriptor.h"
void
Clip::init()
{
gain = 1;
threshold[0] = -.9;
threshold[1] = +.9;
/* going a bit lower than nominal with fc */
double f = .5 * M_PI / OVERSAMPLE;
/* construct the upsampler filter kernel */
DSP::sinc (f, up.c, FIR_SIZE);
DSP::kaiser<DSP::apply_window> (up.c, FIR_SIZE, 6.4);
/* copy upsampler filter kernel for downsampler, make sum */
double s = 0;
for (int i = 0; i < up.n; ++i)
down.c[i] = up.c[i],
s += up.c[i];
/* scale downsampler kernel for unity gain */
s = 1 / s;
for (int i = 0; i < down.n; ++i)
down.c[i] *= s;
/* scale upsampler kernel for unity gain */
s *= OVERSAMPLE;
for (int i = 0; i < up.n; ++i)
up.c[i] *= s;
}
inline sample_t
Clip::clip (sample_t a)
{
if (a < threshold[0])
return threshold[0];
if (a > threshold[1])
return threshold[1];
return a;
}
template <sample_func_t F>
void
Clip::one_cycle (int frames)
{
sample_t * s = ports[0];
double g = getport (1);
double gf;
if (g == gain_db)
gf = 1;
else
{
gain_db = g;
sample_t g = DSP::db2lin (gain_db);
gf = pow (g / gain, 1 / (double) frames);
}
sample_t * d = ports[2];
*ports[3] = OVERSAMPLE;
for (int i = 0; i < frames; ++i)
{
sample_t a = gain * s[i];
a = down.process (clip (up.upsample (a)));
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (clip (up.pad (o)));
F (d, i, a, adding_gain);
gain *= gf;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Clip::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain (dB)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, -72, 72}
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<Clip>::setup()
{
UniqueID = 1771;
Label = "Clip";
Properties = HARD_RT;
Name = CAPS "Clip - Hard clipper, 8x oversampled";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2003-7";
/* fill port info and vtable */
autogen();
}
| 2,896
|
C++
|
.cc
| 118
| 22.245763
| 78
| 0.641035
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
19,998
|
ToneControls.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/ToneControls.cc
|
/*
ToneControls.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
4-way Eq for amplifier emulation plugins
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include <stdio.h>
#include "Amp.h"
PreampBand
ToneControls::bands[] =
{
/* f, Q, g */
{ 80, 1.20, 1.61},
{ 300, 1.10, 1.10},
{1200, 1.14, 1.07},
{4800, .80, 1.06}
};
void
ToneControls::init (double fs)
{
for (int i = 0; i < 4; ++i)
eq.init_band (i, 2 * bands[i].center * M_PI / fs, bands[i].Q);
}
double
ToneControls::get_band_gain (int i, double g)
{
return bands[i].adjust * DSP::db2lin (g);
}
void
ToneControls::set_band_gain (int i, float g)
{
/* sorry, _ != . but hardly readable -- the difference is between local
* buffered value and actual Eq band gain */
eq_gain[i] = g;
eq.gain[i] = get_band_gain (i, g);
}
void
ToneControls::activate (sample_t ** ports)
{
for (int i = 0; i < 4; ++i)
set_band_gain (i, *ports[i]);
eq.reset();
}
| 1,681
|
C++
|
.cc
| 58
| 27.051724
| 72
| 0.707347
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
19,999
|
Scape.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Scape.cc
|
/*
Scape.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Scape.h"
#include "Descriptor.h"
void
Scape::activate()
{
time = 0;
fb = 0;
for (int i = 0; i < 4; ++i)
svf[i].reset(),
svf[i].set_out (SVF::Band),
hipass[i].set_f (250. / fs);
svf[3].set_out (SVF::Low),
delay.reset();
period = 0;
}
static double
dividers [] = {
1 /* 0 sentinel */,
1, 0.5, 0.66666666666666666667, 0.75
};
float
frandom2()
{
float f = frandom();
return f * f * f;
}
template <sample_func_t F>
void
Scape::one_cycle (int frames)
{
sample_t * s = ports[0];
// double one_over_n = 1 / (double) frames;
/* delay times */
double t1 = fs * 60. / getport(1);
int div = (int) getport(2);
double t2 = t1 * dividers[div];
fb = getport(3);
double dry = getport(4);
dry = dry * dry;
double blend = getport(5);
sample_t * dl = ports[6];
sample_t * dr = ports[7];
DSP::FPTruncateMode truncate;
while (frames)
{
/* flip 'renormal' addition constant */
normal = -normal;
/* retune filters */
if (period <= 1)
{
period = t2 * .5;
float f, q;
f = frandom2();
svf[0].set_f_Q (300 + 300 * f / fs, .3);
svf[3].set_f_Q (300 + 600 * 2 * f / fs, .6);
f = frandom2();
q = f;
svf[1].set_f_Q (400 + 2400 * f / fs, q);
q = 1 - f;
svf[2].set_f_Q (400 + 2400 * f / fs, q);
}
int n = min ((int) period, frames);
if (n < 1)
{
/* not reached */
#ifdef DEBUG
fprintf (stderr, "Scape: %d - %d/%d frames, t2 = %.3f?!?\n", (int) period, n, frames, t2);
#endif
return;
}
/* sample loop */
for (int i = 0; i < n; ++i)
{
sample_t x = s[i] + normal;
sample_t x1 = delay.get_at (t1);
sample_t x2 = delay.get_at (t2);
delay.put (x + fb * x1 + normal);
x = dry * x + .2 * svf[0].process (x) + .6 * svf[3].process(x);
x1 = svf[1].process (x1 - normal);
x2 = svf[2].process (x2 - normal);
x1 = hipass[1].process (x1);
x2 = hipass[2].process (x2);
sample_t x1l, x1r, x2l, x2r;
x1l = fabs (lfo[0].get());
x1r = 1 - x1l;
x2r = fabs (lfo[1].get());
x2l = 1 - x2r;
F (dl, i, x + blend * (x1 * x1l + x2 * x2l), adding_gain);
F (dr, i, x + blend * (x2 * x2r + x1 * x1r), adding_gain);
}
frames -= n;
period -= n;
s += n;
dl += n;
dr += n;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Scape::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"bpm",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 30, 240}
}, {
"divider",
INPUT | CONTROL,
{BOUNDED | INTEGER | DEFAULT_MIN, 2, 4}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"dry",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Scape>::setup()
{
UniqueID = 2588;
Label = "Scape";
Properties = HARD_RT;
Name = CAPS "Scape - Stereo delay + Filters";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 3,941
|
C++
|
.cc
| 167
| 20.856287
| 93
| 0.597479
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,000
|
VCO.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/VCO.cc
|
/*
VCO.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
an oversampled triangle/saw/square oscillator, and a combination of two
such oscillators with hard sync.
TODO: optimize for phase clamping like this:
phi -= floor (phi);
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "VCO.h"
#include "Descriptor.h"
void
VCOs::init()
{
/* going a fair bit lower than nominal with fc because the filter
* rolloff is not as steep as we might like it to be. */
double f = .5 * M_PI / OVERSAMPLE;
/* construct the downsampler filter kernel */
DSP::sinc (f, down.c, FIR_SIZE);
DSP::kaiser<DSP::apply_window> (down.c, FIR_SIZE, 6.4);
/* normalize downsampler filter gain */
double s = 0;
for (int i = 0; i < down.n; ++i)
s += down.c[i];
/* scale downsampler kernel */
s = 1 / s;
for (int i = 0; i < down.n; ++i)
down.c[i] *= s;
}
template <sample_func_t F>
void
VCOs::one_cycle (int frames)
{
vco.set_f (getport(0), OVERSAMPLE * fs);
vco.set_saw_square (getport(1), getport(2));
double g = (gain == *ports[3]) ?
1 : pow (getport(3) / gain, 1. / (double) frames);
sample_t * d = ports[4];
for (int i = 0; i < frames; ++i)
{
F (d, i, gain * down.process (vco.get()), adding_gain);
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (vco.get());
gain *= g;
}
gain = getport(3);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
VCOs::port_info [] =
{
{
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_100, 1, 5751}
}, {
"tri .. saw",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"~ .. square",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<VCOs>::setup()
{
UniqueID = 1783;
Label = "VCOs";
Properties = HARD_RT;
Name = CAPS "VCOs - Virtual 'analogue' oscillator";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
VCOd::init()
{
/* going a fair bit lower than nominal with fc because the filter
* rolloff is not as steep as we might like it to be. */
double f = .5 * M_PI / OVERSAMPLE;
/* construct the downsampler filter kernel */
DSP::sinc (f, down.c, FIR_SIZE);
DSP::kaiser<DSP::apply_window> (down.c, FIR_SIZE, 6.4);
/* normalize downsampler filter gain */
double s = 0;
for (int i = 0; i < down.n; ++i)
s += down.c[i];
/* scale downsampler kernel */
s = 1 / s;
for (int i = 0; i < down.n; ++i)
down.c[i] *= s;
}
template <sample_func_t F>
void
VCOd::one_cycle (int frames)
{
vco.set_f (getport(0), OVERSAMPLE * fs, getport(5));
vco.vco[0].set_saw_square (getport(1), getport(2));
vco.vco[1].set_saw_square (getport(3), getport(4));
vco.set_sync (getport(6));
vco.set_blend (getport(7));
double g = (gain == *ports[8]) ?
1 : pow (getport(8) / gain, 1. / (double) frames);
sample_t * d = ports[9];
for (int i = 0; i < frames; ++i)
{
F (d, i, gain * down.process (vco.get()), adding_gain);
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (vco.get());
gain *= g;
}
gain = getport(8);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
VCOd::port_info [] =
{
{
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_100, 1, 5751}
}, {
"1: tri .. saw",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"1: ~ .. square",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"2: tri .. saw",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"2: ~ .. square",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"2: tune",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -12, 12}
}, {
"sync",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, -1, 1}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<VCOd>::setup()
{
UniqueID = 1784;
Label = "VCOd";
Properties = HARD_RT;
Name = CAPS "VCOd - Double VCO with detune and hard sync options";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 5,100
|
C++
|
.cc
| 198
| 23.39899
| 78
| 0.612897
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,001
|
Compress.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Compress.cc
|
/*
Compress.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
mono compressor suitable for solo instruments. adaptation of Steve
Harris' 'sc1' unit, with minor tweaks: table lookup for attack and
release time to frames mapping replaced with exp. port order changed.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Compress.h"
#include "Descriptor.h"
template <sample_func_t F>
void
Compress::one_cycle (int frames)
{
sample_t * s = ports[0];
sample_t range = DSP::db2lin (getport(1));
sample_t ratio = (*ports[2] - 1) / getport(2);
/* sc1 has lookup tables here, and they're only 40 % used (400 ms/1 s).
* thus, sc1's attack/release controls are a bit coarse due to truncation
* error. calling exp() once per cycle doesn't seem too expensive.
*
* besides, i have a suspicion that the attack and release parameters
* don't work like they should. if they, as the code suggests, control
* an exponential envelope fade, pow (.5, n_frames) or something like
* that seems more appropriate. so ...
*
* TODO: check whether these parameters work like they should, try pow()
*/
double ga = exp (-1 / (fs * getport(3)));
double gr = exp (-1 / (fs * getport(4)));
sample_t threshold = getport(5);
sample_t knee = getport(6);
sample_t * d = ports[7];
sample_t knee0 = DSP::db2lin (threshold - knee);
sample_t knee1 = DSP::db2lin (threshold + knee);
sample_t ef_a = ga * .25;
sample_t ef_ai = 1 - ef_a;
for (int i = 0; i < frames; ++i)
{
sum += s[i] * s[i];
if (amp > env)
env = env * ga + amp * (1 - ga);
else
env = env * gr + amp * (1 - gr);
if ((count++ & 3) == 3)
{
amp = rms.process (sum * .25);
sum = 0;
if (env < knee0)
gain_t = 1;
else if (env < knee1)
{
float x = -(threshold - knee - DSP::lin2db (env)) / knee;
gain_t = DSP::db2lin (-knee * ratio * x * x * 0.25f);
}
else
gain_t = DSP::db2lin ((threshold - DSP::lin2db (env)) * ratio);
}
gain = gain * ef_a + gain_t * ef_ai;
F (d, i, s[i] * gain * range, adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Compress::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain (dB)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 24}
}, {
"ratio (1:n)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, 1, 10}
}, {
"attack (s)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, .001, 1}
}, {
"release (s)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, .001, 1}
}, {
"threshold (dB)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -30, 400}
}, {
"knee radius (dB)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 1, 10}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Compress>::setup()
{
UniqueID = 1772;
Label = "Compress";
Properties = HARD_RT;
Name = CAPS "Compress - Mono compressor";
Maker = "Tim Goetze <tim@quitte.de>, Steve Harris <steve@plugin.org.uk>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 3,774
|
C++
|
.cc
| 127
| 27.015748
| 78
| 0.647303
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,002
|
Roessler.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Roessler.cc
|
/*
Roessler.cc
Copyright 2002-11 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
the sound of a Roessler attractor.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include <stdlib.h>
#include "basics.h"
#include "Roessler.h"
#include "Descriptor.h"
void
Roessler::init()
{
roessler.init (h = .001, frandom());
gain = 0;
}
template <sample_func_t F>
void
Roessler::one_cycle (int frames)
{
roessler.set_rate (getport(0));
double g = (gain == getport(4)) ?
1 : pow (getport(4) / gain, 1. / (double) frames);
sample_t * d = ports[5];
sample_t x,
sx = .043 * getport(1),
sy = .051 * getport(2),
sz = .018 * getport(3);
for (int i = 0; i < frames; ++i)
{
roessler.get();
x =
sx * (roessler.get_x() - .515) +
sy * (roessler.get_y() + 2.577) +
sz * (roessler.get_z() - 2.578);
F (d, i, gain * x, adding_gain);
gain *= g;
}
gain = getport(4);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Roessler::port_info [] =
{
{
"h",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"x",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"y",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"z",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Roessler>::setup()
{
UniqueID = 1780;
Label = "Roessler";
Properties = HARD_RT;
Name = CAPS "Roessler - The sound of a Roessler attractor";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 2,384
|
C++
|
.cc
| 96
| 22.364583
| 78
| 0.646174
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,003
|
Lorenz.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Lorenz.cc
|
/*
Lorenz.cc
Copyright 2002-11 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
the sound of a Lorenz attractor.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include <stdlib.h>
#include "basics.h"
#include "Lorenz.h"
#include "Descriptor.h"
void
Lorenz::init()
{
lorenz.init (h = .001, 0.1 * frandom());
gain = 0;
}
template <sample_func_t F>
void
Lorenz::one_cycle (int frames)
{
lorenz.set_rate (*ports[0]);
double g = (gain == *ports[4]) ?
1 : pow (getport(4) / gain, 1. / (double) frames);
sample_t * d = ports[5];
sample_t x, sx = getport(1), sy = getport(2), sz = getport(3);
for (int i = 0; i < frames; ++i)
{
lorenz.step();
x = sx * lorenz.get_x() + sy * lorenz.get_y() + sz * lorenz.get_z();
F (d, i, gain * x, adding_gain);
gain *= g;
}
gain = getport(4);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Lorenz::port_info [] =
{
{
"h",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"x",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"y",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"z",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Lorenz>::setup()
{
UniqueID = 1774;
Label = "Lorenz";
Properties = HARD_RT;
Name = CAPS "Lorenz - The sound of a Lorenz attractor";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 2,279
|
C++
|
.cc
| 90
| 23.044444
| 78
| 0.650324
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
20,004
|
Chorus.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Chorus.cc
|
/*
Chorus.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
mono and mono-to-stereo chorus units.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Chorus.h"
#include "Descriptor.h"
template <sample_func_t F>
void
ChorusI::one_cycle (int frames)
{
sample_t * s = ports[0];
double one_over_n = 1 / (double) frames;
double ms = .001 * fs;
double t = time;
time = getport(1) * ms;
double dt = (time - t) * one_over_n;
double w = width;
width = getport(2) * ms;
/* clamp, or we need future samples from the delay line */
if (width >= t - 3) width = t - 3;
double dw = (width - w) * one_over_n;
if (rate != *ports[3])
lfo.set_f (max (rate = getport(3), .000001), fs, lfo.get_phase());
double blend = getport(4);
double ff = getport(5);
double fb = getport(6);
sample_t * d = ports[7];
DSP::FPTruncateMode truncate;
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
/* truncate the feedback tap to integer, better quality for less
* cycles (just a bit of zipper when changing 't', but it does sound
* interesting) */
int ti;
fistp (t, ti);
x -= fb * delay[ti];
delay.put (x + normal);
# if 0
/* allpass delay sounds a little cleaner for a chorus
* but sucks big time when flanging. */
x = blend * x + ff * tap.get (delay, t + w * lfo.get());
# elif 0
/* linear interpolation */
x = blend * x + ff * delay.get_at (t + w * lfo.get());
# else
/* cubic interpolation */
x = blend * x + ff * delay.get_cubic (t + w * lfo.get());
# endif
F (d, i, x, adding_gain);
t += dt;
w += dw;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
ChorusI::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"t (ms)",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_LOW, 2.5, 40}
}, {
"width (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, .5, 10}
}, {
"rate (Hz)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 5}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"feedforward",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<ChorusI>::setup()
{
UniqueID = 1767;
Label = "ChorusI";
Properties = HARD_RT;
Name = CAPS "ChorusI - Mono chorus/flanger";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
StereoChorusI::one_cycle (int frames)
{
sample_t * s = ports[0];
double one_over_n = 1 / (double) frames;
double ms = .001 * fs;
double t = time;
time = getport(1) * ms;
double dt = (time - t) * one_over_n;
double w = width;
width = getport(2) * ms;
/* clamp, or we need future samples from the delay line */
if (width >= t - 1) width = t - 1;
double dw = (width - w) * one_over_n;
if (rate != *ports[3] && phase != *ports[4])
{
rate = getport(3);
phase = getport(4);
double phi = left.lfo.get_phase();
left.lfo.set_f (max (rate, .000001), fs, phi);
right.lfo.set_f (max (rate, .000001), fs, phi + phase * M_PI);
}
double blend = getport(5);
double ff = getport(6);
double fb = getport(7);
sample_t * dl = ports[8];
sample_t * dr = ports[9];
/* to go sure (on i386) that the fistp instruction does the right thing
* when looking up fractional sample indices */
DSP::FPTruncateMode truncate;
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
/* truncate the feedback tap to integer, better quality for less
* cycles (just a bit of zipper when changing 't', but it does sound
* interesting) */
int ti;
fistp (t, ti);
x -= fb * delay[ti];
delay.put (x + normal);
sample_t l = blend * x + ff * delay.get_cubic (t + w * left.lfo.get());
sample_t r = blend * x + ff * delay.get_cubic (t + w * right.lfo.get());
F (dl, i, l, adding_gain);
F (dr, i, r, adding_gain);
t += dt;
w += dw;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
StereoChorusI::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"t (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, 2.5, 40}
}, {
"width (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, .5, 10}
}, {
"rate (Hz)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 5}
}, {
"phase",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0, 1}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"feedforward",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<StereoChorusI>::setup()
{
UniqueID = 1768;
Label = "StereoChorusI";
Properties = HARD_RT;
Name = CAPS "StereoChorusI - Stereo chorus/flanger";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
ChorusII::one_cycle (int frames)
{
sample_t * s = ports[0];
double one_over_n = 1 / (double) frames;
double ms = .001 * fs;
double t = time;
time = getport(1) * ms;
double dt = (time - t) * one_over_n;
double w = width;
width = getport(2) * ms;
/* clamp, or we need future samples from the delay line */
if (width >= t - 3) width = t - 3;
double dw = (width - w) * one_over_n;
if (rate != *ports[3])
set_rate (*ports[3]);
double blend = getport(4);
double ff = getport(5);
double fb = getport(6);
sample_t * d = ports[7];
DSP::FPTruncateMode truncate;
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
x -= fb * delay.get_cubic (t);
delay.put (filter.process (x + normal));
double a = 0;
for (int j = 0; j < Taps; ++j)
a += taps[j].get (delay, t, w);
x = blend * x + ff * a;
F (d, i, x, adding_gain);
t += dt;
w += dw;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
ChorusII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"t (ms)",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_LOW, 2.5, 40}
}, {
"width (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, .5, 10}
}, {
"rate",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"feedforward",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<ChorusII>::setup()
{
UniqueID = 2583;
Label = "ChorusII";
Properties = HARD_RT;
Name = CAPS "ChorusII - Mono chorus/flanger modulated by a fractal";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
StereoChorusII::one_cycle (int frames)
{
sample_t * s = ports[0];
double one_over_n = 1 / (double) frames;
double ms = .001 * fs;
double t = time;
time = getport(1) * ms;
double dt = (time - t) * one_over_n;
double w = width;
width = getport(2) * ms;
/* clamp, or we need future samples from the delay line */
if (width >= t - 1) width = t - 1;
double dw = (width - w) * one_over_n;
set_rate (*ports[3]);
double blend = getport(4);
double ff = getport(5);
double fb = getport(6);
sample_t * dl = ports[7];
sample_t * dr = ports[8];
/* to go sure (on i386) that the fistp instruction does the right thing
* when looking up fractional sample indices */
DSP::FPTruncateMode truncate;
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
/* truncate the feedback tap to integer, better quality for less
* cycles (just a bit of zipper when changing 't', but it does sound
* interesting) */
int ti;
fistp (t, ti);
x -= fb * delay[ti];
delay.put (x + normal);
double m;
m = left.lfo_lp.process (left.fractal.get());
sample_t l = blend * x + ff * delay.get_cubic (t + w * m);
m = right.lfo_lp.process (right.fractal.get());
sample_t r = blend * x + ff * delay.get_cubic (t + w * m);
F (dl, i, l, adding_gain);
F (dr, i, r, adding_gain);
t += dt;
w += dw;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
StereoChorusII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"t (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 2.5, 40}
}, {
"width (ms)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, .5, 10}
}, {
"rate",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"feedforward",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"feedback",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<StereoChorusII>::setup()
{
UniqueID = 2584;
Label = "StereoChorusII";
Properties = HARD_RT;
Name = CAPS "StereoChorusII - Stereo chorus/flanger modulated by a fractal";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 10,227
|
C++
|
.cc
| 416
| 22.069712
| 78
| 0.589889
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,005
|
Pan.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Pan.cc
|
/*
Pan.cc
Copyright 2002-11 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
panorama with width control,
stereo image width reduction
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Pan.h"
#include "Descriptor.h"
void
Pan::init()
{
delay.init ((int) (.040 * fs));
}
void
Pan::activate()
{
delay.reset();
tap.reset (400 / fs);
set_pan (getport (1));
}
inline void
Pan::set_pan (sample_t p)
{
pan = p;
double phi = (pan + 1) * M_PI * .25;
gain_l = cos (phi);
gain_r = sin (phi);
}
template <sample_func_t F>
void
Pan::one_cycle (int frames)
{
sample_t * s = ports[0];
if (pan != *ports[1])
set_pan (getport(1));
sample_t g = getport(2);
sample_t
width_l = g * gain_r,
width_r = g * gain_l;
tap.t = (int) (getport(3) * fs * .001);
bool mono = getport(4);
sample_t * dl = ports[5];
sample_t * dr = ports[6];
sample_t x, xt;
if (mono) for (int i = 0; i < frames; ++i)
{
x = s[i];
xt = tap.get (delay);
delay.put (x + normal);
x = (gain_l * x + gain_r * x + width_l * xt + width_r * xt) * .5;
F (dl, i, x, adding_gain);
F (dr, i, x, adding_gain);
normal = -normal;
}
else /* stereo */ for (int i = 0; i < frames; ++i)
{
x = s[i];
xt = tap.get (delay);
delay.put (x + normal);
F (dl, i, gain_l * x + width_l * xt, adding_gain);
F (dr, i, gain_r * x + width_r * xt, adding_gain);
normal = -normal;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Pan::port_info [] =
{
{
"in",
INPUT | AUDIO,
{0}
}, {
"pan",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -1, 1}
}, {
"width",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"t",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.1, 40}
}, {
"mono",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0 | INTEGER | TOGGLE, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Pan>::setup()
{
UniqueID = 1788;
Label = "Pan";
Properties = HARD_RT;
Name = CAPS "Pan - Pan and width";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
Narrower::init()
{
}
void
Narrower::activate()
{
}
template <sample_func_t F>
void
Narrower::one_cycle (int frames)
{
sample_t * sl = ports[0];
sample_t * sr = ports[1];
if (strength != *ports[2])
strength = *ports[2];
sample_t * dl = ports[3];
sample_t * dr = ports[4];
double xl, xr, m;
double dry = 1 - strength, wet = strength;
for (int i = 0; i < frames; ++i)
{
xl = sl[i];
xr = sr[i];
m = wet * (xl + xr) * .5;
xl *= dry;
xr *= dry;
xl += m;
xr += m;
F (dl, i, xl, adding_gain);
F (dr, i, xr, adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Narrower::port_info [] =
{
{
"in:l",
INPUT | AUDIO,
{0}
}, {
"in:r",
INPUT | AUDIO,
{0}
}, {
"strength",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Narrower>::setup()
{
UniqueID = 2595;
Label = "Narrower";
Properties = HARD_RT;
Name = CAPS "Narrower - Stereo image width reduction";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2011";
/* fill port info and vtable */
autogen();
}
| 4,176
|
C++
|
.cc
| 198
| 18.70202
| 78
| 0.588852
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,006
|
Sin.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Sin.cc
|
/*
Sin.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
simple sin() generator.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Sin.h"
#include "Descriptor.h"
void
Sin::init()
{
sin.set_f (f = .005, fs, 0);
gain = 0;
}
template <sample_func_t F>
void
Sin::one_cycle (int frames)
{
if (f != *ports[0])
sin.set_f (f = getport(0), fs, sin.get_phase());
double g = (gain == *ports[1]) ?
1 : pow (getport(1) / gain, 1. / (double) frames);
sample_t * d = ports[2];
for (int i = 0; i < frames; ++i)
{
F (d, i, gain * sin.get(), adding_gain);
gain *= g;
}
gain = getport(1);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Sin::port_info [] =
{
{
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_100, 0.0001, 20000}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Sin>::setup()
{
UniqueID = 1781;
Label = "Sin";
Properties = HARD_RT;
Name = CAPS "Sin - Sine wave generator";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 1,923
|
C++
|
.cc
| 75
| 23.493333
| 78
| 0.657722
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
20,007
|
White.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/White.cc
|
/*
White.cc
Copyright 2004-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
white noise generation.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "White.h"
#include "Descriptor.h"
template <sample_func_t F>
void
White::one_cycle (int frames)
{
double g = (gain == *ports[0]) ?
1 : pow (getport(0) / gain, 1. / (double) frames);
sample_t * d = ports[1];
for (int i = 0; i < frames; ++i)
{
F (d, i, gain * white.get(), adding_gain);
gain *= g;
}
gain = getport(0);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
White::port_info [] =
{
{
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, MIN_GAIN, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<White>::setup()
{
UniqueID = 1785;
Label = "White";
Properties = HARD_RT;
Name = CAPS "White - White noise generator";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 1,726
|
C++
|
.cc
| 63
| 25.253968
| 78
| 0.675593
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| true
| false
| false
| true
| false
| false
|
20,008
|
Reverb.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Reverb.cc
|
/*
Reverb.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
three reverb units: JVRev, Plate and Plate2x2.
the former is a rewrite of STK's JVRev, a traditional design.
original comment:
This is based on some of the famous
Stanford CCRMA reverbs (NRev, KipRev)
all based on the Chowning/Moorer/
Schroeder reverberators, which use
networks of simple allpass and comb
delay filters.
the algorithm is mostly unchanged in this implementation; the delay
line lengths have been fiddled with to make the stereo field more
evenly weighted, and denormal protection has been added.
the latter two are based on the circuit discussed in Jon Dattorro's
september 1997 JAES paper on effect design (part 1: reverb & filters).
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "Reverb.h"
#include "Descriptor.h"
int
JVRev::default_length[9] = {
#if 1 /* slightly modified, tg */
1777, 1847, 1993, 2137, 389, 127, 43, 211, 209
#else
4799, 4999, 5399, 5801, 1051, 337, 113, 573, 487
#endif
};
void
JVRev::init()
{
memcpy (length, default_length, sizeof (length));
if (fs != 44100)
{
double s = fs / 44100.;
for (int i = 0; i < 9; ++i)
{
int v = (int) (s * length[i]);
v |= 1;
while (!DSP::isprime (v))
v += 2;
length[i] = v;
}
}
for (int i = 0; i < 4; ++i)
comb[i].init (length[i]);
for (int i = 0; i < 3; ++i)
allpass[i].init (length[i+4]);
left.init (length[7]);
right.init (length[8]);
/* such a simple number, but i couldn't find a better one. */
apc = .7;
}
void
JVRev::set_t60 (sample_t t)
{
t60 = t;
t = max (.00001, t);
for (int i = 0; i < 4; ++i)
comb[i].c = pow (10, (-3 * length[i] / (t * fs)));
}
void
JVRev::activate()
{
for (int i = 0; i < 3; ++i)
allpass[i].reset();
for (int i = 0; i < 4; ++i)
comb[i].reset();
left.reset();
right.reset();
set_t60 (getport(1));
}
template <sample_func_t F>
void
JVRev::one_cycle (int frames)
{
sample_t * s = ports[0];
if (t60 != *ports[1])
set_t60 (getport(1));
double wet = getport(2), dry = 1 - wet;
sample_t * dl = ports[3];
sample_t * dr = ports[4];
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i], a = x + normal;
x *= dry;
/* diffusors */
a = allpass[0].process (a, -apc);
a = allpass[1].process (a, -apc);
a = allpass[2].process (a, -apc);
/* tank */
sample_t t = 0;
a -= normal;
for (int j = 0; j < 4; ++j)
t += comb[j].process (a);
F (dl, i, x + wet * left.putget (t), adding_gain);
F (dr, i, x + wet * right.putget (t), adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
JVRev::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"t60 (s)",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 4.6}
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, .28}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<JVRev>::setup()
{
UniqueID = 1778;
Label = "JVRev";
Properties = HARD_RT;
Name = CAPS "JVRev - Stanford-style reverb from STK";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
PlateStub::init()
{
f_lfo = -1;
# define L(i) ((int) (l[i] * fs))
static float l[] = {
0.004771345048889486, 0.0035953092974026408,
0.01273478713752898, 0.0093074829474816042,
0.022579886428547427, 0.030509727495715868,
0.14962534861059779, 0.060481838647894894, 0.12499579987231611,
0.14169550754342933, 0.089244313027116023, 0.10628003091293972
};
/* lh */
input.lattice[0].init (L(0));
input.lattice[1].init (L(1));
/* rh */
input.lattice[2].init (L(2));
input.lattice[3].init (L(3));
/* modulated, width about 12 samples @ 44.1 */
tank.mlattice[0].init (L(4), (int) (0.00040322707570310132 * fs));
tank.mlattice[1].init (L(5), (int) (0.00040322707570310132 * fs));
/* lh */
tank.delay[0].init (L(6));
tank.lattice[0].init (L(7));
tank.delay[1].init (L(8));
/* rh */
tank.delay[2].init (L(9));
tank.lattice[1].init (L(10));
tank.delay[3].init (L(11));
# undef L
# define T(i) ((int) (t[i] * fs))
static float t[] = {
0.0089378717113000241, 0.099929437854910791, 0.064278754074123853,
0.067067638856221232, 0.066866032727394914, 0.006283391015086859,
0.01186116057928161, 0.12187090487550822, 0.041262054366452743,
0.089815530392123921, 0.070931756325392295, 0.011256342192802662
};
for (int i = 0; i < 12; ++i)
tank.taps[i] = T(i);
# undef T
/* tuned for soft attack, ambience */
indiff1 = .742;
indiff2 = .712;
dediff1 = .723;
dediff2 = .729;
}
inline void
PlateStub::process (sample_t x, sample_t decay, sample_t * _xl, sample_t * _xr)
{
x = input.bandwidth.process (x);
/* lh */
x = input.lattice[0].process (x, indiff1);
x = input.lattice[1].process (x, indiff1);
/* rh */
x = input.lattice[2].process (x, indiff2);
x = input.lattice[3].process (x, indiff2);
/* summation point */
sample_t xl = x + decay * tank.delay[3].get();
sample_t xr = x + decay * tank.delay[1].get();
/* lh */
xl = tank.mlattice[0].process (xl, dediff1);
xl = tank.delay[0].putget (xl);
xl = tank.damping[0].process (xl);
xl *= decay;
xl = tank.lattice[0].process (xl, dediff2);
tank.delay[1].put (xl);
/* rh */
xr = tank.mlattice[1].process (xr, dediff1);
xr = tank.delay[2].putget (xr);
xr = tank.damping[1].process (xr);
xr *= decay;
xr = tank.lattice[1].process (xr, dediff2);
tank.delay[3].put (xr);
/* gather output */
xl = .6 * tank.delay[2] [tank.taps[0]];
xl += .6 * tank.delay[2] [tank.taps[1]];
xl -= .6 * tank.lattice[1] [tank.taps[2]];
xl += .6 * tank.delay[3] [tank.taps[3]];
xl -= .6 * tank.delay[0] [tank.taps[4]];
xl += .6 * tank.lattice[0] [tank.taps[5]];
xr = .6 * tank.delay[0] [tank.taps[6]];
xr += .6 * tank.delay[0] [tank.taps[7]];
xr -= .6 * tank.lattice[0] [tank.taps[8]];
xr += .6 * tank.delay[1] [tank.taps[9]];
xr -= .6 * tank.delay[2] [tank.taps[10]];
xr += .6 * tank.lattice[1] [tank.taps[11]];
*_xl = xl;
*_xr = xr;
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
Plate::one_cycle (int frames)
{
sample_t * s = ports[0];
input.bandwidth.set (exp (-M_PI * (1. - getport(1))));
sample_t decay = getport(2);
double damp = exp (-M_PI * getport(3));
tank.damping[0].set (damp);
tank.damping[1].set (damp);
sample_t blend = getport(4), dry = 1 - blend;
sample_t * dl = ports[5];
sample_t * dr = ports[6];
/* the modulated lattices interpolate, which needs truncated float */
DSP::FPTruncateMode _truncate;
for (int i = 0; i < frames; ++i)
{
normal = -normal;
sample_t x = s[i] + normal;
sample_t xl, xr;
PlateStub::process (x, decay, &xl, &xr);
x = dry * s[i];
F (dl, i, x + blend * xl, adding_gain);
F (dr, i, x + blend * xr, adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Plate::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"bandwidth",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.005, .999} /* .9995 */
}, {
"tail",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, .749} /* .5 */
}, {
"damping",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, .0005, 1} /* .0005 */
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Plate>::setup()
{
UniqueID = 1779;
Label = "Plate";
Properties = HARD_RT;
Name = CAPS "Plate - Versatile plate reverb";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
Plate2x2::one_cycle (int frames)
{
sample_t * sl = ports[0];
sample_t * sr = ports[1];
input.bandwidth.set (exp (-M_PI * (1. - getport(2))));
sample_t decay = getport(3);
double damp = exp (-M_PI * getport(4));
tank.damping[0].set (damp);
tank.damping[1].set (damp);
sample_t blend = getport(5), dry = 1 - blend;
sample_t * dl = ports[6];
sample_t * dr = ports[7];
/* the modulated lattices interpolate, which needs truncated float */
DSP::FPTruncateMode _truncate;
for (int i = 0; i < frames; ++i)
{
normal = -normal;
sample_t x = (sl[i] + sr[i] + normal) * .5;
sample_t xl, xr;
PlateStub::process (x, decay, &xl, &xr);
xl = blend * xl + dry * sl[i];
xr = blend * xr + dry * sr[i];
F (dl, i, xl, adding_gain);
F (dr, i, xr, adding_gain);
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Plate2x2::port_info [] =
{
{
"in:l",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"in:r",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"bandwidth",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.005, .999} /* .9995 */
}, {
"tail",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, .749} /* .5 */
}, {
"damping",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, .0005, 1} /* .0005 */
}, {
"blend",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Plate2x2>::setup()
{
UniqueID = 1795;
Label = "Plate2x2";
Properties = HARD_RT;
Name = CAPS "Plate2x2 - Versatile plate reverb, stereo inputs";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 10,409
|
C++
|
.cc
| 395
| 23.868354
| 79
| 0.604181
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,009
|
Click.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Click.cc
|
/*
Click.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
Plugins playing a sound snippet in regular intervals.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "waves/click.h"
#include "waves/money.h"
#include "Click.h"
#include "Descriptor.h"
void
ClickStub::init (float * _wave, int _N)
{
wave = _wave;
N = _N;
bpm = -1;
}
template <sample_func_t F>
void
ClickStub::one_cycle (int frames)
{
bpm = getport(0);
sample_t gain = getport(1) * *ports[1];
lp.set (1 - *ports[2]);
sample_t * d = ports[3];
while (frames)
{
if (period == 0)
{
period = (int) (fs * 60 / bpm);
played = 0;
}
int n = min (frames, period);
if (played < N)
{
n = min (n, N - played);
for (int i = 0; i < n; ++i)
{
sample_t x = gain * wave [played + i] + normal;
F (d, i, lp.process (x), adding_gain);
normal = -normal;
}
played += n;
}
else
{
for (int i = 0; i < n; ++i)
{
F (d, i, lp.process (normal), adding_gain);
normal = -normal;
}
}
period -= n;
frames -= n;
d += n;
}
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
ClickStub::port_info [] =
{
{
"bpm",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 4, 244}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"damping",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
/* //////////////////////////////////////////////////////////////////////// */
#define LENGTH(W) ((int) (sizeof (W) / sizeof (float)))
void
Click::init()
{
this->ClickStub::init (click, LENGTH (click));
}
template <> void
Descriptor<Click>::setup()
{
UniqueID = 1769;
Label = "Click";
Properties = HARD_RT;
Name = CAPS "Click - Metronome";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
CEO::port_info [] =
{
{
"mpm",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 4, 244}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"damping",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
void
CEO::init()
{
this->ClickStub::init (money, LENGTH (money));
}
template <> void
Descriptor<CEO>::setup()
{
UniqueID = 1770;
Label = "CEO";
Properties = HARD_RT;
Name = CAPS "CEO - Chief Executive Oscillator";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
float dirac [] = { 1, };
PortInfo
Dirac::port_info [] =
{
{
"ppm",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, 30, 60}
}, {
"volume",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"damping",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
void
Dirac::init()
{
this->ClickStub::init (dirac, LENGTH (dirac));
}
template <> void
Descriptor<Dirac>::setup()
{
UniqueID = 2585;
Label = "Dirac";
Properties = HARD_RT;
Name = CAPS "Dirac - One-sample impulse generator";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 4,077
|
C++
|
.cc
| 192
| 18.84375
| 78
| 0.594475
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,010
|
Eq.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Eq.cc
|
/*
Eq.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
10-band octave-spread equalizer.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include <stdio.h>
#include "Eq.h"
#include "Descriptor.h"
/* slight adjustments to gain to keep response optimally flat at
* 0 dB gain in all bands */
inline static double
adjust_gain (int i, double g)
{
static float adjust[] = {
0.69238604707174034, 0.67282771124180096,
0.67215187672467813, 0.65768648447259315,
0.65988083755898952, 0.66359580101701909,
0.66485139160960427, 0.65890297086039662,
0.6493229390740376, 0.82305724539749325
};
return g * adjust[i];
}
#define Q 1.414
void
Eq::init()
{
eq.init (fs, Q);
}
void
Eq::activate()
{
for (int i = 0; i < 10; ++i)
{
gain[i] = getport (1 + i);
eq.gain[i] = adjust_gain (i, DSP::db2lin (gain[i]));
eq.gf[i] = 1;
}
}
template <sample_func_t F>
void
Eq::one_cycle (int frames)
{
sample_t * s = ports[0];
/* evaluate band gain changes and compute recursion factor to prevent
* zipper noise */
double one_over_n = frames > 0 ? 1. / frames : 1;
for (int i = 0; i < 10; ++i)
{
sample_t g = getport (1 + i);
if (g == gain[i])
{
/* no gain factoring */
eq.gf[i] = 1;
continue;
}
gain[i] = g;
double want = adjust_gain (i, DSP::db2lin (g));
eq.gf[i] = pow (want / eq.gain[i], one_over_n);
}
sample_t * d = ports[11];
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
x = eq.process (x);
F (d, i, x, adding_gain);
}
eq.normal = -normal;
eq.flush_0();
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
Eq::port_info [] =
{
{
"in",
INPUT | AUDIO,
{0, -1, 1}
}, {
"31 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"63 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"125 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"250 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"500 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"1 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"2 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"4 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"8 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"16 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Eq>::setup()
{
UniqueID = 1773;
Label = "Eq";
Properties = HARD_RT;
Name = CAPS "Eq - 10-band equalizer";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
Eq2x2::init()
{
for (int c = 0; c < 2; ++c)
eq[c].init (fs, Q);
}
void
Eq2x2::activate()
{
/* Fetch current parameter settings so we won't sweep band gains in the
* first block to process.
*/
for (int i = 0; i < 10; ++i)
{
gain[i] = getport (2 + i);
double a = adjust_gain (i, DSP::db2lin (gain[i]));
for (int c = 0; c < 2; ++c)
eq[c].gf[i] = 1,
eq[c].gain[i] = a;
}
}
template <sample_func_t F>
void
Eq2x2::one_cycle (int frames)
{
/* evaluate band gain changes and compute recursion factor to prevent
* zipper noise */
double one_over_n = frames > 0 ? 1. / frames : 1;
for (int i = 0; i < 10; ++i)
{
double a;
if (*ports [2 + i] == gain[i])
/* still same value, no gain fade */
a = 1;
else
{
gain[i] = getport (2 + i);
/* prepare factor for logarithmic gain fade */
a = adjust_gain (i, DSP::db2lin (gain[i]));
a = pow (a / eq[0].gain[i], one_over_n);
}
for (int c = 0; c < 2; ++c)
eq[c].gf[i] = a;
}
for (int c = 0; c < 2; ++c)
{
sample_t
* s = ports[c],
* d = ports[12 + c];
for (int i = 0; i < frames; ++i)
{
sample_t x = s[i];
x = eq[c].process (x);
F (d, i, x, adding_gain);
}
}
/* flip 'renormal' values */
for (int c = 0; c < 2; ++c)
{
eq[c].normal = normal;
eq[c].flush_0();
}
}
PortInfo
Eq2x2::port_info [] =
{
{
"in:l",
INPUT | AUDIO,
{0, -1, 1}
}, {
"in:r",
INPUT | AUDIO,
{0, -1, 1}
}, {
"31 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"63 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"125 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"250 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"500 Hz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"1 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"2 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"4 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"8 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"16 kHz",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -48, 24}
}, {
"out:l",
OUTPUT | AUDIO,
{0}
}, {
"out:r",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<Eq2x2>::setup()
{
UniqueID = 2594;
Label = "Eq2x2";
Properties = HARD_RT;
Name = CAPS "Eq2x2 - stereo 10-band equalizer";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
/*
todo: parametric -- 20-400, 60-1k, 150-2.5k, 500-8k, 1k-20k
bandwidth 0-2 octaves
*/
| 6,151
|
C++
|
.cc
| 293
| 18.498294
| 78
| 0.586474
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,012
|
Preamp.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Preamp.cc
|
/*
Preamp.cc
Copyright 2003-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
Loosely 12AX7-based tube preamp model with 8x oversampling.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include <stdio.h>
#include "Amp.h"
#include "Descriptor.h"
void
PreampIII::init()
{
this->AmpStub::init();
DSP::RBJ::LoShelve (200 / fs, .2, -6, filter.a, filter.b);
}
template <sample_func_t F, int OVERSAMPLE>
void
PreampIII::one_cycle (int frames)
{
sample_t * s = ports[0];
sample_t gain = getport(1);
sample_t temp = getport(2) * tube.scale;
sample_t * d = ports[3];
*ports[4] = OVERSAMPLE;
double g = current.g;
current.g = max (gain < 1 ? gain : exp2 (gain - 1), .000001);
/* correction for attenuated first transfer */
current.g *= tube.scale / fabs (tube.transfer (temp));
if (g == 0) g = current.g;
/* recursive fade to prevent zipper noise from the 'gain' knob */
double one_over_n = frames > 0 ? 1. / frames : 1;
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i] + normal;
a = g * tube.transfer (a * temp);
a = filter.process (a);
a = down.process (tube.transfer_clip (up.upsample (a)));
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (tube.transfer_clip (up.pad (o)));
F (d, i, dc_blocker.process (a), adding_gain);
g *= gf;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
PreampIII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 10}
}, {
"temperature",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.005, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<PreampIII>::setup()
{
UniqueID = 1776;
Label = "PreampIII";
Properties = HARD_RT;
Name = CAPS "PreampIII - Tube preamp emulation";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
PreampIV::init()
{
this->AmpStub::init();
tone.init (fs);
}
void
PreampIV::activate()
{
this->PreampIII::activate();
tone.activate (ports + 3);
}
template <sample_func_t F, int OVERSAMPLE>
void
PreampIV::one_cycle (int frames)
{
double one_over_n = frames > 0 ? 1. / frames : 1;
sample_t * s = ports[0];
sample_t gain = getport(1);
sample_t temp = getport(2) * tube.scale;
tone.start_cycle (ports + 3, one_over_n);
sample_t * d = ports[7];
*ports[8] = OVERSAMPLE;
double g = current.g;
current.g = max (gain < 1 ? gain : exp2 (gain - 1), .000001);
current.g *= tube.scale / fabs (tube.transfer (temp));
if (g == 0) g = current.g;
/* recursive fade to prevent zipper noise from the 'gain' knob */
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
sample_t a = tone.process (s[i] + normal);
a = g * tube.transfer (a * temp);
a = down.process (tube.transfer_clip (up.upsample (a)));
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (tube.transfer_clip (up.pad (o)));
F (d, i, dc_blocker.process (a), adding_gain);
g *= gf;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
PreampIV::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 10}
}, {
"temperature",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.005, 1}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"mid",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"treble",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"hi",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<PreampIV>::setup()
{
UniqueID = 1777;
Label = "PreampIV";
Properties = HARD_RT;
Name = CAPS "PreampIV - Tube preamp emulation + tone controls";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
| 4,927
|
C++
|
.cc
| 194
| 23.041237
| 78
| 0.622783
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,013
|
ToneStack.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/ToneStack.cc
|
/*
ToneStack.cc
Copyright 2006-7
David Yeh <dtyeh@ccrma.stanford.edu>
Tim Goetze <tim@quitte.de> (cosmetics)
Tone Stack emulation.
*
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include "ToneStack.h"
#include "Descriptor.h"
#include "dsp/tonestack/ks_tab.h"
#include "dsp/tonestack/vs_tab.h"
DSP::TSParameters
DSP::ToneStack::presets[] = {
/* for convenience, temporarily define k and MOhms as well as nF and pF */
#define k * 1000
#define M * 1000000
#define nF * 1e-9
#define pF * 1e-12
/* parameter order is R1 - R4, C1 - C3 */
/* { 250000, 1000000, 25000, 56000, 0.25e-9, 20e-9, 20e-9 }, DY */
/* Fender */
{250 k, 1 M, 25 k, 56 k, 250 pF, 20 nF, 20 nF}, /* 59 Bassman 5F6-A */
{250 k, 250 k, 10 k, 100 k, 120 pF, 100 nF, 47 nF}, /* 69 Twin Reverb AA270 */
{250 k, 250 k, 4.8 k, 100 k, 250 pF, 100 nF, 47 nF}, /* 64 Princeton AA1164 */
/* Marshall */
{220 k, 1 M, 22 k, 33 k, 470 pF, 22 nF, 22 nF}, /* 59/81 JCM-800 Lead 100 2203 */
/* R4 is a 10 k fixed + 100 k pot in series actually */
{250 k, 1 M, 25 k, 56 k, 500 pF, 22 nF, 22 nF}, /* 81 2000 Lead */
#if 0
{220 k, 1 M, 22 k, 33 k, 470 pF, 22 nF, 22 nF}, /* 90 JCM-900 Master 2100 (same as JCM-800) */
{250 k, 1 M, 25 k, 33 k, 500 pF, 22 nF, 22 nF}, /* 67 Major Lead 200 */
{250 k, 250 k, 25 k, 56 k, 250 pF, 47 nF, 47 nF}, /* undated M2199 30W solid state */
#endif
/* Vox -- R3 is fixed (circuit differs anyway) */
{1 M, 1 M, 10 k, 100 k, 50 pF, 22 nF, 22 nF}, /* 59/86 AC-30 */
#undef k
#undef M
#undef nF
#undef pF
};
int DSP::ToneStack::n_presets = TS_N_PRESETS;
void
ToneStack::activate()
{
tonestack.activate (ports + 2);
}
template <sample_func_t F>
void
ToneStack::one_cycle (int frames)
{
sample_t * s = ports[0];
tonestack.start_cycle (ports + 1);
sample_t * d = ports[5];
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i];
a = tonestack.process (a + normal);
F (d, i, a, adding_gain);
}
}
PortInfo
ToneStack::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"model",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0 | INTEGER, 0, TS_N_PRESETS - 1}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"mid",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"treble",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<ToneStack>::setup()
{
UniqueID = 2589;
Label = "ToneStack";
Properties = HARD_RT;
Name = CAPS "ToneStack - Tone stack emulation";
Maker = "David Yeh <dtyeh@ccrma.stanford.edu>";
Copyright = "GPL, 2006-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
template <sample_func_t F>
void
ToneStackLT::one_cycle (int frames)
{
sample_t * s = ports[0];
tonestack.updatecoefs (ports + 1);
sample_t * d = ports[4];
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i];
a = tonestack.process (a + normal);
F (d, i, a, adding_gain);
}
}
PortInfo
ToneStackLT::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"mid",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"treble",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<ToneStackLT>::setup()
{
UniqueID = 2590;
Label = "ToneStackLT";
Properties = HARD_RT;
Name = CAPS "ToneStackLT - Tone stack emulation, lattice filter 44.1";
Maker = "David Yeh <dtyeh@ccrma.stanford.edu>";
Copyright = "GPL, 2006-7";
/* fill port info and vtable */
autogen();
}
| 4,385
|
C++
|
.cc
| 169
| 23.757396
| 95
| 0.640726
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,014
|
Amp.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/Amp.cc
|
/*
Amp.cc
Copyright 2003-7
Tim Goetze <tim@quitte.de>
David Yeh <dtyeh@ccrma.stanford.edu> (Tone Stack in TS models)
http://quitte.de/dsp/
Tube amplifier models
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include <stdio.h>
#include "Amp.h"
#include "Descriptor.h"
void
AmpStub::init (bool adjust_downsampler)
{
dc_blocker.set_f (10. / fs);
/* going a bit lower than nominal with fc */
double f = .7 * M_PI / OVERSAMPLE;
/* construct the upsampler filter kernel */
DSP::sinc (f, up.c, FIR_SIZE);
DSP::kaiser<DSP::apply_window> (up.c, FIR_SIZE, 6.4);
/* copy upsampler filter kernel for downsampler, make sum */
double s = 0;
for (int i = 0; i < up.n; ++i)
down.c[i] = up.c[i],
s += up.c[i];
s = 1 / s;
/* scale downsampler kernel for unity gain + correction for transfer */
double t = adjust_downsampler ?
s / max (fabs (tube.clip[0].value), fabs (tube.clip[1].value)) : s;
for (int i = 0; i < down.n; ++i)
down.c[i] *= t;
/* scale upsampler kernel for unity gain */
s *= OVERSAMPLE;
for (int i = 0; i < up.n; ++i)
up.c[i] *= s;
}
/* //////////////////////////////////////////////////////////////////////// */
void
AmpIII::init()
{
this->AmpStub::init (false);
/* need to filter out dc before the power amp stage, which is running at
* the oversampled rate */
dc_blocker.set_f (10. / (fs * OVERSAMPLE));
DSP::RBJ::LoShelve (200 / fs, .2, -3, filter.a, filter.b);
}
template <sample_func_t F, int OVERSAMPLE>
void
AmpIII::one_cycle (int frames)
{
sample_t * s = ports[0];
sample_t gain = getport(1);
sample_t temp = getport(2) * tube.scale;
drive = getport(3) * .5;
i_drive = 1 / (1 - drive);
sample_t * d = ports[4];
*ports[5] = OVERSAMPLE;
double g = current.g;
current.g = max (gain < 1 ? gain : exp2 (gain - 1), .000001);
current.g *= tube.scale / fabs (tube.transfer (temp));
/* recursive fade to prevent zipper noise from the 'gain' knob */
if (g == 0) g = current.g;
double one_over_n = frames > 0 ? 1. / frames : 1;
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i];
a = g * tube.transfer (a * temp);
a = filter.process (a + normal);
a = tube.transfer_clip (up.upsample (a));
a = power_transfer (dc_blocker.process (a));
a = down.process (a);
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (
power_transfer (
dc_blocker.process (
normal + tube.transfer_clip (up.pad (o)))));
F (d, i, a, adding_gain);
g *= gf;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
AmpIII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 10}
}, {
"temperature",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.005, 1}
}, {
"drive",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0.0001, 1} /* ^2 gives the nice drive */
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<AmpIII>::setup()
{
UniqueID = 1786;
Label = "AmpIII";
Properties = HARD_RT;
Name = CAPS "AmpIII - Tube amp";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
AmpIV::init()
{
this->AmpStub::init (false);
/* need to filter out dc before the power amp stage, which is running at
* the oversampled rate */
dc_blocker.set_f (10. / (fs * OVERSAMPLE));
tone.init (fs);
}
template <sample_func_t F, int OVERSAMPLE>
void
AmpIV::one_cycle (int frames)
{
double one_over_n = frames > 0 ? 1. / frames : 1;
sample_t * s = ports[0];
sample_t gain = getport(1);
sample_t temp = getport(2) * tube.scale;
tone.start_cycle (ports + 3, one_over_n);
drive = getport(7) * .5;
i_drive = 1 / (1 - drive);
sample_t * d = ports[8];
*ports[9] = OVERSAMPLE;
double g = current.g;
current.g = max (gain < 1 ? gain : exp2 (gain - 1), .000001);
current.g *= tube.scale / fabs (tube.transfer (temp));
/* recursive fade to prevent zipper noise from the 'gain' knob */
if (g == 0) g = current.g;
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i] + normal;
a = g * tube.transfer (a * temp);
a = tone.process (a);
a = tube.transfer_clip (up.upsample (a));
a = power_transfer (dc_blocker.process (a));
a = down.process (a);
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (
power_transfer (
dc_blocker.process (
normal + tube.transfer_clip (up.pad (o)))));
F (d, i, a, adding_gain);
g *= gf;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
AmpIV::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 10}
}, {
"temperature",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.005, 1}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"mid",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"treble",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"hi",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -20, 20}
}, {
"drive",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0.0001, 1} /* ^2 gives the nice drive */
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<AmpIV>::setup()
{
UniqueID = 1794;
Label = "AmpIV";
Properties = HARD_RT;
Name = CAPS "AmpIV - Tube amp + tone controls";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
AmpV::init()
{
this->AmpStub::init (false);
/* need to filter out dc before the power amp stage, which is running at
* the oversampled rate */
dc_blocker.set_f (10. / (fs * OVERSAMPLE));
DSP::RBJ::LoShelve (210. / fs, .2, -1, filter[0].a, filter[0].b);
DSP::RBJ::LoShelve (4200. / fs, 1.2, +6, filter[1].a, filter[1].b);
DSP::RBJ::LoShelve (420. / fs, .2, +2, filter[2].a, filter[2].b);
/* power supply cap */
for (int i = 0; i < 2; ++i)
DSP::RBJ::LP (10. / fs, .3, power_cap[i].a, power_cap[i].b);
}
template <sample_func_t F, int OVERSAMPLE>
void
AmpV::one_cycle (int frames)
{
sample_t * s = ports[0];
sample_t gain = getport(1);
if (*ports[2] != cut)
{
cut = getport(2);
DSP::RBJ::LoShelve (210. / fs, .2, cut, filter[0].a, filter[0].b);
}
if (*ports[3] != tone)
{
tone = getport(3);
double f = tone * tone * 8400 + 420;
double q = tone * .4 + .2;
double db = tone * 2 + 2;
DSP::RBJ::LoShelve (f / fs, q, db, filter[2].a, filter[2].b);
}
drive = getport(4) * .5;
i_drive = 1 / (1 - drive);
#define MAX_WATTS port_info[5].range.UpperBound
sample_t sag = (MAX_WATTS - getport(5)) / MAX_WATTS;
sag = .6 * sag * sag;
sample_t * d = ports[6];
*ports[7] = OVERSAMPLE;
double g = current.g;
current.g = max (gain < 1 ? gain : pow (20, gain - 1), .000001);
#if 0
if ( (++_turn & 127) == 0)
fprintf (stderr, "supply = %.3f sag = %.3f\n", supply, sag);
#endif
if (g == 0) g = current.g;
/* recursive fade to prevent zipper noise from the 'gain' knob */
double one_over_n = frames > 0 ? 1. / frames : 1;
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
sample_t a = s[i];
sample_t v = 3 - supply;
/* alternative curve: v = v * v * .1 + .1; */
v = v * v * .06 + .46;
a = filter[0].process (a + normal);
a = g * (a + supply * .001);
a = v * tube.transfer_clip (up.upsample (a));
a = power_transfer (dc_blocker.process (a));
a = down.process (a);
a = filter[1].process (a - normal);
a = filter[2].process (a + normal);
{
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (
power_transfer (
dc_blocker.process (
normal + tube.transfer_clip (
up.pad (o)))));
}
F (d, i, a, adding_gain);
/* integrate for an approximation of cumulative output power */
supply += sag * fabs (a) + normal;
/* filter integrated power consumption */
for (int j = 0; j < 2; ++j)
supply = 0.9 * (power_cap[j].process (supply));
g *= gf;
normal = -normal;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
AmpV::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 3}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0, -9, 9}
}, {
"tone",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MIN, 0, 1}
}, {
"drive",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0.0001, 1} /* ^2 gives the nice drive */
}, {
"watts",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 5, 150}
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<AmpV>::setup()
{
UniqueID = 2587;
Label = "AmpV";
Properties = HARD_RT;
Name = CAPS "AmpV - Tube amp";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
AmpVTS::init()
{
this->AmpStub::init (false);
/* need to filter out dc before the power amp stage, which is running at
* the oversampled rate */
dc_blocker.set_f (10. / (fs * OVERSAMPLE));
/* power supply capacitance */
for (int i = 0; i < 2; ++i)
DSP::RBJ::LP (10. / fs, .3, power_cap[i].a, power_cap[i].b);
tonestack.init (fs);
}
template <sample_func_t F, int OVERSAMPLE>
void
AmpVTS::one_cycle (int frames)
{
sample_t * s = ports[0];
tonestack.start_cycle (ports + 1, 2);
sample_t gain = getport(2);
drive = getport(6) * .5;
i_drive = 1 / (1 - drive);
sample_t sag = 1 - max (0.0001, min (1, getport(7)));
sag = .6 * sag * sag; /* map to log space makes slider better */
sample_t * d = ports[8];
*ports[9] = OVERSAMPLE;
double g = current.g;
if (gain < 1)
current.g = max (gain, .001);
else
{
gain -= 1;
gain *= gain;
current.g = pow (10, gain);
}
/* recursive fade to prevent zipper noise from the 'gain' knob */
double one_over_n = frames > 0 ? 1. / frames : 1;
double gf = pow (current.g / g, one_over_n);
for (int i = 0; i < frames; ++i)
{
double a = s[i];
double v = 3 - supply;
v = v * v * .06 + .46;
a = tube.transfer (a);
a = tonestack.process (a + normal);
a = g * (a + supply * .001);
a = v * tube.transfer_clip (up.upsample (a));
a = power_transfer (dc_blocker.process (a));
a = down.process (a);
{
for (int o = 1; o < OVERSAMPLE; ++o)
down.store (
power_transfer (
dc_blocker.process (
normal + tube.transfer_clip (
up.pad (o)))));
}
F (d, i, a, adding_gain);
/* integrate for an approximation of cumulative output power */
supply += sag * fabs (a) + normal;
/* filter integrated power consumption */
for (int j = 0; j < 2; ++j)
supply = 0.9 * (power_cap[j].process (supply + normal));
g *= gf;
normal = -normal;
}
current.g = g;
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
AmpVTS::port_info [] =
{
{
"in",
INPUT | AUDIO,
{BOUNDED, -1, 1}
}, {
"model",
INPUT | CONTROL,
{BOUNDED | DEFAULT_0 | INTEGER, 0, 5} /* no way to set dyn at compile t */
}, {
"gain",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 3}
}, {
"bass",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"mid",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1, 0, 1}
}, {
"treble",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0, 1}
}, {
"drive",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.0001, 1}
}, {
"watts",
INPUT | CONTROL,
{BOUNDED | DEFAULT_HIGH, 0.0001, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}, {
"latency",
OUTPUT | CONTROL,
{0}
}
};
template <> void
Descriptor<AmpVTS>::setup()
{
UniqueID = 2592;
Label = "AmpVTS";
Properties = HARD_RT;
Name = CAPS "AmpVTS - Tube amp + Tone stack";
Maker = "David Yeh <dtyeh@ccrma.stanford.edu> & Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2002-7";
/* fill port info and vtable */
autogen();
}
| 13,084
|
C++
|
.cc
| 503
| 23.240557
| 78
| 0.582991
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
20,015
|
SweepVF.cc
|
LMMS_lmms/plugins/LadspaEffect/caps/SweepVF.cc
|
/*
SweepVF.cc
Copyright 2002-7 Tim Goetze <tim@quitte.de>
http://quitte.de/dsp/
SweepVFI, a lorenz fractal modulating the cutoff frequency of a
state-variable (ladder) filter.
SweepVFII, the same with Q being modulated by a second fractal.
*/
/*
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA or point your web browser to http://www.gnu.org.
*/
#include "basics.h"
#include <algorithm>
#include "SweepVF.h"
#include "Descriptor.h"
#include "dsp/RBJ.h"
void
SweepVFI::init()
{
f = .1;
Q = .1;
lorenz.init();
}
void
SweepVFI::activate()
{
svf.reset();
svf.set_f_Q (f = getport(1) / fs, Q = getport(2));
}
template <sample_func_t F>
void
SweepVFI::one_cycle (int frames)
{
sample_t * s = ports[0];
int blocks = frames / BLOCK_SIZE;
if (frames & (BLOCK_SIZE - 1))
++blocks;
double one_over_blocks = 1 / (double) blocks;
/* cheesy linear interpolation for f, works well though. */
double df = (getport(1) / fs - f) * one_over_blocks;
double dQ = (getport(2) - Q) * one_over_blocks;
svf.set_out ((int) getport(3));
lorenz.set_rate (getport(7));
sample_t * d = ports[8];
while (frames)
{
lorenz.step();
double modulation =
getport(4) * lorenz.get_x() +
getport(5) * lorenz.get_y() +
getport(6) * lorenz.get_z();
double scale = getport(4) + getport(5) + getport(6);
modulation *= scale * f;
svf.set_f_Q (max (.001, f + modulation), Q);
int n = std::min<int> (frames, BLOCK_SIZE);
for (int i = 0; i < n; ++i)
F (d, i, svf.process (s[i] + normal), adding_gain);
s += n;
d += n;
frames -= n;
f += df;
Q += dQ;
}
f = getport(1) / fs;
Q = getport(2);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
SweepVFI::port_info [] =
{
{
"in",
INPUT | AUDIO,
{0, 0, 0}
}, {
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_LOW, 83, 3383}
}, {
"Q",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.001, .999}
}, {
"mode",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1 | INTEGER, 0, 1} /* only lo and band make sense */
}, {
"depth:x",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"depth:y",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"depth:z",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0, 1}
}, {
"h",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.001, 1} /* .039 */
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<SweepVFI>::setup()
{
UniqueID = 1782;
Label = "SweepVFI";
Properties = HARD_RT;
Name = CAPS "SweepVFI - Resonant filter swept by a Lorenz fractal";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
SweepVFII::init()
{
f = .1;
Q = .1;
lorenz1.init();
lorenz2.init();
}
void
SweepVFII::activate()
{
svf.reset();
svf.set_f_Q (f = getport(1) / fs, Q = getport(2));
}
template <sample_func_t F>
void
SweepVFII::one_cycle (int frames)
{
sample_t * s = ports[0];
int blocks = frames / BLOCK_SIZE;
if (frames & (BLOCK_SIZE - 1))
++blocks;
double one_over_blocks = 1 / (double) blocks;
/* cheesy linear interpolation for f, works well though. */
double df = (getport(1) / fs - f) * one_over_blocks;
double dQ = (getport(2) - Q) * one_over_blocks;
svf.set_out ((int) getport(3));
lorenz1.set_rate (getport(7));
lorenz2.set_rate (getport(11));
sample_t * d = ports[12];
while (frames)
{
/* f modulation */
lorenz1.step();
double modulation1 =
getport(4) * lorenz1.get_x() +
getport(5) * lorenz1.get_y() +
getport(6) * lorenz1.get_z();
double scale1 = getport(4) + getport(5) + getport(6);
modulation1 *= scale1 * f;
/* Q modulation */
lorenz2.step();
double modulation2 =
getport(8) * lorenz2.get_x() +
getport(9) * lorenz2.get_y() +
getport(10) * lorenz2.get_z();
double scale2 = getport(8) + getport(9) + getport(10);
/* enforce Q limit */
double q = Q + (modulation2 * scale2 * Q);
q = min (0.96, max (q, 0));
svf.set_f_Q (max (.001, f + modulation1), q);
int n = std::min<int> (frames, BLOCK_SIZE);
for (int i = 0; i < n; ++i)
F (d, i, svf.process (s[i] + normal), adding_gain);
s += n;
d += n;
frames -= n;
f += df;
Q += dQ;
}
f = getport(1) / fs;
Q = getport(2);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
SweepVFII::port_info [] =
{
{
"in",
INPUT | AUDIO,
{0, 0, 0}
}, {
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_LOW, 83, 3383}
}, {
"Q",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0.001, .999}
}, {
"mode",
INPUT | CONTROL,
{BOUNDED | DEFAULT_1 | INTEGER, 0, 1} /* only lo and band make sense */
}, {
"f:depth:x",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"f:depth:y",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"f:depth:z",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0, 1}
}, {
"f:h",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.001, 1} /* .039 */
}, {
"Q:depth:x",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0, 1}
}, {
"Q:depth:y",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"Q:depth:z",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MAX, 0, 1}
}, {
"Q:h",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.001, 1} /* .039 */
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<SweepVFII>::setup()
{
UniqueID = 2582;
Label = "SweepVFII";
Properties = HARD_RT;
Name = CAPS "SweepVFII - Resonant filter, f and Q swept by a Lorenz fractal";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
/* //////////////////////////////////////////////////////////////////////// */
void
AutoWah::init()
{
f = 800 / fs;
Q = .5;
}
void
AutoWah::activate()
{
svf.reset();
svf.set_f_Q (f = getport(1) / fs, Q = getport(2));
svf.set_out (DSP::SVF<1>::Band);
/* hi-passing input for envelope RMS calculation */
hp.set_f (250. / fs);
/* smoothing the envelope at 20 Hz */
DSP::RBJ::LP (20. * BLOCK_SIZE / fs, .6, filter.a, filter.b);
rms.reset();
hp.reset();
filter.reset();
}
template <sample_func_t F>
void
AutoWah::one_cycle (int frames)
{
sample_t * s = ports[0];
int blocks = frames / BLOCK_SIZE;
if (frames & (BLOCK_SIZE - 1))
++blocks;
double one_over_blocks = 1 / (double) blocks;
/* cheesy linear interpolation for f, works well though. */
double df = (getport(1) / fs - f) * one_over_blocks;
double dQ = (getport(2) - Q) * one_over_blocks;
double scale = getport(3);
sample_t * d = ports[4];
while (frames)
{
double m = rms.rms();
m = filter.process (m + normal);
/* Leaving debug output in your code is cheesy! */
/*
static int _turn = 0;
if (_turn++ % 100 == 0)
fprintf (stderr, "%.4f\n", m);
*/
m *= scale * .08;
svf.set_f_Q (max (.001, f + m), Q);
int n = std::min<int> (frames, BLOCK_SIZE);
for (int i = 0; i < n; ++i)
{
sample_t x = s[i] + normal;
/* A stacked SVF in bandpass mode is rather quiet, which is
* compensated here */
F (d, i, 2 * svf.process (x), adding_gain);
/* for envelope calculation, prefer high f content */
x = hp.process (x);
rms.store (x * x);
}
s += n;
d += n;
frames -= n;
f += df;
Q += dQ;
normal = -normal;
}
f = getport(1) / fs;
Q = getport(2);
}
/* //////////////////////////////////////////////////////////////////////// */
PortInfo
AutoWah::port_info [] =
{
{
"in",
INPUT | AUDIO,
{0, 0, 0}
}, {
"f",
INPUT | CONTROL,
{BOUNDED | LOG | DEFAULT_LOW, 43, 933}
}, {
"Q",
INPUT | CONTROL,
{BOUNDED | DEFAULT_LOW, 0.001, .999}
}, {
"depth",
INPUT | CONTROL,
{BOUNDED | DEFAULT_MID, 0, 1}
}, {
"out",
OUTPUT | AUDIO,
{0}
}
};
template <> void
Descriptor<AutoWah>::setup()
{
UniqueID = 2593;
Label = "AutoWah";
Properties = HARD_RT;
Name = CAPS "AutoWah - Resonant envelope-following filter";
Maker = "Tim Goetze <tim@quitte.de>";
Copyright = "GPL, 2004-7";
/* fill port info and vtable */
autogen();
}
| 8,754
|
C++
|
.cc
| 371
| 21.008086
| 78
| 0.594278
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
20,016
|
StereoEnhancer.h
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancer.h
|
/*
* StereoEnhancer.h - stereo-enhancer-effect-plugin
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREO_ENHANCER_H
#define _STEREO_ENHANCER_H
#include "Effect.h"
#include "DspEffectLibrary.h"
#include "StereoEnhancerControls.h"
namespace lmms
{
class StereoEnhancerEffect : public Effect
{
public:
StereoEnhancerEffect( Model * parent,
const Descriptor::SubPluginFeatures::Key * _key );
~StereoEnhancerEffect() override;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls * controls() override
{
return( &m_bbControls );
}
void clearMyBuffer();
private:
DspEffectLibrary::StereoEnhancer m_seFX;
SampleFrame* m_delayBuffer;
int m_currFrame;
StereoEnhancerControls m_bbControls;
friend class StereoEnhancerControls;
} ;
} // namespace lmms
#endif
| 1,681
|
C++
|
.h
| 51
| 30.431373
| 77
| 0.766605
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,017
|
StereoEnhancerControls.h
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancerControls.h
|
/*
* StereoEnhancerControls.h - controls for StereoEnhancer effect
*
* Copyright (c) 2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREO_ENHANCER_CONTROLS_H
#define _STEREO_ENHANCER_CONTROLS_H
#include "EffectControls.h"
#include "StereoEnhancerControlDialog.h"
namespace lmms
{
class StereoEnhancerEffect;
class StereoEnhancerControls : public EffectControls
{
Q_OBJECT
public:
StereoEnhancerControls( StereoEnhancerEffect( * _eff ) );
~StereoEnhancerControls() override = default;
void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override;
void loadSettings( const QDomElement & _this ) override;
inline QString nodeName() const override
{
return( "stereoenhancercontrols" );
}
int controlCount() override
{
return( 1 );
}
gui::EffectControlDialog* createView() override
{
return new gui::StereoEnhancerControlDialog( this );
}
private slots:
void changeWideCoeff();
private:
StereoEnhancerEffect * m_effect;
FloatModel m_widthModel;
friend class gui::StereoEnhancerControlDialog;
} ;
} // namespace lmms
#endif /*_STEREO_ENHANCER_CONTROLS_H*/
| 1,924
|
C++
|
.h
| 59
| 30.457627
| 74
| 0.776152
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,018
|
StereoEnhancerControlDialog.h
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancerControlDialog.h
|
/*
* StereoEnhancerControlDialog.h - control-dialog for stereo-enhancer effect
*
* Copyright (c) 2006 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREOENHANCER_CONTROL_DIALOG_H
#define _STEREOENHANCER_CONTROL_DIALOG_H
#include "EffectControlDialog.h"
namespace lmms
{
class StereoEnhancerControls;
namespace gui
{
class StereoEnhancerControlDialog : public EffectControlDialog
{
Q_OBJECT
public:
StereoEnhancerControlDialog( StereoEnhancerControls * _controls );
~StereoEnhancerControlDialog() override = default;
};
} // namespace gui
} // namespace lmms
#endif
| 1,393
|
C++
|
.h
| 41
| 32.04878
| 76
| 0.783582
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,019
|
NineButtonSelector.h
|
LMMS_lmms/plugins/Vibed/NineButtonSelector.h
|
/*
* NineButtonSelector.h
*
* Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
* Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_GUI_NINE_BUTTON_SELECTOR_H
#define LMMS_GUI_NINE_BUTTON_SELECTOR_H
#include <array>
#include <memory>
#include <QWidget>
#include "AutomatableModelView.h"
#include "PixmapButton.h"
namespace lmms
{
namespace gui
{
class NineButtonSelector : public QWidget, public IntModelView
{
Q_OBJECT
public:
NineButtonSelector(std::array<QPixmap, 18> onOffIcons, int defaultButton, int x, int y, QWidget* parent);
~NineButtonSelector() override = default;
protected:
void setSelected(int newButton);
public slots:
void buttonClicked(int id);
void contextMenuEvent(QContextMenuEvent*) override;
signals:
void NineButtonSelection(int);
private:
void modelChanged() override;
void updateButton(int);
std::array<std::unique_ptr<PixmapButton>, 9> m_buttons;
PixmapButton* m_lastBtn;
};
} // namespace gui
using NineButtonSelectorModel = IntModel;
} // namespace lmms
#endif // LMMS_GUI_NINE_BUTTON_SELECTOR_H
| 1,895
|
C++
|
.h
| 58
| 30.758621
| 106
| 0.777228
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,020
|
Vibed.h
|
LMMS_lmms/plugins/Vibed/Vibed.h
|
/*
* Vibed.h - combination of PluckedStringSynth and BitInvader
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_VIBED_H
#define LMMS_VIBED_H
#include "Instrument.h"
#include "InstrumentView.h"
#include "NineButtonSelector.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "Graph.h"
#include "PixmapButton.h"
#include <array>
#include <memory>
namespace lmms
{
class NotePlayHandle;
class graphModel;
namespace gui
{
class Graph;
class LedCheckBox;
class VibedView;
}
class Vibed : public Instrument
{
Q_OBJECT
public:
Vibed(InstrumentTrack* instrumentTrack);
~Vibed() override = default;
void playNote(NotePlayHandle* n, SampleFrame* workingBuffer) override;
void deleteNotePluginData(NotePlayHandle* n) override;
void saveSettings(QDomDocument& doc, QDomElement& elem) override;
void loadSettings(const QDomElement& elem) override;
QString nodeName() const override;
gui::PluginView* instantiateView(QWidget* parent) override;
private:
class StringContainer;
static constexpr int s_sampleLength = 128;
static constexpr int s_stringCount = 9;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_pickModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_pickupModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_stiffnessModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_volumeModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_panModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_detuneModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_randomModels;
std::array<std::unique_ptr<FloatModel>, s_stringCount> m_lengthModels;
std::array<std::unique_ptr<BoolModel>, s_stringCount> m_powerModels;
std::array<std::unique_ptr<graphModel>, s_stringCount> m_graphModels;
std::array<std::unique_ptr<BoolModel>, s_stringCount> m_impulseModels;
std::array<std::unique_ptr<NineButtonSelectorModel>, s_stringCount> m_harmonicModels;
friend class gui::VibedView;
};
namespace gui
{
class VibedView : public InstrumentViewFixedSize
{
Q_OBJECT
public:
VibedView(Instrument* instrument, QWidget* parent);
~VibedView() override = default;
public slots:
void showString(int str);
void contextMenuEvent(QContextMenuEvent*) override;
protected slots:
void sinWaveClicked();
void triangleWaveClicked();
void sawWaveClicked();
void sqrWaveClicked();
void noiseWaveClicked();
void usrWaveClicked();
void smoothClicked();
void normalizeClicked();
private:
void modelChanged() override;
// String-related
Knob m_volumeKnob;
Knob m_stiffnessKnob;
Knob m_pickKnob;
Knob m_pickupKnob;
Knob m_panKnob;
Knob m_detuneKnob;
Knob m_randomKnob;
Knob m_lengthKnob;
Graph m_graph;
LedCheckBox m_impulse;
LedCheckBox m_power;
std::unique_ptr<NineButtonSelector> m_harmonic;
// Not in model
std::unique_ptr<NineButtonSelector> m_stringSelector;
PixmapButton m_smoothBtn;
PixmapButton m_normalizeBtn;
// From impulse editor
PixmapButton m_sinWaveBtn;
PixmapButton m_triangleWaveBtn;
PixmapButton m_sawWaveBtn;
PixmapButton m_sqrWaveBtn;
PixmapButton m_whiteNoiseWaveBtn;
PixmapButton m_usrWaveBtn;
};
} // namespace gui
} // namespace lmms
#endif // LMMS_VIBED_H
| 4,032
|
C++
|
.h
| 124
| 30.58871
| 86
| 0.788809
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,021
|
VibratingString.h
|
LMMS_lmms/plugins/Vibed/VibratingString.h
|
/*
* VibratingString.h - model of a vibrating string lifted from pluckedSynth
*
* Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_VIBRATING_STRING_H
#define LMMS_VIBRATING_STRING_H
#include <memory>
#include <cstdlib>
#include "lmms_basics.h"
namespace lmms
{
class VibratingString
{
public:
VibratingString() = default;
VibratingString(float pitch, float pick, float pickup, const float* impulse, int len,
sample_rate_t sampleRate, int oversample, float randomize, float stringLoss, float detune, bool state);
~VibratingString() = default;
VibratingString(const VibratingString&) = delete;
VibratingString& operator=(const VibratingString&) = delete;
VibratingString(VibratingString&&) noexcept = delete;
VibratingString& operator=(VibratingString&&) noexcept = default;
sample_t nextSample()
{
for (int i = 0; i < m_oversample; ++i)
{
// Output at pickup position
m_outsamp[i] = fromBridgeAccess(m_fromBridge.get(), m_pickupLoc);
m_outsamp[i] += toBridgeAccess(m_toBridge.get(), m_pickupLoc);
// Sample traveling into "bridge"
sample_t ym0 = toBridgeAccess(m_toBridge.get(), 1);
// Sample to "nut"
sample_t ypM = fromBridgeAccess(m_fromBridge.get(), m_fromBridge->length - 2);
// String state update
// Decrement pointer and then update
fromBridgeUpdate(m_fromBridge.get(), -bridgeReflection(ym0));
// Update and then increment pointer
toBridgeUpdate(m_toBridge.get(), -ypM);
}
return m_outsamp[m_choice];
}
private:
struct DelayLine
{
std::unique_ptr<sample_t[]> data;
int length;
sample_t* pointer;
sample_t* end;
};
std::unique_ptr<DelayLine> m_fromBridge;
std::unique_ptr<DelayLine> m_toBridge;
int m_pickupLoc;
int m_oversample;
float m_randomize;
float m_stringLoss;
std::unique_ptr<float[]> m_impulse;
int m_choice;
float m_state;
std::unique_ptr<sample_t[]> m_outsamp;
std::unique_ptr<DelayLine> initDelayLine(int len);
void resample(const float* src, f_cnt_t srcFrames, f_cnt_t dstFrames);
/**
* setDelayLine initializes the string with an impulse at the pick
* position unless the impulse is longer than the string, in which
* case the impulse gets truncated.
*/
void setDelayLine(DelayLine* dl, int pick, const float* values, int len, float scale, bool state)
{
if (!state)
{
for (int i = 0; i < pick; ++i)
{
float r = static_cast<float>(std::rand()) / RAND_MAX;
float offset = (m_randomize / 2.0f - m_randomize) * r;
dl->data[i] = scale * values[dl->length - i - 1] + offset;
}
for (int i = pick; i < dl->length; ++i)
{
float r = static_cast<float>(std::rand()) / RAND_MAX;
float offset = (m_randomize / 2.0f - m_randomize) * r;
dl->data[i] = scale * values[i - pick] + offset;
}
}
else
{
if (len + pick > dl->length)
{
for (int i = pick; i < dl->length; ++i)
{
float r = static_cast<float>(std::rand()) / RAND_MAX;
float offset = (m_randomize / 2.0f - m_randomize) * r;
dl->data[i] = scale * values[i - pick] + offset;
}
}
else
{
for (int i = 0; i < len; ++i)
{
float r = static_cast<float>(std::rand()) / RAND_MAX;
float offset = (m_randomize / 2.0f - m_randomize) * r;
dl->data[i+pick] = scale * values[i] + offset;
}
}
}
}
/**
* toBridgeUpdate(dl, insamp);
* Places "nut-reflected" sample from upper delay-line into
* current lower delay-line pointer position (which represents
* x = 0 position). The pointer is then incremented (i.e. the
* wave travels one sample to the left), turning the previous
* position into an "effective" x = L position for the next
* iteration.
*/
void toBridgeUpdate(DelayLine* dl, sample_t insamp)
{
sample_t* ptr = dl->pointer;
*ptr = insamp * m_stringLoss;
++ptr;
if (ptr > dl->end)
{
ptr = dl->data.get();
}
dl->pointer = ptr;
}
/**
* fromBridgeUpdate(dl, insamp);
* Decrements current upper delay-line pointer position (i.e.
* the wave travels one sample to the right), moving it to the
* "effective" x = 0 position for the next iteration. The
* "bridge-reflected" sample from lower delay-line is then placed
* into this position.
*/
void fromBridgeUpdate(DelayLine* dl, sample_t insamp)
{
sample_t* ptr = dl->pointer;
--ptr;
if (ptr < dl->data.get())
{
ptr = dl->end;
}
*ptr = insamp * m_stringLoss;
dl->pointer = ptr;
}
/**
* dlAccess(dl, position);
* Returns sample "position" samples into delay-line's past.
* Position "0" points to the most recently inserted sample.
*/
static sample_t dlAccess(DelayLine* dl, int position)
{
sample_t* outpos = dl->pointer + position;
while (outpos < dl->data.get())
{
outpos += dl->length;
}
while (outpos > dl->end)
{
outpos -= dl->length;
}
return *outpos;
}
/*
* Right-going delay line:
* -->---->---->---
* x=0
* (pointer)
* Left-going delay line:
* --<----<----<---
* x=0
* (pointer)
*/
/**
* fromBridgeAccess(dl, position);
* Returns spatial sample at position "position", where position zero
* is equal to the current upper delay-line pointer position (x = 0).
* In a right-going delay-line, position increases to the right, and
* delay increases to the right => left = past and right = future.
*/
static sample_t fromBridgeAccess(DelayLine* dl, int position)
{
return dlAccess(dl, position);
}
/**
* toBridgeAccess(dl, position);
* Returns spatial sample at position "position", where position zero
* is equal to the current lower delay-line pointer position (x = 0).
* In a left-going delay-line, position increases to the right, and
* delay DEcreases to the right => left = future and right = past.
*/
static sample_t toBridgeAccess(DelayLine* dl, int position)
{
return dlAccess(dl, position);
}
sample_t bridgeReflection(sample_t insamp)
{
m_state = (m_state + insamp) * 0.5;
return m_state;
}
};
} // namespace lmms
#endif // LMMS_VIBRATING_STRING_H
| 6,790
|
C++
|
.h
| 221
| 27.755656
| 105
| 0.686287
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,022
|
StereoMatrixControlDialog.h
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrixControlDialog.h
|
/*
* StereoMatrixControlDialog.h - control dialog for StereoMatrix effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREOMATRIX_CONTROL_DIALOG_H
#define _STEREOMATRIX_CONTROL_DIALOG_H
#include "EffectControlDialog.h"
namespace lmms
{
class StereoMatrixControls;
namespace gui
{
class StereoMatrixControlDialog : public EffectControlDialog
{
Q_OBJECT
public:
StereoMatrixControlDialog( StereoMatrixControls * _controls );
~StereoMatrixControlDialog() override = default;
};
} // namespace gui
} // namespace lmms
#endif
| 1,363
|
C++
|
.h
| 41
| 31.317073
| 71
| 0.779389
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,023
|
StereoMatrixControls.h
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrixControls.h
|
/*
* StereoMatrixControls.h - controls for StereoMatrix effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREO_MATRIX_CONTROLS_H
#define _STEREO_MATRIX_CONTROLS_H
#include "EffectControls.h"
#include "StereoMatrixControlDialog.h"
namespace lmms
{
class StereoMatrixEffect;
class StereoMatrixControls : public EffectControls
{
Q_OBJECT
public:
StereoMatrixControls( StereoMatrixEffect( * _eff ) );
~StereoMatrixControls() override = default;
void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override;
void loadSettings( const QDomElement & _this ) override;
inline QString nodeName() const override
{
return( "stereomatrixcontrols" );
}
int controlCount() override
{
return( 1 );
}
gui::EffectControlDialog* createView() override
{
return new gui::StereoMatrixControlDialog( this );
}
private slots:
void changeMatrix();
private:
StereoMatrixEffect * m_effect;
FloatModel m_llModel;
FloatModel m_lrModel;
FloatModel m_rlModel;
FloatModel m_rrModel;
friend class gui::StereoMatrixControlDialog;
friend class StereoMatrixEffect;
} ;
} // namespace lmms
#endif
| 1,952
|
C++
|
.h
| 63
| 28.809524
| 74
| 0.774625
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,024
|
StereoMatrix.h
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrix.h
|
/*
* StereoMatrix.h - stereo-matrix-effect-plugin
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _STEREO_MATRIX_H
#define _STEREO_MATRIX_H
#include "Effect.h"
#include "StereoMatrixControls.h"
namespace lmms
{
class StereoMatrixEffect : public Effect
{
public:
StereoMatrixEffect( Model * parent,
const Descriptor::SubPluginFeatures::Key * _key );
~StereoMatrixEffect() override = default;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls* controls() override
{
return( &m_smControls );
}
private:
StereoMatrixControls m_smControls;
friend class StereoMatrixControls;
} ;
} // namespace lmms
#endif
| 1,509
|
C++
|
.h
| 46
| 30.26087
| 74
| 0.755694
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,025
|
AudioFileProcessorView.h
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessorView.h
|
/*
* AudioFileProcessorView.h - View of the AFP
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_AUDIO_FILE_PROCESSOR_VIEW_H
#define LMMS_AUDIO_FILE_PROCESSOR_VIEW_H
#include "InstrumentView.h"
namespace lmms
{
namespace gui
{
class automatableButtonGroup;
class Knob;
class PixmapButton;
class ComboBox;
class AudioFileProcessorWaveView;
class AudioFileProcessorView : public gui::InstrumentViewFixedSize
{
Q_OBJECT
public:
AudioFileProcessorView(Instrument* instrument, QWidget* parent);
virtual ~AudioFileProcessorView() = default;
void newWaveView();
protected slots:
void sampleUpdated();
void openAudioFile();
protected:
virtual void dragEnterEvent(QDragEnterEvent* dee);
virtual void dropEvent(QDropEvent* de);
virtual void paintEvent(QPaintEvent*);
// Private methods
private:
virtual void modelChanged();
// Private members
private:
AudioFileProcessorWaveView* m_waveView;
Knob* m_ampKnob;
Knob* m_startKnob;
Knob* m_endKnob;
Knob* m_loopKnob;
gui::PixmapButton* m_openAudioFileButton;
PixmapButton* m_reverseButton;
automatableButtonGroup* m_loopGroup;
PixmapButton* m_stutterButton;
ComboBox* m_interpBox;
} ;
} // namespace gui
} // namespace lmms
#endif // LMMS_AUDIO_FILE_PROCESSOR_VIEW_H
| 2,082
|
C++
|
.h
| 68
| 28.720588
| 77
| 0.789184
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,026
|
AudioFileProcessorWaveView.h
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessorWaveView.h
|
/*
* AudioFileProcessorWaveView.h - Wave renderer of the AFP
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_AUDIO_FILE_PROCESSOR_WAVE_VIEW_H
#define LMMS_AUDIO_FILE_PROCESSOR_WAVE_VIEW_H
#include "Knob.h"
namespace lmms
{
class Sample;
namespace gui
{
class AudioFileProcessorView;
class AudioFileProcessorWaveView : public QWidget
{
Q_OBJECT
protected:
virtual void enterEvent(QEvent* e);
virtual void leaveEvent(QEvent* e);
virtual void mousePressEvent(QMouseEvent* me);
virtual void mouseReleaseEvent(QMouseEvent* me);
virtual void mouseMoveEvent(QMouseEvent* me);
virtual void wheelEvent(QWheelEvent* we);
virtual void paintEvent(QPaintEvent* pe);
public:
enum class Point
{
Start,
End,
Loop
} ;
class knob : public Knob
{
const AudioFileProcessorWaveView* m_waveView;
const Knob* m_relatedKnob;
public:
knob(QWidget* parent) :
Knob(KnobType::Bright26, parent),
m_waveView(0),
m_relatedKnob(0)
{
setFixedSize(37, 47);
}
void setWaveView(const AudioFileProcessorWaveView* wv)
{
m_waveView = wv;
}
void setRelatedKnob(const Knob* knob)
{
m_relatedKnob = knob;
}
void slideBy(double v, bool check_bound = true)
{
slideTo(model()->value() + v, check_bound);
}
void slideTo(double v, bool check_bound = true);
protected:
float getValue(const QPoint & p);
private:
bool checkBound(double v) const;
} ;
public slots:
void update()
{
updateGraph();
QWidget::update();
}
void isPlaying(lmms::f_cnt_t current_frame);
private:
static const int s_padding = 2;
enum class DraggingType
{
Wave,
SlideWave,
ZoomWave,
SampleStart,
SampleEnd,
SampleLoop
} ;
Sample const* m_sample;
QPixmap m_graph;
int m_from;
int m_to;
int m_last_from;
int m_last_to;
float m_last_amp;
knob* m_startKnob;
knob* m_endKnob;
knob* m_loopKnob;
int m_startFrameX;
int m_endFrameX;
int m_loopFrameX;
bool m_isDragging;
QPoint m_draggingLastPoint;
DraggingType m_draggingType;
bool m_reversed;
f_cnt_t m_framesPlayed;
bool m_animation;
friend class AudioFileProcessorView;
public:
AudioFileProcessorWaveView(QWidget* parent, int w, int h, Sample const* buf,
knob* start, knob* end, knob* loop);
void updateSampleRange();
private:
void setTo(int to);
void setFrom(int from);
int range() const;
void zoom(const bool out = false);
void slide(int px);
void slideSamplePointByPx(Point point, int px);
void slideSamplePointByFrames(Point point, long frameOffset, bool slideTo = false);
void slideSampleByFrames(long frameOffset);
void slideSamplePointToFrames(Point point, f_cnt_t frames)
{
slideSamplePointByFrames(point, frames, true);
}
void updateGraph();
void reverse();
void updateCursor(QMouseEvent* me = nullptr);
void configureKnobRelationsAndWaveViews();
static bool isCloseTo(int a, int b)
{
return qAbs(a - b) < 4;
}
} ;
} // namespace gui
} // namespace lmms
#endif // LMMS_AUDIO_FILE_PROCESSOR_WAVE_VIEW_H
| 3,809
|
C++
|
.h
| 147
| 23.47619
| 84
| 0.755869
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,027
|
AudioFileProcessor.h
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessor.h
|
/*
* AudioFileProcessor.h - declaration of class AudioFileProcessor
* (instrument-plugin for using audio-files)
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_AUDIO_FILE_PROCESSOR_H
#define LMMS_AUDIO_FILE_PROCESSOR_H
#include "AutomatableModel.h"
#include "ComboBoxModel.h"
#include "Instrument.h"
#include "Sample.h"
#include "lmms_basics.h"
namespace lmms
{
class AudioFileProcessor : public Instrument
{
Q_OBJECT
public:
AudioFileProcessor( InstrumentTrack * _instrument_track );
void playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer ) override;
void deleteNotePluginData( NotePlayHandle * _n ) override;
void saveSettings(QDomDocument& doc, QDomElement& elem) override;
void loadSettings(const QDomElement& elem) override;
void loadFile( const QString & _file ) override;
QString nodeName() const override;
auto beatLen(NotePlayHandle* note) const -> f_cnt_t override;
float desiredReleaseTimeMs() const override
{
return 3.f;
}
gui::PluginView* instantiateView( QWidget * _parent ) override;
Sample const & sample() const { return m_sample; }
FloatModel & ampModel() { return m_ampModel; }
FloatModel & startPointModel() { return m_startPointModel; }
FloatModel & endPointModel() { return m_endPointModel; }
FloatModel & loopPointModel() { return m_loopPointModel; }
BoolModel & reverseModel() { return m_reverseModel; }
IntModel & loopModel() { return m_loopModel; }
BoolModel & stutterModel() { return m_stutterModel; }
ComboBoxModel & interpolationModel() { return m_interpolationModel; }
public slots:
void setAudioFile(const QString& _audio_file, bool _rename = true);
private slots:
void reverseModelChanged();
void ampModelChanged();
void loopPointChanged();
void startPointChanged();
void endPointChanged();
void pointChanged();
void stutterModelChanged();
signals:
void isPlaying( lmms::f_cnt_t _current_frame );
void sampleUpdated();
private:
Sample m_sample;
FloatModel m_ampModel;
FloatModel m_startPointModel;
FloatModel m_endPointModel;
FloatModel m_loopPointModel;
BoolModel m_reverseModel;
IntModel m_loopModel;
BoolModel m_stutterModel;
ComboBoxModel m_interpolationModel;
f_cnt_t m_nextPlayStartPoint;
bool m_nextPlayBackwards;
} ;
} // namespace lmms
#endif // LMMS_AUDIO_FILE_PROCESSOR_H
| 3,170
|
C++
|
.h
| 88
| 33.886364
| 77
| 0.768652
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,028
|
PeakControllerEffectControls.h
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffectControls.h
|
/*
* peak_controller_EffectControls.h - controls for peakController effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
* Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _PEAK_CONTROLLER_EFFECT_CONTROLS_H
#define _PEAK_CONTROLLER_EFFECT_CONTROLS_H
#include "EffectControls.h"
#include "PeakControllerEffectControlDialog.h"
namespace lmms
{
class PeakControllerEffect;
class PeakControllerEffectControls : public EffectControls
{
Q_OBJECT
public:
PeakControllerEffectControls( PeakControllerEffect * _eff );
~PeakControllerEffectControls() override = default;
void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override;
void loadSettings( const QDomElement & _this ) override;
inline QString nodeName() const override
{
return "peakcontrollereffectcontrols";
}
int controlCount() override
{
return 1;
}
gui::EffectControlDialog * createView() override
{
return new gui::PeakControllerEffectControlDialog( this );
}
private:
PeakControllerEffect * m_effect;
FloatModel m_baseModel;
FloatModel m_amountModel;
FloatModel m_attackModel;
FloatModel m_decayModel;
FloatModel m_tresholdModel;
BoolModel m_muteModel;
BoolModel m_absModel;
FloatModel m_amountMultModel;
friend class gui::PeakControllerEffectControlDialog;
friend class PeakControllerEffect;
} ;
} // namespace lmms
#endif
| 2,187
|
C++
|
.h
| 66
| 31.060606
| 74
| 0.79135
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,029
|
PeakControllerEffect.h
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffect.h
|
/*
* peak_controller_Effect.h - PeakController effect plugin
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef PEAK_CONTROLLER_EFFECT_H
#define PEAK_CONTROLLER_EFFECT_H
#include "Effect.h"
#include "PeakControllerEffectControls.h"
namespace lmms
{
class PeakController;
class PeakControllerEffect : public Effect
{
public:
PeakControllerEffect( Model * parent,
const Descriptor::SubPluginFeatures::Key * _key );
~PeakControllerEffect() override;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls * controls() override
{
return &m_peakControls;
}
float lastSample()
{
return m_lastSample;
}
PeakController * controller()
{
return m_autoController;
}
FloatModel * attackModel()
{
return &( m_peakControls.m_attackModel );
}
FloatModel * decayModel()
{
return &( m_peakControls.m_decayModel );
}
int m_effectId;
private:
PeakControllerEffectControls m_peakControls;
float m_lastSample;
PeakController * m_autoController;
friend class PeakControllerEffectControls;
} ;
} // namespace lmms
#endif
| 1,913
|
C++
|
.h
| 66
| 26.681818
| 74
| 0.769189
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,030
|
PeakControllerEffectControlDialog.h
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffectControlDialog.h
|
/*
* peak_controller_EffectControlDialog.h - control dialog for
* peakControllerEffect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _PEAK_CONTROLLER_EFFECT_CONTROL_DIALOG_H
#define _PEAK_CONTROLLER_EFFECT_CONTROL_DIALOG_H
#include "EffectControlDialog.h"
namespace lmms
{
class PeakControllerEffectControls;
namespace gui
{
class Knob;
class LedCheckBox;
class PeakControllerEffectControlDialog : public EffectControlDialog
{
Q_OBJECT
public:
PeakControllerEffectControlDialog(
PeakControllerEffectControls * _controls );
~PeakControllerEffectControlDialog() override = default;
protected:
Knob * m_baseKnob;
Knob * m_amountKnob;
Knob * m_attackKnob;
Knob * m_decayKnob;
Knob * m_tresholdKnob;
LedCheckBox * m_muteLed;
LedCheckBox * m_absLed;
Knob * m_amountMultKnob;
} ;
} // namespace gui
} // namespace lmms
#endif
| 1,714
|
C++
|
.h
| 54
| 29.759259
| 70
| 0.760024
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,031
|
BassBoosterControlDialog.h
|
LMMS_lmms/plugins/BassBooster/BassBoosterControlDialog.h
|
/*
* BassBoosterControlDialog.h - control dialog for bassbooster effect
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _BASSBOOSTER_CONTROL_DIALOG_H
#define _BASSBOOSTER_CONTROL_DIALOG_H
#include "EffectControlDialog.h"
namespace lmms
{
class BassBoosterControls;
namespace gui
{
class BassBoosterControlDialog : public EffectControlDialog
{
Q_OBJECT
public:
BassBoosterControlDialog( BassBoosterControls* controls );
~BassBoosterControlDialog() override = default;
} ;
} // namespace gui
} // namespace lmms
#endif
| 1,367
|
C++
|
.h
| 41
| 31.463415
| 77
| 0.780989
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,032
|
BassBoosterControls.h
|
LMMS_lmms/plugins/BassBooster/BassBoosterControls.h
|
/*
* BassBoosterControls.h - controls for bassboosterx -effect
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef BASSBOOSTER_CONTROLS_H
#define BASSBOOSTER_CONTROLS_H
#include "EffectControls.h"
#include "BassBoosterControlDialog.h"
namespace lmms
{
class BassBoosterEffect;
class BassBoosterControls : public EffectControls
{
Q_OBJECT
public:
BassBoosterControls( BassBoosterEffect* effect );
~BassBoosterControls() override = default;
void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override;
void loadSettings( const QDomElement & _this ) override;
inline QString nodeName() const override
{
return "bassboostercontrols";
}
int controlCount() override
{
return 3;
}
gui::EffectControlDialog* createView() override
{
return new gui::BassBoosterControlDialog( this );
}
private slots:
void changeFrequency();
private:
BassBoosterEffect* m_effect;
FloatModel m_freqModel;
FloatModel m_gainModel;
FloatModel m_ratioModel;
friend class gui::BassBoosterControlDialog;
friend class BassBoosterEffect;
} ;
} // namespace lmms
#endif
| 1,921
|
C++
|
.h
| 62
| 28.935484
| 77
| 0.782963
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
20,033
|
BassBooster.h
|
LMMS_lmms/plugins/BassBooster/BassBooster.h
|
/*
* BassBooster.h - bass-booster-effect-plugin
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef BASS_BOOSTER_H
#define BASS_BOOSTER_H
#include "Effect.h"
#include "DspEffectLibrary.h"
#include "BassBoosterControls.h"
namespace lmms
{
class BassBoosterEffect : public Effect
{
public:
BassBoosterEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key );
~BassBoosterEffect() override = default;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls* controls() override
{
return &m_bbControls;
}
protected:
void changeFrequency();
void changeGain();
void changeRatio();
bool m_frequencyChangeNeeded;
private:
DspEffectLibrary::MonoToStereoAdaptor<DspEffectLibrary::FastBassBoost> m_bbFX;
BassBoosterControls m_bbControls;
friend class BassBoosterControls;
} ;
} // namespace lmms
#endif
| 1,703
|
C++
|
.h
| 52
| 30.711538
| 83
| 0.780906
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
20,034
|
Carla.h
|
LMMS_lmms/plugins/CarlaBase/Carla.h
|
/*
* carla.h - Carla for LMMS
*
* Copyright (C) 2014-2018 Filipe Coelho <falktx@falktx.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef CARLA_H
#define CARLA_H
#define CARLA_SETTING_PREFIX "PARAM_KNOB_"
#define CARLA_MIN_PARAM_VERSION 0x020090
#define CARLA_VERSION_HEX_3 0x30000
#include <vector>
// qt
#include <QCloseEvent>
#include <QDomElement>
#include <QMutex>
#include <QRegularExpression>
// carla/source/includes
#include "carlabase_export.h"
#include <CarlaDefines.h>
#if CARLA_VERSION_HEX >= 0x010911
#include <CarlaNativePlugin.h>
#else
#include <CarlaBackend.h>
#include <CarlaNative.h>
#include <CarlaUtils.h>
CARLA_EXPORT
const NativePluginDescriptor* carla_get_native_patchbay_plugin();
CARLA_EXPORT
const NativePluginDescriptor* carla_get_native_rack_plugin();
#endif
// lmms/include/
#include "AutomatableModel.h"
#include "Instrument.h"
#include "InstrumentView.h"
#include "SubWindow.h"
class QPushButton;
class QComboBox;
class QCompleter;
class QGridLayout;
class QHBoxLayout;
class QLineEdit;
class QStringListModel;
class QScrollArea;
namespace lmms
{
namespace gui
{
class CarlaParamsView;
class CarlaInstrumentView;
class Knob;
}
class CarlaParamFloatModel : public FloatModel
{
public:
CarlaParamFloatModel(Model * parent):
FloatModel(0.f, 0.f, 1.f, 0.001f, parent, "Unused"),
m_isOutput(false),
m_isEnabled(false)
{
}
// From AutomatableModel.h, it's private there.
inline static bool mustQuoteName(const QString &name)
{
QRegularExpression reg("^[A-Za-z0-9._-]+$");
return !reg.match(name).hasMatch();
}
inline void loadSettings(const QDomElement& element, const QString& name = QString("value")) override
{
AutomatableModel::loadSettings(element, name);
bool mustQuote = mustQuoteName(name);
QDomElement me = element.firstChildElement(mustQuote ? QString("automatablemodel") : name);
if (!me.isNull()) {
m_isOutput = (bool)me.attribute("output", "0").toInt();
m_groupName = QString(me.attribute("groupName", ""));
}
}
inline void saveSettings(QDomDocument& doc, QDomElement& element,
const QString& name = QString( "value" )) override
{
if (m_isEnabled)
{
AutomatableModel::saveSettings(doc, element, name);
bool mustQuote = mustQuoteName(name);
QDomElement me = element.firstChildElement(mustQuote ? QString("automatablemodel") : name);
if (!me.isNull())
{
me.setAttribute("output", m_isOutput);
me.setAttribute("groupName", m_groupName);
}
}
}
inline const bool enabled()
{
return m_isEnabled;
}
inline const bool isOutput()
{
return m_isOutput;
}
inline void setOutput(bool state = true)
{
m_isOutput = state;
}
inline void setEnabled(bool state = true)
{
m_isEnabled = state;
}
inline void setGroupName(QString groupName)
{
m_groupName = groupName;
}
inline void setGroupId(uint8_t groupId)
{
m_groupId = groupId;
}
virtual QString groupName() const
{
return m_groupName;
}
virtual uint8_t groupId() const
{
return m_groupId;
}
private:
bool m_isOutput;
bool m_isEnabled;
uint8_t m_groupId;
QString m_groupName;
};
// -------------------------------------------------------------------
class CARLABASE_EXPORT CarlaInstrument : public Instrument
{
Q_OBJECT
public:
static const uint32_t kMaxMidiEvents = 512;
CarlaInstrument(InstrumentTrack* const instrumentTrack, const Descriptor* const descriptor, const bool isPatchbay);
~CarlaInstrument() override;
// Carla NativeHostDescriptor functions
uint32_t handleGetBufferSize() const;
double handleGetSampleRate() const;
bool handleIsOffline() const;
const NativeTimeInfo* handleGetTimeInfo() const;
void handleUiParameterChanged(const uint32_t index, const float value) const;
void handleUiClosed();
intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt);
// LMMS functions
QString nodeName() const override;
void saveSettings(QDomDocument& doc, QDomElement& parent) override;
void loadSettings(const QDomElement& elem) override;
void play(SampleFrame* workingBuffer) override;
bool handleMidiEvent(const MidiEvent& event, const TimePos& time, f_cnt_t offset) override;
gui::PluginView* instantiateView(QWidget* parent) override;
signals:
void uiClosed();
void paramsUpdated();
private slots:
void sampleRateChanged();
void refreshParams(bool init = false);
void clearParamModels();
void paramModelChanged(uint32_t index);
void updateParamModel(uint32_t index);
private:
const bool kIsPatchbay;
NativePluginHandle fHandle;
NativeHostDescriptor fHost;
const NativePluginDescriptor* fDescriptor;
uint32_t fMidiEventCount;
NativeMidiEvent fMidiEvents[kMaxMidiEvents];
NativeTimeInfo fTimeInfo;
// this is only needed because note-offs are being sent during play
QMutex fMutex;
uint8_t m_paramGroupCount;
std::vector<CarlaParamFloatModel*> m_paramModels;
QDomElement m_settingsElem;
QCompleter* m_paramsCompleter;
QStringListModel* m_completerModel;
friend class gui::CarlaInstrumentView;
friend class gui::CarlaParamsView;
};
// -------------------------------------------------------------------
namespace gui
{
class CarlaParamsSubWindow : public SubWindow
{
Q_OBJECT
signals:
void uiClosed();
void resized();
public:
CarlaParamsSubWindow(QWidget * _parent, Qt::WindowFlags windowFlags) :
SubWindow(_parent)
{
setAttribute(Qt::WA_DeleteOnClose, false);
setWindowFlags(windowFlags);
}
void resizeEvent(QResizeEvent * event) override
{
if (mousePress) {
resizing = true;
}
SubWindow::resizeEvent(event);
}
void mousePressEvent(QMouseEvent * event) override
{
mousePress = true;
SubWindow::mousePressEvent(event);
}
void mouseReleaseEvent(QMouseEvent * event) override
{
if (resizing) {
resizing = false;
mousePress = false;
emit resized();
}
SubWindow::mouseReleaseEvent(event);
}
void closeEvent(QCloseEvent * event) override
{
emit uiClosed();
event->accept();
}
private:
bool resizing = false;
bool mousePress = false;
};
// -------------------------------------------------------------------
class CarlaInstrumentView : public InstrumentViewFixedSize
{
Q_OBJECT
public:
CarlaInstrumentView(CarlaInstrument* const instrument, QWidget* const parent);
~CarlaInstrumentView() override;
private slots:
void toggleUI(bool);
void uiClosed();
void toggleParamsWindow();
void paramsUiClosed();
private:
void modelChanged() override;
void timerEvent(QTimerEvent*) override;
NativePluginHandle fHandle;
const NativePluginDescriptor* fDescriptor;
int fTimerId;
CarlaInstrument* const m_carlaInstrument;
QWidget* const m_parent;
QMdiSubWindow* m_paramsSubWindow;
CarlaParamsView* m_paramsView;
QPushButton* m_toggleUIButton;
QPushButton* m_toggleParamsWindowButton;
friend class CarlaParamsView;
};
// -------------------------------------------------------------------
class CarlaParamsView : public InstrumentView
{
Q_OBJECT
public:
CarlaParamsView(CarlaInstrumentView* const instrumentView, QWidget* const parent);
~CarlaParamsView() override;
signals:
void uiClosed();
private slots:
void refreshKnobs();
void filterKnobs();
void clearFilterText();
void windowResized();
private:
void adjustWindowWidth();
void addKnob(uint32_t index);
void clearKnobs();
CarlaInstrument* const m_carlaInstrument;
CarlaInstrumentView* const m_carlaInstrumentView;
std::vector<Knob*> m_knobs;
// Keep track of the biggest knob width per group
QList<uint16_t> m_maxKnobWidthPerGroup;
uint32_t m_maxColumns;
uint32_t m_curColumn;
uint32_t m_curRow;
uint32_t m_curOutColumn;
uint32_t m_curOutRow;
QScrollArea* m_inputScrollArea;
QGridLayout* m_inputScrollAreaLayout;
QWidget* m_inputScrollAreaWidgetContent;
QScrollArea* m_outputScrollArea;
QGridLayout* m_outputScrollAreaLayout;
QWidget* m_outputScrollAreaWidgetContent;
QHBoxLayout* m_toolBarLayout;
QLineEdit* m_paramsFilterLineEdit;
QPushButton* m_clearFilterButton;
QPushButton* m_automatedOnlyButton;
QComboBox* m_groupFilterCombo;
QStringListModel* m_groupFilterModel;
};
} // namespace gui
} // namespace lmms
#endif
| 9,145
|
C++
|
.h
| 313
| 26.370607
| 148
| 0.741409
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,035
|
config.h
|
LMMS_lmms/plugins/CarlaBase/CarlaConfig/config.h
|
// config.h for Carla
#ifndef FOR_CARLA_CONFIG_H
#define FOR_CARLA_CONFIG_H
#ifdef _MSC_VER
#define HAVE_CPP11_SUPPORT 1
#endif
#endif
| 137
|
C++
|
.h
| 7
| 18.285714
| 28
| 0.789063
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,036
|
Mallets.h
|
LMMS_lmms/plugins/Stk/Mallets/Mallets.h
|
/*
* Mallets.h - tuned instruments that one would bang upon
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
*
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef _MALLET_H
#define _MALLET_H
#include <stk/Instrmnt.h>
#include "ComboBox.h"
#include "Instrument.h"
#include "InstrumentView.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "LedCheckBox.h"
// As of Stk 4.4 all classes and types have been moved to the namespace "stk".
// However in older versions this namespace does not exist, therefore declare it
// so this plugin builds with all versions of Stk.
namespace stk { } ;
namespace lmms
{
using namespace stk;
static const int MALLETS_PRESET_VERSION = 1;
namespace gui
{
class MalletsInstrumentView;
} // namespace gui
class MalletsSynth
{
public:
// ModalBar
MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const StkFloat _control1,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control8,
const StkFloat _control11,
const int _control16,
const uint8_t _delay,
const sample_rate_t _sample_rate );
// TubeBell
MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const int _preset,
const StkFloat _control1,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control11,
const StkFloat _control128,
const uint8_t _delay,
const sample_rate_t _sample_rate );
// BandedWG
MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control11,
const int _control16,
const StkFloat _control64,
const StkFloat _control128,
const uint8_t _delay,
const sample_rate_t _sample_rate );
inline ~MalletsSynth()
{
if (m_voice) {m_voice->noteOff(0.0);}
delete[] m_delay;
delete m_voice;
}
inline sample_t nextSampleLeft()
{
if( m_voice == nullptr )
{
return( 0.0f );
}
else
{
StkFloat s = m_voice->tick();
m_delay[m_delayWrite] = s;
m_delayWrite++;
return( s );
}
}
inline sample_t nextSampleRight()
{
StkFloat s = m_delay[m_delayRead];
m_delayRead++;
return( s );
}
inline void setFrequency(const StkFloat _pitch)
{
if (m_voice) { m_voice->setFrequency(_pitch); }
}
// ModalBar updates
inline void setVibratoGain(const StkFloat _control8)
{
// bug in stk, Control Number 8 and 1 swapped in ModalBar
// we send the control number for stick direct mix instead
if (m_voice) { m_voice->controlChange(8, _control8); }
}
inline void setVibratoFreq(const StkFloat _control11)
{
if (m_voice) { m_voice->controlChange(11, _control11); }
}
// Tubular Bells updates
inline void setADSR(const StkFloat _control128)
{
if (m_voice) { m_voice->controlChange(128, _control128); }
}
inline void setLFODepth(const StkFloat _control1)
{
if (m_voice) { m_voice->controlChange(1, _control1); }
}
inline void setLFOSpeed(const StkFloat _control11)
{
if (m_voice) { m_voice->controlChange(11, _control11); }
}
inline int presetIndex()
{
return m_presetIndex;
}
inline void setPresetIndex(int presetIndex)
{
m_presetIndex = presetIndex;
}
protected:
int m_presetIndex;
Instrmnt * m_voice;
StkFloat * m_delay;
uint8_t m_delayRead;
uint8_t m_delayWrite;
};
class MalletsInstrument : public Instrument
{
Q_OBJECT
public:
MalletsInstrument( InstrumentTrack * _instrument_track );
~MalletsInstrument() override = default;
void playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer ) override;
void deleteNotePluginData( NotePlayHandle * _n ) override;
void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override;
void loadSettings( const QDomElement & _this ) override;
QString nodeName() const override;
gui::PluginView* instantiateView( QWidget * _parent ) override;
private:
FloatModel m_hardnessModel;
FloatModel m_positionModel;
FloatModel m_vibratoGainModel;
FloatModel m_vibratoFreqModel;
FloatModel m_stickModel;
FloatModel m_modulatorModel;
FloatModel m_crossfadeModel;
FloatModel m_lfoSpeedModel;
FloatModel m_lfoDepthModel;
FloatModel m_adsrModel;
FloatModel m_pressureModel;
FloatModel m_motionModel;
FloatModel m_vibratoModel;
FloatModel m_velocityModel;
BoolModel m_strikeModel;
ComboBoxModel m_presetsModel;
FloatModel m_spreadModel;
FloatModel m_randomModel;
IntModel m_versionModel;
BoolModel m_isOldVersionModel;
QVector<sample_t> m_scalers;
bool m_filesMissing;
friend class gui::MalletsInstrumentView;
} ;
namespace gui
{
class MalletsInstrumentView: public InstrumentViewFixedSize
{
Q_OBJECT
public:
MalletsInstrumentView( MalletsInstrument * _instrument,
QWidget * _parent );
~MalletsInstrumentView() override = default;
public slots:
void changePreset();
private:
void modelChanged() override;
void setWidgetBackground( QWidget * _widget, const QString & _pic );
QWidget * setupModalBarControls( QWidget * _parent );
QWidget * setupTubeBellControls( QWidget * _parent );
QWidget * setupBandedWGControls( QWidget * _parent );
QWidget * m_modalBarWidget;
Knob * m_hardnessKnob;
Knob * m_positionKnob;
Knob * m_vibratoGainKnob;
Knob * m_vibratoFreqKnob;
Knob * m_stickKnob;
QWidget * m_tubeBellWidget;
Knob * m_modulatorKnob;
Knob * m_crossfadeKnob;
Knob * m_lfoSpeedKnob;
Knob * m_lfoDepthKnob;
Knob * m_adsrKnob;
QWidget * m_bandedWGWidget;
Knob * m_pressureKnob;
// Knob * m_motionKnob;
// Knob * m_vibratoKnob;
Knob * m_velocityKnob;
// LedCheckBox * m_strikeLED;
ComboBox * m_presetsCombo;
Knob * m_spreadKnob;
Knob * m_randomKnob;
};
} // namespace gui
} // namespace lmms
#endif
| 6,438
|
C++
|
.h
| 230
| 25.495652
| 80
| 0.753581
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,037
|
OpulenZ.h
|
LMMS_lmms/plugins/OpulenZ/OpulenZ.h
|
/*
* OpulenZ.h - AdLib OPL2 FM synth based instrument
*
* Copyright (c) 2013 Raine M. Ekman <raine/at/iki/fi>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef OPULENZ_H
#define OPULENZ_H
#include <QMutex>
#include "AutomatableModel.h"
#include "Instrument.h"
#include "InstrumentView.h"
class Copl;
namespace lmms
{
namespace gui
{
class Knob;
class LcdSpinBox;
class PixmapButton;
class automatableButtonGroup;
}
// This one is a flag, MIDI notes take 7 low bits
#define OPL2_VOICE_FREE 128
#define OPL2_NO_VOICE 255
#define OPL2_VOICES 9
// The "normal" range for LMMS pitchbends
#define DEFAULT_BEND_CENTS 100
class OpulenzInstrument : public Instrument
{
Q_OBJECT
public:
OpulenzInstrument( InstrumentTrack * _instrument_track );
~OpulenzInstrument() override;
QString nodeName() const override;
gui::PluginView* instantiateView( QWidget * _parent ) override;
bool handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset = 0 ) override;
void play( SampleFrame* _working_buffer ) override;
void saveSettings( QDomDocument & _doc, QDomElement & _this ) override;
void loadSettings( const QDomElement & _this ) override;
void loadPatch(const unsigned char inst[14]);
void tuneEqual(int center, float Hz);
void loadFile( const QString& file ) override;
IntModel m_patchModel;
FloatModel op1_a_mdl;
FloatModel op1_d_mdl;
FloatModel op1_s_mdl;
FloatModel op1_r_mdl;
FloatModel op1_lvl_mdl;
FloatModel op1_scale_mdl;
FloatModel op1_mul_mdl;
FloatModel feedback_mdl;
BoolModel op1_ksr_mdl;
BoolModel op1_perc_mdl;
BoolModel op1_trem_mdl;
BoolModel op1_vib_mdl;
BoolModel op1_w0_mdl;
BoolModel op1_w1_mdl;
BoolModel op1_w2_mdl;
BoolModel op1_w3_mdl;
IntModel op1_waveform_mdl;
FloatModel op2_a_mdl;
FloatModel op2_d_mdl;
FloatModel op2_s_mdl;
FloatModel op2_r_mdl;
FloatModel op2_lvl_mdl;
FloatModel op2_scale_mdl;
FloatModel op2_mul_mdl;
BoolModel op2_ksr_mdl;
BoolModel op2_perc_mdl;
BoolModel op2_trem_mdl;
BoolModel op2_vib_mdl;
BoolModel op2_w0_mdl;
BoolModel op2_w1_mdl;
BoolModel op2_w2_mdl;
BoolModel op2_w3_mdl;
IntModel op2_waveform_mdl;
BoolModel fm_mdl;
BoolModel vib_depth_mdl;
BoolModel trem_depth_mdl;
private slots:
void updatePatch();
void reloadEmulator();
void loadGMPatch();
private:
Copl *theEmulator;
QString storedname;
fpp_t frameCount;
short *renderbuffer;
int voiceNote[OPL2_VOICES];
// Least recently used voices
int voiceLRU[OPL2_VOICES];
// 0 - no note, >0 - note on velocity
int velocities[128];
// These include both octave and Fnumber
int fnums[128];
// in cents, range defaults to +/-100 cents (should this be changeable?)
int pitchbend;
int pitchBendRange;
int popVoice();
int pushVoice(int v);
int Hz2fnum(float Hz);
static QMutex emulatorMutex;
void setVoiceVelocity(int voice, int vel);
// Pitch bend range comes through RPNs.
int RPNcoarse, RPNfine;
};
namespace gui
{
class OpulenzInstrumentView : public InstrumentViewFixedSize
{
Q_OBJECT
public:
OpulenzInstrumentView( Instrument * _instrument, QWidget * _parent );
~OpulenzInstrumentView() override;
LcdSpinBox *m_patch;
void modelChanged() override;
Knob *op1_a_kn;
Knob *op1_d_kn;
Knob *op1_s_kn;
Knob *op1_r_kn;
Knob *op1_lvl_kn;
Knob *op1_scale_kn;
Knob *op1_mul_kn;
Knob *feedback_kn;
PixmapButton *op1_ksr_btn;
PixmapButton *op1_perc_btn;
PixmapButton *op1_trem_btn;
PixmapButton *op1_vib_btn;
PixmapButton *op1_w0_btn;
PixmapButton *op1_w1_btn;
PixmapButton *op1_w2_btn;
PixmapButton *op1_w3_btn;
automatableButtonGroup *op1_waveform;
Knob *op2_a_kn;
Knob *op2_d_kn;
Knob *op2_s_kn;
Knob *op2_r_kn;
Knob *op2_lvl_kn;
Knob *op2_scale_kn;
Knob *op2_mul_kn;
PixmapButton *op2_ksr_btn;
PixmapButton *op2_perc_btn;
PixmapButton *op2_trem_btn;
PixmapButton *op2_vib_btn;
PixmapButton *op2_w0_btn;
PixmapButton *op2_w1_btn;
PixmapButton *op2_w2_btn;
PixmapButton *op2_w3_btn;
automatableButtonGroup *op2_waveform;
PixmapButton *fm_btn;
PixmapButton *vib_depth_btn;
PixmapButton *trem_depth_btn;
private slots:
void updateKnobHints();
private:
QString knobHintHelper(float n);
};
} // namespace gui
} // namespace lmms
#endif
| 4,955
|
C++
|
.h
| 178
| 25.780899
| 98
| 0.770059
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,038
|
EqFader.h
|
LMMS_lmms/plugins/Eq/EqFader.h
|
/* eqfader.h - defination of EqFader class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQFADER_H
#define EQFADER_H
#include <QList>
#include <QWidget>
#include "EffectControls.h"
#include "Fader.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "TextFloat.h"
namespace lmms::gui
{
class EqFader : public Fader
{
public:
Q_OBJECT
public:
EqFader( FloatModel * model, const QString & name, QWidget * parent, float* lPeak, float* rPeak ) :
Fader( model, name, parent )
{
setMinimumSize( 23, 116 );
setMaximumSize( 23, 116 );
resize( 23, 116 );
m_lPeak = lPeak;
m_rPeak = rPeak;
connect( getGUI()->mainWindow(), SIGNAL( periodicUpdate() ), this, SLOT( updateVuMeters() ) );
m_model = model;
setPeak_L( 0 );
setPeak_R( 0 );
}
~EqFader() override = default;
private slots:
void updateVuMeters()
{
const float opl = getPeak_L();
const float opr = getPeak_R();
const float fallOff = 1.07f;
if( *m_lPeak > opl )
{
setPeak_L( *m_lPeak );
*m_lPeak = 0;
}
else
{
setPeak_L( opl/fallOff );
}
if( *m_rPeak > opr )
{
setPeak_R( *m_rPeak );
*m_rPeak = 0;
}
else
{
setPeak_R( opr/fallOff );
}
update();
}
private:
float* m_lPeak;
float* m_rPeak;
FloatModel* m_model;
};
} // namespace lmms::gui
#endif // EQFADER_H
| 2,132
|
C++
|
.h
| 85
| 22.882353
| 101
| 0.708786
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,039
|
EqFilter.h
|
LMMS_lmms/plugins/Eq/EqFilter.h
|
/*
* eqfilter.cpp - defination of EqFilterclass.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQFILTER_H
#define EQFILTER_H
#include "BasicFilters.h"
#include "lmms_math.h"
namespace lmms
{
///
/// \brief The EqFilter class.
/// A wrapper for the StereoBiQuad class, giving it freq, res, and gain controls.
/// Used on a per channel per frame basis with recalculation of coefficents
/// upon parameter changes. The intention is to use this as a bass class, children override
/// the calcCoefficents() function, providing the coefficents a1, a2, b0, b1, b2.
///
class EqFilter
{
public:
EqFilter() :
m_sampleRate(0),
m_freq(0),
m_res(0),
m_gain(0),
m_bw(0)
{
}
virtual inline void setSampleRate( int sampleRate )
{
if( sampleRate != m_sampleRate )
{
m_sampleRate = sampleRate;
calcCoefficents();
}
}
virtual inline void setFrequency( float freq ){
if ( freq != m_freq )
{
m_freq = freq;
calcCoefficents();
}
}
virtual inline void setQ( float res )
{
if ( res != m_res )
{
m_res = res;
calcCoefficents();
}
}
virtual inline void setGain( float gain )
{
if ( gain != m_gain )
{
m_gain = gain;
calcCoefficents();
}
}
virtual inline void setParameters( float sampleRate, float freq, float res, float gain )
{
bool hasChanged = ( sampleRate != m_sampleRate ||
freq != m_freq ||
res != m_res ||
gain != m_gain );
if ( hasChanged )
{
m_sampleRate = sampleRate;
m_freq = freq;
m_res = res;
m_gain = gain;
calcCoefficents();
}
}
///
/// \brief update
/// filters using two BiQuads, then crossfades,
/// depending on on percentage of period processes
/// \param in
/// \param ch
/// \param frameProgress percentage of frame processed
/// \return
///
inline float update( float in, ch_cnt_t ch, float frameProgress)
{
float initailF = m_biQuadFrameInitial.update( in, ch );
float targetF = m_biQuadFrameTarget.update( in, ch );
if(frameProgress > 0.99999 )
{
m_biQuadFrameInitial= m_biQuadFrameTarget;
}
return (1.0f-frameProgress) * initailF + frameProgress * targetF;
}
protected:
///
/// \brief calcCoefficents
/// Override this in child classes to provide the coefficents, based on
/// Freq, Res and Gain
virtual void calcCoefficents(){
setCoeffs( 0, 0, 0, 0, 0 );
}
inline void setCoeffs( float a1, float a2, float b0, float b1, float b2 )
{
m_biQuadFrameTarget.setCoeffs( a1, a2, b0, b1, b2 );
}
float m_sampleRate;
float m_freq;
float m_res;
float m_gain;
float m_bw;
StereoBiQuad m_biQuadFrameInitial;
StereoBiQuad m_biQuadFrameTarget;
};
///
/// \brief The EqHp12Filter class
/// A 2 pole High Pass Filter
/// Coefficent calculations from http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
class EqHp12Filter : public EqFilter
{
public :
void calcCoefficents() override
{
// calc intermediate
float w0 = F_2PI * m_freq / m_sampleRate;
float c = cosf( w0 );
float s = sinf( w0 );
float alpha = s / ( 2 * m_res );
//calc coefficents
float b0 = (1 + c) * 0.5;
float b1 = (-(1 + c));
float b2 = (1 + c) * 0.5;
float a0 = 1 + alpha;
float a1 = (-2 * c);
float a2 = 1 - alpha;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
setCoeffs( a1, a2, b0, b1, b2 );
}
};
///
/// \brief The EqLp12Filter class.
/// A 2 pole low pass filter
/// Coefficent calculations from http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
///
class EqLp12Filter : public EqFilter
{
public :
void calcCoefficents() override
{
// calc intermediate
float w0 = F_2PI * m_freq / m_sampleRate;
float c = cosf( w0 );
float s = sinf( w0 );
float alpha = s / ( 2 * m_res );
//calc coefficents
float b0 = (1 - c) * 0.5;
float b1 = 1 - c;
float b2 = (1 - c) * 0.5;
float a0 = 1 + alpha;
float a1 = -2 * c;
float a2 = 1 - alpha;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
setCoeffs( a1, a2, b0, b1, b2 );
}
};
///
/// \brief The EqPeakFilter class
/// A Peak Filter
/// Coefficent calculations from http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
///
class EqPeakFilter : public EqFilter
{
public:
void calcCoefficents() override
{
// calc intermediate
float w0 = F_2PI * m_freq / m_sampleRate;
float c = cosf( w0 );
float s = sinf( w0 );
float A = pow( 10, m_gain * 0.025);
float alpha = s * sinh( log( 2 ) / 2 * m_bw * w0 / sinf(w0) );
//calc coefficents
float b0 = 1 + alpha * A;
float b1 = -2 * c;
float b2 = 1 - alpha * A;
float a0 = 1 + alpha / A;
float a1 = -2 * c;
float a2 = 1 - alpha / A;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
setCoeffs( a1, a2, b0, b1, b2 );
}
inline void setParameters( float sampleRate, float freq, float bw, float gain ) override
{
bool hasChanged = false;
if( sampleRate != m_sampleRate )
{
m_sampleRate = sampleRate;
hasChanged = true;
}
if ( freq != m_freq )
{
m_freq = freq;
hasChanged = true;
}
if ( bw != m_bw )
{
m_bw = bw;
hasChanged = true;
}
if ( gain != m_gain )
{
m_gain = gain;
hasChanged = true;
}
if ( hasChanged ) { calcCoefficents(); }
}
};
class EqLowShelfFilter : public EqFilter
{
public :
void calcCoefficents() override
{
// calc intermediate
float w0 = F_2PI * m_freq / m_sampleRate;
float c = cosf( w0 );
float s = sinf( w0 );
float A = pow( 10, m_gain * 0.025);
// float alpha = s / ( 2 * m_res );
float beta = sqrt( A ) / m_res;
//calc coefficents
float b0 = A * ((A + 1) - (A - 1) * c + beta * s);
float b1 = 2 * A * ((A - 1) - (A + 1) * c);
float b2 = A * ((A + 1) - (A - 1) * c - beta * s);
float a0 = (A + 1) + (A - 1) * c + beta * s;
float a1 = -2 * ((A - 1) + (A + 1) * c);
float a2 = (A + 1) + (A - 1) * c - beta * s;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
setCoeffs( a1, a2, b0, b1, b2 );
}
};
class EqHighShelfFilter : public EqFilter
{
public :
void calcCoefficents() override
{
// calc intermediate
float w0 = F_2PI * m_freq / m_sampleRate;
float c = cosf( w0 );
float s = sinf( w0 );
float A = pow( 10, m_gain * 0.025 );
float beta = sqrt( A ) / m_res;
//calc coefficents
float b0 = A * ((A + 1) + (A - 1) * c + beta * s);
float b1 = -2 * A * ((A - 1) + (A + 1) * c);
float b2 = A * ((A + 1) + (A - 1) * c - beta * s);
float a0 = (A + 1) - (A - 1) * c + beta * s;
float a1 = 2 * ((A - 1) - (A + 1) * c);
float a2 = (A + 1) - (A - 1) * c - beta * s;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
setCoeffs( a1, a2, b0, b1, b2 );
}
};
class EqLinkwitzRiley : public StereoLinkwitzRiley
{
public:
EqLinkwitzRiley() :
StereoLinkwitzRiley( 44100),
m_freq(0 ),
m_sr( 1 )
{
}
virtual inline void setSR( int sampleRate )
{
if( sampleRate != m_sr )
{
m_sr = sampleRate;
setSampleRate( sampleRate );
setLowpass(m_freq);
}
}
virtual inline void setFrequency( float freq ){
if ( freq != m_freq )
{
m_freq = freq;
setLowpass(m_freq);
}
}
virtual void processBuffer( SampleFrame* buf, const fpp_t frames )
{
for ( fpp_t f = 0 ; f < frames ; ++f)
{
buf[f][0] = update( buf[f][0] , 0);
buf[f][1] = update( buf[f][1] , 1);
}
}
protected:
float m_freq;
int m_sr;
};
} // namespace lmms
#endif // EQFILTER_H
| 8,359
|
C++
|
.h
| 349
| 21.017192
| 91
| 0.622976
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,040
|
EqSpectrumView.h
|
LMMS_lmms/plugins/Eq/EqSpectrumView.h
|
/* eqspectrumview.h - defination of EqSpectrumView class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQSPECTRUMVIEW_H
#define EQSPECTRUMVIEW_H
#include <QPainterPath>
#include <QWidget>
#include "fft_helpers.h"
#include "lmms_basics.h"
namespace lmms
{
class SampleFrame;
const int MAX_BANDS = 2048;
class EqAnalyser
{
public:
EqAnalyser();
virtual ~EqAnalyser();
float m_bands[MAX_BANDS];
bool getInProgress();
void clear();
void analyze( SampleFrame* buf, const fpp_t frames );
float getEnergy() const;
int getSampleRate() const;
bool getActive() const;
void setActive(bool active);
private:
fftwf_plan m_fftPlan;
fftwf_complex * m_specBuf;
float m_absSpecBuf[FFT_BUFFER_SIZE+1];
float m_buffer[FFT_BUFFER_SIZE*2];
int m_framesFilledUp;
float m_energy;
int m_sampleRate;
bool m_active;
bool m_inProgress;
float m_fftWindow[FFT_BUFFER_SIZE];
};
namespace gui
{
class EqSpectrumView : public QWidget
{
Q_OBJECT
public:
explicit EqSpectrumView( EqAnalyser *b, QWidget *_parent = 0 );
~EqSpectrumView() override = default;
QColor getColor() const;
void setColor( const QColor &value );
protected:
void paintEvent( QPaintEvent *event ) override;
private slots:
void periodicalUpdate();
private:
QColor m_color;
EqAnalyser *m_analyser;
QPainterPath m_path;
float m_peakSum;
float m_pixelsPerUnitWidth;
float m_scale;
int m_skipBands;
bool m_periodicalUpdate;
QList<float> m_bandHeight;
float bandToFreq ( int index );
};
} // namespace gui
} // namespace lmms
#endif // EQSPECTRUMVIEW_H
| 2,359
|
C++
|
.h
| 86
| 25.744186
| 74
| 0.774767
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,041
|
EqControls.h
|
LMMS_lmms/plugins/Eq/EqControls.h
|
/*
* eqcontrols.h - defination of EqControls class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQCONTROLS_H
#define EQCONTROLS_H
#include "EffectControls.h"
#include "EqSpectrumView.h"
namespace lmms
{
class EqEffect;
namespace gui
{
class EqControlsDialog;
}
class EqControls : public EffectControls
{
Q_OBJECT
public:
explicit EqControls( EqEffect* effect );
~EqControls() override = default;
void saveSettings ( QDomDocument& doc, QDomElement& parent ) override;
void loadSettings ( const QDomElement &_this ) override;
inline QString nodeName() const override
{
return "Eq";
}
int controlCount() override
{
return 42;
}
gui::EffectControlDialog* createView() override;
float m_inPeakL;
float m_inPeakR;
float m_outPeakL;
float m_outPeakR;
// The following are linear peaks
float m_lowShelfPeakL, m_lowShelfPeakR;
float m_para1PeakL, m_para1PeakR;
float m_para2PeakL, m_para2PeakR;
float m_para3PeakL, m_para3PeakR;
float m_para4PeakL, m_para4PeakR;
float m_highShelfPeakL, m_highShelfPeakR;
EqAnalyser m_inFftBands;
EqAnalyser m_outFftBands;
bool m_inProgress;
bool visable();
private:
EqEffect *m_effect;
FloatModel m_inGainModel;
FloatModel m_outGainModel;
FloatModel m_lowShelfGainModel;
FloatModel m_para1GainModel;
FloatModel m_para2GainModel;
FloatModel m_para3GainModel;
FloatModel m_para4GainModel;
FloatModel m_highShelfGainModel;
FloatModel m_hpResModel;
FloatModel m_lowShelfResModel;
FloatModel m_para1BwModel;
FloatModel m_para2BwModel;
FloatModel m_para3BwModel;
FloatModel m_para4BwModel;
FloatModel m_highShelfResModel;
FloatModel m_lpResModel;
FloatModel m_hpFeqModel;
FloatModel m_lowShelfFreqModel;
FloatModel m_para1FreqModel;
FloatModel m_para2FreqModel;
FloatModel m_para3FreqModel;
FloatModel m_para4FreqModel;
FloatModel m_highShelfFreqModel;
FloatModel m_lpFreqModel;
BoolModel m_hpActiveModel;
BoolModel m_lowShelfActiveModel;
BoolModel m_para1ActiveModel;
BoolModel m_para2ActiveModel;
BoolModel m_para3ActiveModel;
BoolModel m_para4ActiveModel;
BoolModel m_highShelfActiveModel;
BoolModel m_lpActiveModel;
BoolModel m_lp12Model;
BoolModel m_lp24Model;
BoolModel m_lp48Model;
BoolModel m_hp12Model;
BoolModel m_hp24Model;
BoolModel m_hp48Model;
IntModel m_lpTypeModel;
IntModel m_hpTypeModel;
BoolModel m_analyseInModel;
BoolModel m_analyseOutModel;
friend class gui::EqControlsDialog;
friend class EqEffect;
};
} // namespace lmms
#endif // EQCONTROLS_H
| 3,330
|
C++
|
.h
| 115
| 26.852174
| 75
| 0.804143
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,042
|
EqControlsDialog.h
|
LMMS_lmms/plugins/Eq/EqControlsDialog.h
|
/*
* eqcontrolsdialog.h - defination of EqControlsDialog class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQCONTROLSDIALOG_H
#define EQCONTROLSDIALOG_H
#include "EffectControlDialog.h"
namespace lmms
{
class BoolModel;
class FloatModel;
class EqControls;
namespace gui
{
class EqBand;
class EqParameterWidget;
class EqControlsDialog : public EffectControlDialog
{
Q_OBJECT
public:
EqControlsDialog( EqControls * controls );
~EqControlsDialog() override = default;
EqBand * setBand( EqControls * controls );
private:
EqControls * m_controls;
EqParameterWidget * m_parameterWidget;
void mouseDoubleClickEvent(QMouseEvent *event) override;
EqBand *setBand( int index, BoolModel *active, FloatModel *freq, FloatModel *res, FloatModel *gain, QColor color, QString name, float *peakL, float *peakR, BoolModel *hp12, BoolModel *hp24, BoolModel *hp48, BoolModel *lp12, BoolModel *lp24, BoolModel *lp48 );
int m_originalHeight;
};
} // namespace gui
} // namespace lmms
#endif // EQCONTROLSDIALOG_H
| 1,857
|
C++
|
.h
| 52
| 33.769231
| 260
| 0.7784
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,043
|
EqCurve.h
|
LMMS_lmms/plugins/Eq/EqCurve.h
|
/*
* EqCurve.h - defination of EqCurve and EqHandle classes.
*
* Copyright (c) 2015 Steffen Baranowsky <BaraMGB/at/freenet/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQCURVE_H
#define EQCURVE_H
#include <QGraphicsObject>
namespace lmms::gui
{
enum class EqHandleType {
HighPass=1,
LowShelf,
Para,
HighShelf,
LowPass
};
// implements the Eq_Handle to control a band
class EqHandle : public QGraphicsObject
{
Q_OBJECT
public:
EqHandle( int num, int x, int y );
static float freqToXPixel( float freq, int w );
static float xPixelToFreq( float x , int w );
static float gainToYPixel( float gain, int h, float pixelPerUnitHeight );
static float yPixelToGain( float y, int h, float pixelPerUnitHeight );
QRectF boundingRect() const override;
QPainterPath getCurvePath();
float getPeakCurve( float x );
float getHighShelfCurve( float x );
float getLowShelfCurve( float x );
float getLowCutCurve( float x );
float getHighCutCurve( float x );
float getResonance();
int getNum();
EqHandleType getType();
void setType( EqHandleType t );
void setResonance( float r );
bool isMouseHover();
void setMouseHover( bool d );
bool isActiveHandle();
void setHandleActive( bool a );
bool mousePressed() const;
void sethp12();
void sethp24();
void sethp48();
void setlp12();
void setlp24();
void setlp48();
signals:
void positionChanged();
protected:
void mousePressEvent( QGraphicsSceneMouseEvent *event ) override;
void mouseReleaseEvent( QGraphicsSceneMouseEvent *event ) override;
void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) override;
void wheelEvent( QGraphicsSceneWheelEvent *wevent ) override;
void hoverEnterEvent( QGraphicsSceneHoverEvent *hevent ) override;
void hoverLeaveEvent( QGraphicsSceneHoverEvent *hevent ) override;
QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override;
private:
double calculateGain( const double freq, const double a1, const double a2, const double b0, const double b1, const double b2 );
void loadPixmap();
float m_pixelsPerUnitWidth;
float m_pixelsPerUnitHeight;
float m_scale;
bool m_hp12;
bool m_hp24;
bool m_hp48;
bool m_lp12;
bool m_lp24;
bool m_lp48;
bool m_mouseHover;
EqHandleType m_type;
int m_numb;
float m_width, m_heigth;
float m_resonance;
bool m_mousePressed;
bool m_active;
QPixmap m_circlePixmap;
};
class EqCurve : public QGraphicsObject
{
Q_OBJECT
public:
EqCurve( QList<EqHandle*> *handle, int x, int y );
QRectF boundingRect() const override;
void setModelChanged(bool mc);
protected:
void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) override;
private:
QList<EqHandle*> *m_handle;
QPainterPath m_curve;
QPixmap m_curvePixmapCache;
int m_width, m_heigth;
int m_alpha;
bool m_modelChanged;
float m_pixelsPerUnitHeight;
float m_scale;
};
} // namespace lmms::gui
#endif // EQCURVE_H
| 3,696
|
C++
|
.h
| 120
| 28.808333
| 128
| 0.775338
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,044
|
EqParameterWidget.h
|
LMMS_lmms/plugins/Eq/EqParameterWidget.h
|
/*
* eqparameterwidget.cpp - defination of EqParameterWidget class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
* Copyright (c) 2015 Steffen Baranowsky <BaraMGB/at/freenet/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQPARAMETERWIDGET_H
#define EQPARAMETERWIDGET_H
#include <QWidget>
namespace lmms
{
class BoolModel;
class EqControls;
class FloatModel;
namespace gui
{
class EqCurve;
class EqHandle;
class EqBand
{
public :
EqBand();
FloatModel *gain;
FloatModel *res;
FloatModel *freq;
BoolModel *active;
BoolModel *hp12;
BoolModel *hp24;
BoolModel *hp48;
BoolModel *lp12;
BoolModel *lp24;
BoolModel *lp48;
QColor color;
int x;
int y;
QString name;
float *peakL;
float *peakR;
};
class EqParameterWidget : public QWidget
{
Q_OBJECT
public:
explicit EqParameterWidget( QWidget *parent = 0, EqControls * controls = 0 );
~EqParameterWidget() override;
QList<EqHandle*> m_handleList;
const int bandCount()
{
return 8;
}
EqBand* getBandModels( int i );
void changeHandle( int i );
private:
float m_pixelsPerUnitWidth;
float m_pixelsPerUnitHeight;
float m_pixelsPerOctave;
float m_scale;
int m_displayWidth, m_displayHeigth;
EqControls *m_controls;
EqBand *m_bands;
EqHandle *m_handle;
EqCurve *m_eqcurve;
private slots:
void updateModels();
void updateHandle();
};
} // namespace gui
} // namespace lmms
#endif // EQPARAMETERWIDGET_H
| 2,194
|
C++
|
.h
| 87
| 23.252874
| 78
| 0.769194
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
20,045
|
EqEffect.h
|
LMMS_lmms/plugins/Eq/EqEffect.h
|
/* eqeffect.h - defination of EqEffect class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef EQEFFECT_H
#define EQEFFECT_H
#include "Effect.h"
#include "EqControls.h"
#include "EqFilter.h"
#include <algorithm>
namespace lmms
{
class EqEffect : public Effect
{
public:
EqEffect( Model * parent , const Descriptor::SubPluginFeatures::Key * key );
~EqEffect() override = default;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls * controls() override
{
return &m_eqControls;
}
inline void gain( SampleFrame* buf, const fpp_t frames, float scale, SampleFrame* peak )
{
peak[0][0] = 0.0f; peak[0][1] = 0.0f;
for( fpp_t f = 0; f < frames; ++f )
{
auto & sf = buf[f];
// Apply gain to sample frame
sf[0] *= scale;
sf[1] *= scale;
// Update peaks
peak[0][0] = std::max(peak[0][0], (float)fabs(sf[0]));
peak[0][1] = std::max(peak[0][1], (float)fabs(sf[1]));
}
}
private:
EqControls m_eqControls;
EqHp12Filter m_hp12;
EqHp12Filter m_hp24;
EqHp12Filter m_hp480;
EqHp12Filter m_hp481;
EqLowShelfFilter m_lowShelf;
EqPeakFilter m_para1;
EqPeakFilter m_para2;
EqPeakFilter m_para3;
EqPeakFilter m_para4;
EqHighShelfFilter m_highShelf;
EqLp12Filter m_lp12;
EqLp12Filter m_lp24;
EqLp12Filter m_lp480;
EqLp12Filter m_lp481;
float m_inGain;
float m_outGain;
float linearPeakBand(float minF, float maxF, EqAnalyser*, int);
inline float bandToFreq ( int index , int sampleRate )
{
return index * sampleRate / ( MAX_BANDS * 2 );
}
void setBandPeaks( EqAnalyser * fft , int );
};
} // namespace lmms
#endif // EQEFFECT_H
| 2,440
|
C++
|
.h
| 81
| 28.037037
| 89
| 0.737045
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,046
|
KickerOsc.h
|
LMMS_lmms/plugins/Kicker/KickerOsc.h
|
/*
* KickerOsc.h - alternative sweeping oscillator
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2014 grejppi <grejppi/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef KICKER_OSC_H
#define KICKER_OSC_H
#include "DspEffectLibrary.h"
#include "Oscillator.h"
#include "lmms_math.h"
#include "interpolation.h"
namespace lmms
{
template<class FX = DspEffectLibrary::StereoBypass>
class KickerOsc
{
public:
KickerOsc( const FX & fx, const float start, const float end, const float noise, const float offset,
const float slope, const float env, const float diststart, const float distend, const float length ) :
m_phase( offset ),
m_startFreq( start ),
m_endFreq( end ),
m_noise( noise ),
m_slope( slope ),
m_env( env ),
m_distStart( diststart ),
m_distEnd( distend ),
m_hasDistEnv( diststart != distend ),
m_length( length ),
m_FX( fx ),
m_counter( 0 ),
m_freq( start )
{
}
virtual ~KickerOsc() = default;
void update( SampleFrame* buf, const fpp_t frames, const float sampleRate )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
const double gain = 1 - fastPow((m_counter < m_length) ? m_counter / m_length : 1, m_env);
const sample_t s = ( Oscillator::sinSample( m_phase ) * ( 1 - m_noise ) ) + ( Oscillator::noiseSample( 0 ) * gain * gain * m_noise );
buf[frame][0] = s * gain;
buf[frame][1] = s * gain;
// update distortion envelope if necessary
if( m_hasDistEnv && m_counter < m_length )
{
float thres = linearInterpolate( m_distStart, m_distEnd, m_counter / m_length );
m_FX.leftFX().setThreshold( thres );
m_FX.rightFX().setThreshold( thres );
}
m_FX.nextSample( buf[frame][0], buf[frame][1] );
m_phase += m_freq / sampleRate;
const double change = (m_counter < m_length) ? ((m_startFreq - m_endFreq) * (1 - fastPow(m_counter / m_length, m_slope))) : 0;
m_freq = m_endFreq + change;
++m_counter;
}
}
private:
float m_phase;
const float m_startFreq;
const float m_endFreq;
const float m_noise;
const float m_slope;
const float m_env;
const float m_distStart;
const float m_distEnd;
const bool m_hasDistEnv;
const float m_length;
FX m_FX;
unsigned long m_counter;
double m_freq;
};
} // namespace lmms
#endif
| 3,062
|
C++
|
.h
| 93
| 30.27957
| 136
| 0.704244
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
20,047
|
Kicker.h
|
LMMS_lmms/plugins/Kicker/Kicker.h
|
/*
* Kicker.h - drum synthesizer
*
* Copyright (c) 2006-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2014 grejppi <grejppi/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef LMMS_KICKER_H
#define LMMS_KICKER_H
#include "AutomatableModel.h"
#include "Instrument.h"
#include "InstrumentView.h"
#include "TempoSyncKnobModel.h"
namespace lmms
{
#define KICKER_PRESET_VERSION 1
class NotePlayHandle;
namespace gui
{
class Knob;
class LedCheckBox;
class KickerInstrumentView;
}
class KickerInstrument : public Instrument
{
Q_OBJECT
public:
KickerInstrument( InstrumentTrack * _instrument_track );
~KickerInstrument() override = default;
void playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer ) override;
void deleteNotePluginData( NotePlayHandle * _n ) override;
void saveSettings(QDomDocument& doc, QDomElement& elem) override;
void loadSettings(const QDomElement& elem) override;
QString nodeName() const override;
float desiredReleaseTimeMs() const override
{
return 12.f;
}
gui::PluginView* instantiateView( QWidget * _parent ) override;
private:
FloatModel m_startFreqModel;
FloatModel m_endFreqModel;
TempoSyncKnobModel m_decayModel;
FloatModel m_distModel;
FloatModel m_distEndModel;
FloatModel m_gainModel;
FloatModel m_envModel;
FloatModel m_noiseModel;
FloatModel m_clickModel;
FloatModel m_slopeModel;
BoolModel m_startNoteModel;
BoolModel m_endNoteModel;
IntModel m_versionModel;
friend class gui::KickerInstrumentView;
} ;
namespace gui
{
class KickerInstrumentView : public InstrumentViewFixedSize
{
Q_OBJECT
public:
KickerInstrumentView( Instrument * _instrument, QWidget * _parent );
~KickerInstrumentView() override = default;
private:
void modelChanged() override;
Knob * m_startFreqKnob;
Knob * m_endFreqKnob;
Knob * m_decayKnob;
Knob * m_distKnob;
Knob * m_distEndKnob;
Knob * m_gainKnob;
Knob * m_envKnob;
Knob * m_noiseKnob;
Knob * m_clickKnob;
Knob * m_slopeKnob;
LedCheckBox * m_startNoteToggle;
LedCheckBox * m_endNoteToggle;
} ;
} // namespace gui
} // namespace lmms
#endif // LMMS_KICKER_H
| 2,901
|
C++
|
.h
| 99
| 27.232323
| 77
| 0.782954
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,048
|
Bitcrush.h
|
LMMS_lmms/plugins/Bitcrush/Bitcrush.h
|
/*
* Bitcrush.h - A native bitcrusher
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 2 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef BITCRUSH_H
#define BITCRUSH_H
#include "Effect.h"
#include "BitcrushControls.h"
#include "BasicFilters.h"
namespace lmms
{
class BitcrushEffect : public Effect
{
public:
BitcrushEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key );
~BitcrushEffect() override;
ProcessStatus processImpl(SampleFrame* buf, const fpp_t frames) override;
EffectControls* controls() override
{
return &m_controls;
}
private:
void sampleRateChanged();
float depthCrush( float in );
float noise( float amt );
BitcrushControls m_controls;
SampleFrame* m_buffer;
float m_sampleRate;
StereoLinkwitzRiley m_filter;
float m_bitCounterL;
float m_rateCoeffL;
float m_bitCounterR;
float m_rateCoeffR;
bool m_rateEnabled;
float m_left;
float m_right;
int m_levels;
float m_levelsRatio;
bool m_depthEnabled;
float m_inGain;
float m_outGain;
float m_outClip;
bool m_needsUpdate;
int m_silenceCounter;
friend class BitcrushControls;
};
} // namespace lmms
#endif
| 1,996
|
C++
|
.h
| 68
| 27.161765
| 80
| 0.771173
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| 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.