id
int64 0
877k
| 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
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,532,310
|
keysignatureui.cpp
|
canorusmusic_canorus/src/scoreui/keysignatureui.cpp
|
/*!
Copyright (c) 2006-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
// Includes
#include <QMessageBox>
#include "canorus.h"
#include "core/muselementfactory.h"
#include "layout/drawablekeysignature.h"
#include "scorectl/keysignaturectl.h"
#include "scoreui/keysignatureui.h"
#include "ui/mainwin.h"
/*!
\class CAKeySignatureUI
\brief Keysignature user interface objects creation
This class creates the key signature user interface parts
of the main window (toolbar, combobox)
*/
/*!
Default Construktor
Besides standard initialization it creates it's ui objects.
Also the control object is created here.
Inbetween the combobox (for selection) gets populated
Finally the Toolbar is added to the main win Toolbar and hidden
*/
CAKeySignatureUI::CAKeySignatureUI(CAMainWin* poMainWin, const QString& oHash)
{
setObjectName("oKeySignatureUI");
_poMainWin = poMainWin;
_poKeySignatureCtl = new CAKeySignatureCtl(poMainWin, oHash);
uiKeySigToolBar = new QToolBar(tr("Key Signature ToolBar"), poMainWin);
uiKeySig = new QComboBox(poMainWin);
uiKeySig->setObjectName("uiKeySig");
CAKeySignatureUI::populateComboBox(uiKeySig);
if (poMainWin == nullptr)
qCritical("KeySignatureUI: No mainwindow instance available!");
// KeySig Toolbar
uiKeySigToolBar->addWidget(uiKeySig);
poMainWin->addToolBar(Qt::TopToolBarArea, uiKeySigToolBar);
_poKeySignatureCtl->setupActions();
uiKeySigToolBar->hide();
}
// Destructor
CAKeySignatureUI::~CAKeySignatureUI()
{
if (uiKeySigToolBar) {
delete uiKeySigToolBar;
}
if (uiKeySig) {
delete uiKeySig;
}
uiKeySigToolBar = nullptr;
uiKeySig = nullptr;
}
/*!
Shows/Hides the key signature properties tool bar according to the current state.
*/
void CAKeySignatureUI::updateKeySigToolBar()
{
if (_poMainWin->isInsertKeySigChecked() && _poMainWin->mode() == CAMainWin::InsertMode) {
uiKeySig->setCurrentIndex(
uiKeySig->findData(
CADiatonicKey::diatonicKeyToString(CADiatonicKey(_poMainWin->musElementFactory()->diatonicKeyNumberOfAccs(), _poMainWin->musElementFactory()->diatonicKeyGender()))));
uiKeySigToolBar->show();
} else if (_poMainWin->mode() == CAMainWin::EditMode && _poMainWin->currentScoreView() && _poMainWin->currentScoreView()->selection().size() && dynamic_cast<CAKeySignature*>(_poMainWin->currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = _poMainWin->currentScoreView();
if (v && v->selection().size()) {
CAKeySignature* keySig = dynamic_cast<CAKeySignature*>(v->selection().at(0)->musElement());
if (keySig) {
uiKeySig->setCurrentIndex(uiKeySig->findData(CADiatonicKey::diatonicKeyToString(keySig->diatonicKey())));
uiKeySigToolBar->show();
} else
uiKeySigToolBar->hide();
}
} else
uiKeySigToolBar->hide();
}
/*!
This function adds key signatures to the given combobox in order
major-minor-major-... from most flats to most sharps.
This function usually called when initializing the main window.
\sa CADrawableKeySignature::comboBoxRowToDiatonicKey(), CADrawableKeySignature::populateComboBoxDirection()
*/
void CAKeySignatureUI::populateComboBox(QComboBox* c)
{
c->addItem(QIcon("images:general/none.svg"), QObject::tr("C major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(0, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs7.svg"), QObject::tr("C-sharp major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(7, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-7.svg"), QObject::tr("C-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-7, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-3.svg"), QObject::tr("c minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-3, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs4.svg"), QObject::tr("c-sharp minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(4, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs2.svg"), QObject::tr("D major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(2, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-5.svg"), QObject::tr("D-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-5, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-1.svg"), QObject::tr("d minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-1, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs6.svg"), QObject::tr("d-sharp minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(6, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs4.svg"), QObject::tr("E major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(4, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-3.svg"), QObject::tr("E-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-3, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs1.svg"), QObject::tr("e minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(1, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs-6.svg"), QObject::tr("e-flat minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-6, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs-1.svg"), QObject::tr("F major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-1, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs6.svg"), QObject::tr("F-sharp major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(6, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-4.svg"), QObject::tr("f minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-4, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs3.svg"), QObject::tr("f-sharp minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(3, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs1.svg"), QObject::tr("G major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(1, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-6.svg"), QObject::tr("G-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-6, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-2.svg"), QObject::tr("g minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-2, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs5.svg"), QObject::tr("g-sharp minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(5, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs3.svg"), QObject::tr("A major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(3, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-4.svg"), QObject::tr("A-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-4, CADiatonicKey::Major)));
c->addItem(QIcon("images:general/none.svg"), QObject::tr("a minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(0, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs7.svg"), QObject::tr("a-sharp minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(7, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs-7.svg"), QObject::tr("a-flat minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-7, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs5.svg"), QObject::tr("B major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(5, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs-2.svg"), QObject::tr("B-flat major"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-2, CADiatonicKey::Major)));
c->addItem(QIcon("images:accidental/accs2.svg"), QObject::tr("b minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(2, CADiatonicKey::Minor)));
c->addItem(QIcon("images:accidental/accs-5.svg"), QObject::tr("b-flat minor"), CADiatonicKey::diatonicKeyToString(CADiatonicKey(-5, CADiatonicKey::Minor)));
}
/*!
Adds directions Up and Down with icons to the given combo box.
\sa CADrawableKeySignature::comboBoxRowToDiatonicKey(), CADrawableKeySignature::populateComboBox()
*/
void CAKeySignatureUI::populateComboBoxDirection(QComboBox* c)
{
c->addItem(QIcon("images:general/up.svg"), QObject::tr("Up"));
c->addItem(QIcon("images:general/down.svg"), QObject::tr("Down"));
}
| 8,622
|
C++
|
.cpp
| 126
| 63.761905
| 245
| 0.744013
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,311
|
dummyui.cpp
|
canorusmusic_canorus/src/scoreui/dummyui.cpp
|
/*!
Copyright (c) 2006-2010, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
// Includes
#include <QMessageBox>
#include "canorus.h"
#include "ctl/dummyctl.h"
#include "ui/dummyui.h"
#include "ui/dummyuiobj.h" // Does not exist, this is only a dummy example!
#include "ui/mainwin.h"
/*!
\class CADummyUI
\brief Dummy example user interface objects creation
Use this dummy class for creating your own user interface
object creation classes
*/
/*!
Default Construktor
Besides standard initialization it creates a dummy ui object.
*/
CADummyUI::CADummyUI(CAMainWin* poMainWin)
{
setObjectName("oDummyUI");
_poMainWin = poMainWin;
_poDummyCtl = new CADummyCtl(poMainWin);
_poDummyUIObj = new DummyUIObj(poMainWin);
if (poMainWin == 0)
qCritical("DummyCtl: No mainwindow instance available!");
}
// Destructor
CADummyUI::~CADummyUI()
{
if (_poDummyUIObj) {
delete _poDummyUIObj;
}
_poDummyUIObj = 0;
}
CADummyUI::updateDummyUIObjs()
{
_poDummyUIObj->updateDummyUI();
}
| 1,209
|
C++
|
.cpp
| 43
| 24.976744
| 93
| 0.734659
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,312
|
drawablefunctionmarkcontext.cpp
|
canorusmusic_canorus/src/layout/drawablefunctionmarkcontext.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QBrush>
#include <QPainter>
#include "layout/drawablefunctionmarkcontext.h"
#include "score/functionmarkcontext.h"
CADrawableFunctionMarkContext::CADrawableFunctionMarkContext(CAFunctionMarkContext* context, double x, double y, int numberOfLines)
: CADrawableContext(context, x, y)
, _numberOfLines(numberOfLines)
, _currentLineIdx(0)
{
setDrawableContextType(CADrawableContext::DrawableFunctionMarkContext);
setWidth(0);
setHeight(45 * numberOfLines - 10 * (numberOfLines - 1));
}
CADrawableFunctionMarkContext::~CADrawableFunctionMarkContext()
{
}
void CADrawableFunctionMarkContext::draw(QPainter* p, const CADrawSettings s)
{
QColor bColor = Qt::yellow;
bColor.setAlphaF(0.2);
p->fillRect(0, s.y, s.w, qRound(height() * s.z), QBrush(bColor));
}
CADrawableFunctionMarkContext* CADrawableFunctionMarkContext::clone()
{
return new CADrawableFunctionMarkContext(static_cast<CAFunctionMarkContext*>(_context), xPos(), yPos());
}
double CADrawableFunctionMarkContext::yPosLine(CAFunctionMarkLine part)
{
double y = yPos();
for (int i = 0; i < _currentLineIdx; i++) {
y += 35; //height of a single line
}
if (part == Middle)
y += 15;
else if (part == Lower)
y += 30;
return y;
}
void CADrawableFunctionMarkContext::nextLine()
{
++_currentLineIdx;
_currentLineIdx = _currentLineIdx % _numberOfLines;
}
| 1,629
|
C++
|
.cpp
| 48
| 30.645833
| 131
| 0.744586
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,313
|
drawabletimesignature.cpp
|
canorusmusic_canorus/src/layout/drawabletimesignature.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawabletimesignature.h"
#include "layout/drawablestaff.h"
#include "score/timesignature.h"
#include <QDebug>
#include <QFont>
#include <QPainter>
#include <QString>
CADrawableTimeSignature::CADrawableTimeSignature(CATimeSignature* timeSig, CADrawableStaff* drawableStaff, double x, double y)
: CADrawableMusElement(timeSig, drawableStaff, x, y)
{
_drawableMusElementType = CADrawableMusElement::DrawableTimeSignature;
if ((timeSignature()->timeSignatureType() == CATimeSignature::Classical) && (timeSignature()->beat() == 4) && (timeSignature()->beats() == 4)) {
setWidth(16);
setHeight(20);
setYPos(drawableContext()->yCenter() - 0.5 * height());
} else if ((timeSignature()->timeSignatureType() == CATimeSignature::Classical) && (timeSignature()->beat() == 2) && (timeSignature()->beats() == 2)) {
setWidth(16);
setHeight(24);
setYPos(drawableContext()->yCenter() - 0.5 * height());
} else { // determine the width - number of characters needed to draw the beat and beats times the width of a single character
setWidth(14);
QString beats = QString::number(timeSignature()->beats()).mid(1); //cut-off the first character already
QString beat = QString::number(timeSignature()->beat()).mid(1); //cut-off the first character already
while ((!beats.isEmpty()) || (!beat.isEmpty())) {
setWidth(width() + 15); // blank + number width
beats = beats.mid(1);
beat = beat.mid(1);
}
setHeight(drawableStaff->height());
}
}
CADrawableTimeSignature::~CADrawableTimeSignature()
{
}
void CADrawableTimeSignature::draw(QPainter* p, CADrawSettings s)
{
QFont font("Emmentaler");
font.setPixelSize(qRound(37 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
/*
* Time signature emmentaler numbers glyphs:
* - timesig.C44: C 4/4 classical key signature - y0 is the center of the glyph
* - timesig.C22: C| 2/2 classical key signature - y0 is the center of the glyph
* - 0..9: y0 is the bottom of the glyph
*/
switch (timeSignature()->timeSignatureType()) {
case CATimeSignature::Classical:
case CATimeSignature::Number: {
// Draw C or C|, if needed.
if (timeSignature()->timeSignatureType() == CATimeSignature::Classical) {
if ((timeSignature()->beat() == 4) && (timeSignature()->beats() == 4)) {
p->drawText(s.x, qRound(s.y + 0.5 * height() * s.z), QString(CACanorus::fetaCodepoint("timesig.C44")));
break;
} else if ((timeSignature()->beat() == 2) && (timeSignature()->beats() == 2)) {
p->drawText(s.x, qRound(s.y + 0.5 * height() * s.z), QString(CACanorus::fetaCodepoint("timesig.C22")));
break;
}
}
// Write the numbers from top to bottom.
QString curBeats = QString::number(timeSignature()->beats());
QString curBeat = QString::number(timeSignature()->beat());
double curX = s.x;
while (!curBeats.isEmpty() || !curBeat.isEmpty()) {
if (!curBeats.isEmpty())
p->drawText(qRound(curX), qRound(s.y + 0.5 * drawableContext()->height() * s.z), QString(curBeats[0]));
if (!curBeat.isEmpty())
p->drawText(qRound(curX), qRound(s.y + drawableContext()->height() * s.z), QString(curBeat[0]));
curX += (14 * s.z);
// Trim-off the left-most characters.
curBeats = curBeats.mid(1);
curBeat = curBeat.mid(1);
}
break;
}
case CATimeSignature::Baroque:
case CATimeSignature::Neomensural:
case CATimeSignature::Mensural:
qWarning() << "CADrawableTimeSignature::draw - Unhandled type " << timeSignature()->timeSignatureType();
break;
}
}
CADrawableTimeSignature* CADrawableTimeSignature::clone(CADrawableContext* newContext)
{
return (new CADrawableTimeSignature(timeSignature(), newContext ? static_cast<CADrawableStaff*>(newContext) : static_cast<CADrawableStaff*>(_drawableContext), xPos(), _drawableContext->yPos()));
}
| 4,370
|
C++
|
.cpp
| 91
| 41.065934
| 198
| 0.644549
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,314
|
drawable.cpp
|
canorusmusic_canorus/src/layout/drawable.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QPainter>
#include "layout/drawable.h"
#include "layout/drawablecontext.h"
#include "layout/drawablemuselement.h"
const int CADrawable::SCALE_HANDLES_SIZE = 2;
CADrawable::CADrawable(double x, double y)
: _xPos(x)
, _yPos(y)
, _neededSpaceWidth(0)
, _neededSpaceHeight(0)
, _visible(true)
, _selectable(true)
, _hScalable(false)
, _vScalable(false)
{
}
void CADrawable::drawHScaleHandles(QPainter* p, CADrawSettings s)
{
p->setPen(QPen(s.color));
p->drawRect(s.x - qRound((SCALE_HANDLES_SIZE * s.z) / 2), s.y + qRound((height() * s.z) / 2 - (SCALE_HANDLES_SIZE * s.z) / 2),
qRound(SCALE_HANDLES_SIZE * s.z), qRound(SCALE_HANDLES_SIZE * s.z));
p->drawRect(s.x + qRound(((width() - SCALE_HANDLES_SIZE / 2.0) * s.z)), s.y + qRound((height() / 2.0 - SCALE_HANDLES_SIZE / 2.0) * s.z),
qRound(SCALE_HANDLES_SIZE * s.z), qRound(SCALE_HANDLES_SIZE * s.z));
}
void CADrawable::drawVScaleHandles(QPainter* p, CADrawSettings s)
{
p->setPen(QPen(s.color));
p->drawRect(s.x + qRound((width() * s.z) / 2 - (SCALE_HANDLES_SIZE * s.z) / 2), s.y - qRound((SCALE_HANDLES_SIZE * s.z) / 2),
qRound(SCALE_HANDLES_SIZE * s.z), qRound(SCALE_HANDLES_SIZE * s.z));
p->drawRect(s.x + qRound((width() * s.z) / 2 - (SCALE_HANDLES_SIZE * s.z) / 2), s.y + qRound(((height() - SCALE_HANDLES_SIZE / 2.0) * s.z)),
qRound(SCALE_HANDLES_SIZE * s.z), qRound(SCALE_HANDLES_SIZE * s.z));
}
| 1,671
|
C++
|
.cpp
| 37
| 41.513514
| 144
| 0.653964
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,315
|
drawablefiguredbassnumber.cpp
|
canorusmusic_canorus/src/layout/drawablefiguredbassnumber.cpp
|
/*!
Copyright (c) 2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablefiguredbassnumber.h"
#include "canorus.h"
#include "layout/drawablefiguredbasscontext.h"
#include "score/figuredbassmark.h"
#include <QPainter>
#include <QPen>
const double CADrawableFiguredBassNumber::DEFAULT_NUMBER_SIZE = 17;
CADrawableFiguredBassNumber::CADrawableFiguredBassNumber(CAFiguredBassMark* f, int number, CADrawableFiguredBassContext* context, double x, double y)
: CADrawableMusElement(f, context, x, y)
, _number(number)
{
setDrawableMusElementType(DrawableFiguredBassNumber);
int textWidth = 11;
setWidth(textWidth < 11 ? 11 : textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_NUMBER_SIZE) * figuredBassMark()->numbers().size());
}
CADrawableFiguredBassNumber::~CADrawableFiguredBassNumber()
{
}
void CADrawableFiguredBassNumber::draw(QPainter* p, const CADrawSettings s)
{
QPen pen(s.color);
pen.setWidth(qRound(1.2 * s.z));
pen.setCapStyle(Qt::RoundCap);
p->setPen(pen);
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_NUMBER_SIZE * s.z * 1.3));
p->setFont(font);
QString accs;
if (figuredBassMark()->accs().contains(_number)) {
if (figuredBassMark()->accs()[_number] == -2) {
accs += QString(CACanorus::fetaCodepoint("accidentals.flatflat"));
} else if (figuredBassMark()->accs()[_number] == -1) {
accs += QString(CACanorus::fetaCodepoint("accidentals.flat"));
} else if (figuredBassMark()->accs()[_number] == 0) {
accs += QString(CACanorus::fetaCodepoint("accidentals.natural"));
} else if (figuredBassMark()->accs()[_number] == 1) {
accs += QString(CACanorus::fetaCodepoint("accidentals.sharp"));
} else if (figuredBassMark()->accs()[_number] == 2) {
accs += QString(CACanorus::fetaCodepoint("accidentals.doublesharp"));
}
}
if (!accs.isEmpty()) {
p->drawText(s.x, s.y + qRound(0.45 * DEFAULT_NUMBER_SIZE * s.z), accs);
}
QString text;
if (_number) {
text += QString::number(_number);
} else {
text += " ";
}
p->drawText(s.x + (accs.isEmpty() ? 0 : (static_cast<int>(8 * s.z))), s.y + qRound(0.8 * DEFAULT_NUMBER_SIZE * s.z), text);
}
CADrawableFiguredBassNumber* CADrawableFiguredBassNumber::clone(CADrawableContext* c)
{
return new CADrawableFiguredBassNumber(
figuredBassMark(),
_number,
(c ? static_cast<CADrawableFiguredBassContext*>(c) : static_cast<CADrawableFiguredBassContext*>(drawableContext())),
xPos(),
yPos());
}
| 2,809
|
C++
|
.cpp
| 67
| 36.716418
| 149
| 0.680337
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,316
|
drawablemidinote.cpp
|
canorusmusic_canorus/src/layout/drawablemidinote.cpp
|
/*!
Copyright (c) 2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QBrush>
#include <QPainter>
#include <QPen>
#include "layout/drawablemidinote.h"
#include "layout/drawablestaff.h"
#include "score/midinote.h"
CADrawableMidiNote::CADrawableMidiNote(CAMidiNote* midiNote, CADrawableStaff* c, double x, double y)
: CADrawableMusElement(midiNote, c, x, y)
{
setDrawableMusElementType(DrawableMidiNote);
setNeededSpaceWidth(midiNote->timeLength() / 8.0);
setNeededSpaceHeight(c->lineSpace());
}
CADrawableMidiNote::~CADrawableMidiNote()
{
}
void CADrawableMidiNote::draw(QPainter* p, CADrawSettings s)
{
QBrush brush(s.color);
p->fillRect(s.x, s.y, qRound(neededSpaceWidth() * s.z), qRound(neededSpaceHeight() * s.z), brush);
}
CADrawableMidiNote* CADrawableMidiNote::clone(CADrawableContext* newContext)
{
return new CADrawableMidiNote(static_cast<CAMidiNote*>(_musElement), static_cast<CADrawableStaff*>((newContext) ? newContext : _drawableContext), _xPos, _yPos);
}
| 1,153
|
C++
|
.cpp
| 30
| 36.166667
| 164
| 0.77509
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,317
|
drawablelyricscontext.cpp
|
canorusmusic_canorus/src/layout/drawablelyricscontext.cpp
|
/*!
Copyright (c) 2007-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablelyricscontext.h"
#include "layout/drawablesyllable.h"
#include "score/lyricscontext.h"
#include <QBrush>
#include <QPainter>
/*!
Vertical space between the top edge of the lyrics context and the top border of the lyrcs text.
*/
const double CADrawableLyricsContext::DEFAULT_TEXT_VERTICAL_SPACING = 3;
/*!
Drawable instance of the lyrics context.
\sa CALyricsContext
*/
CADrawableLyricsContext::CADrawableLyricsContext(CALyricsContext* c, double x, double y)
: CADrawableContext(c, x, y)
{
setDrawableContextType(DrawableLyricsContext);
setWidth(0);
setHeight(CADrawableSyllable::DEFAULT_TEXT_SIZE + 2 * DEFAULT_TEXT_VERTICAL_SPACING);
}
CADrawableLyricsContext::~CADrawableLyricsContext()
{
}
CADrawableLyricsContext* CADrawableLyricsContext::clone()
{
return new CADrawableLyricsContext(lyricsContext(), xPos(), yPos());
}
void CADrawableLyricsContext::draw(QPainter* p, const CADrawSettings s)
{
QColor bColor = Qt::green;
bColor.setAlphaF(0.2);
p->fillRect(0, s.y, s.w, qRound(height() * s.z), QBrush(bColor));
}
| 1,303
|
C++
|
.cpp
| 38
| 32.052632
| 96
| 0.778662
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,318
|
drawablecontext.cpp
|
canorusmusic_canorus/src/layout/drawablecontext.cpp
|
/*!
Copyright (c) 2006-2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "layout/drawablecontext.h"
CADrawableContext::CADrawableContext(CAContext* c, double x, double y)
: CADrawable(x, y)
, _context(c)
{
setDrawableType(CADrawable::DrawableContext);
}
/*!
Returns a list of drawable music elements the current drawable context includes between
the horizontal coordinates \a x1 and \a x2.
The element is in a list already if only part of the element is touched by the region.
That is the first returned element's left border is smaller than \a x1 and the last returned element's
right border is larger than \a x2.
*/
QList<CADrawableMusElement*> CADrawableContext::findInRange(double x1, double x2)
{
//int i;
QList<CADrawableMusElement*> list;
for (int i = 0; i < _drawableMusElementList.size(); i++) {
if (static_cast<CADrawable*>(_drawableMusElementList[i])->xPos() <= x2 && // The object is normal and fits into the area
static_cast<CADrawable*>(_drawableMusElementList[i])->xPos() + static_cast<CADrawable*>(_drawableMusElementList[i])->width() >= x1) {
list << _drawableMusElementList[i];
}
}
return list;
}
| 1,346
|
C++
|
.cpp
| 31
| 39.709677
| 145
| 0.726926
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,319
|
drawablenote.cpp
|
canorusmusic_canorus/src/layout/drawablenote.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "layout/drawablenote.h"
#include "canorus.h"
#include "layout/drawableaccidental.h"
#include "layout/drawablecontext.h"
#include "layout/drawablestaff.h"
#include "score/staff.h"
#include "score/voice.h"
#include <QPainter>
#include <iostream>
const double CADrawableNote::HUNDREDTWENTYEIGHTH_STEM_LENGTH = 50;
const double CADrawableNote::SIXTYFOURTH_STEM_LENGTH = 43;
const double CADrawableNote::THIRTYSECOND_STEM_LENGTH = 37;
const double CADrawableNote::SIXTEENTH_STEM_LENGTH = 31;
const double CADrawableNote::EIGHTH_STEM_LENGTH = 31;
const double CADrawableNote::QUARTER_STEM_LENGTH = 31;
const double CADrawableNote::HALF_STEM_LENGTH = 31;
const double CADrawableNote::QUARTER_YPOS_DELTA = 21;
const double CADrawableNote::HALF_YPOS_DELTA = 23;
/*!
Default constructor.
\param x coordinate represents the left border of the notehead.
\param y coordinate represents the center of the notehead.
*/
CADrawableNote::CADrawableNote(CANote* n, CADrawableContext* drawableContext, double x, double y, bool shadowNote, CADrawableAccidental* drawableAcc)
: CADrawableMusElement(n, drawableContext, x, y)
{
_drawableMusElementType = CADrawableMusElement::DrawableNote;
_drawableAcc = drawableAcc;
_stemDirection = note()->actualStemDirection();
// Notehead widths are hardcoded below; it's possible to determine them at runtime using QFontMetrics, if necessary.
switch (n->playableLength().musicLength()) {
case CAPlayableLength::HundredTwentyEighth:
case CAPlayableLength::SixtyFourth:
case CAPlayableLength::ThirtySecond:
case CAPlayableLength::Sixteenth:
case CAPlayableLength::Eighth:
case CAPlayableLength::Quarter:
_noteHeadGlyphName = "noteheads.s2";
_penWidth = 1.2;
setWidth(11);
setHeight(10);
break;
case CAPlayableLength::Half:
_noteHeadGlyphName = "noteheads.s1";
_penWidth = 1.3;
setWidth(12);
setHeight(10);
break;
case CAPlayableLength::Whole:
_noteHeadGlyphName = "noteheads.s0";
_penWidth = 0;
setWidth(17);
setHeight(8);
break;
case CAPlayableLength::Breve:
_noteHeadGlyphName = "noteheads.sM1";
_penWidth = 0;
setWidth(18);
setHeight(8);
break;
case CAPlayableLength::Undefined:
fprintf(stderr, "Warning: CADrawableNote::CADrawableNote - Unhandled Length %d\n", n->playableLength().musicLength());
break;
}
setYPos(y - height() / 2.0);
setXPos(x);
int mlength = n->playableLength().musicLength();
switch (mlength) {
case CAPlayableLength::HundredTwentyEighth:
/// \todo Emmentaler font doesn't have 128th, 64th flag is drawn instead! Need to somehow compose the 128th flag? -Matevz
_stemLength = HUNDREDTWENTYEIGHTH_STEM_LENGTH;
_flagUpGlyphName = "flags.u7";
_flagDownGlyphName = "flags.d7";
break;
case CAPlayableLength::SixtyFourth:
_stemLength = SIXTYFOURTH_STEM_LENGTH;
_flagUpGlyphName = "flags.u6";
_flagDownGlyphName = "flags.d6";
break;
case CAPlayableLength::ThirtySecond:
_stemLength = THIRTYSECOND_STEM_LENGTH;
_flagUpGlyphName = "flags.u5";
_flagDownGlyphName = "flags.d5";
break;
case CAPlayableLength::Sixteenth:
_stemLength = SIXTEENTH_STEM_LENGTH;
_flagUpGlyphName = "flags.u4";
_flagDownGlyphName = "flags.d4";
break;
case CAPlayableLength::Eighth:
_stemLength = EIGHTH_STEM_LENGTH;
_flagUpGlyphName = "flags.u3";
_flagDownGlyphName = "flags.d3";
break;
case CAPlayableLength::Quarter:
_stemLength = QUARTER_STEM_LENGTH;
break;
case CAPlayableLength::Half:
_stemLength = HALF_STEM_LENGTH;
break;
case CAPlayableLength::Whole:
case CAPlayableLength::Breve:
case CAPlayableLength::Undefined:
if (mlength < 0 /*|| mlength > HundredTwentyEighth*/) // Currently no refined check done
fprintf(stderr, "Warning: CADrawableNote::CADrawableNote - Unhandled length %d", mlength);
break;
}
_noteHeadWidth = width();
if (n->playableLength().dotted()) {
setWidth(width() + 3);
for (int i = 0; i < n->playableLength().dotted(); i++)
setWidth(width() + 2);
}
_shadowNote = shadowNote;
_drawLedgerLines = true;
}
CADrawableNote::~CADrawableNote()
{
}
void CADrawableNote::draw(QPainter* p, CADrawSettings s)
{
QFont font("Emmentaler");
font.setPixelSize(qRound(35 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
QPen pen;
// Draw ledger lines
if (_drawLedgerLines && drawableContext() && drawableContext()->drawableContextType() == CADrawableContext::DrawableStaff && note() && note()->voice() && note()->voice()->staff() && ((note()->notePosition() <= -2) || // note is below the staff
(note()->notePosition() >= note()->voice()->staff()->numberOfLines() * 2) // note is above the staff
)) {
int direction = (note()->notePosition() > 0 ? 1 : -1); // 1 falling, -1 rising
double ledgerDist = static_cast<CADrawableStaff*>(drawableContext())->lineSpace() * s.z; // distance between the ledger lines - notehead height
// draw ledger lines in direction from the notehead to staff
qreal ry = (direction == 1) ? _drawableContext->yPos() : _drawableContext->yPos() + (_drawableContext->height());
ry -= s.worldY;
ry *= s.z;
QPen pen(s.color);
pen.setWidthF(1.0 * s.z);
p->setPen(pen);
for (int i = 0;
i < ((note()->notePosition() * direction - ((direction > 0) ? ((note()->voice()->staff()->numberOfLines() - 1) * 2) : 0)) / 2);
++i) {
ry -= ledgerDist * direction;
p->drawLine(qRound(s.x - 4 * s.z), qRound(ry), qRound(s.x + (_noteHeadWidth + 4) * s.z), qRound(ry));
}
}
// Draw notehead
s.y += height() * s.z / 2;
p->drawText(s.x, s.y, QString(CACanorus::fetaCodepoint(_noteHeadGlyphName)));
if (note()->noteLength().musicLength() >= CAPlayableLength::Half) {
// Draw stem and flag
pen.setWidthF(_penWidth * s.z);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(s.color);
p->setPen(pen);
if (_stemDirection == CANote::StemUp) {
s.x += qRound(_noteHeadWidth * s.z); // increase X-offset before drawing the stem
p->drawLine(s.x, qRound(s.y - 1 * s.z), s.x, s.y - qRound(_stemLength * s.z));
if (note()->noteLength().musicLength() >= CAPlayableLength::Eighth) {
p->drawText(qRound(s.x + 0.6 * s.z), qRound(s.y - _stemLength * s.z), QString(CACanorus::fetaCodepoint(_flagUpGlyphName)));
s.x += qRound(6 * s.z); // additional X-offset for dots because of the flag on the right
}
} else {
s.x += qRound(0.6 * s.z);
p->drawLine(s.x, qRound(s.y + 1 * s.z), s.x, s.y + qRound(_stemLength * s.z));
if (note()->noteLength().musicLength() >= CAPlayableLength::Eighth) {
p->drawText(qRound(s.x + 0.4 * s.z), qRound(s.y + (_stemLength + 5) * s.z), QString(CACanorus::fetaCodepoint(_flagDownGlyphName)));
}
s.x += qRound(_noteHeadWidth * s.z); // increase X-offset after drawing the stem
}
} else {
s.x += qRound(_noteHeadWidth * s.z); // increase X-offset for drawing the dots
}
// Draw Dots
double delta = 4 * s.z;
for (int i = 0; i < note()->playableLength().dotted(); i++) {
pen.setWidth(qRound(2.7 * s.z) + 1);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(s.color);
p->setPen(pen);
p->drawPoint(qRound(s.x + delta), qRound(s.y - 1.7 * s.z));
delta += 4 * s.z;
}
s.x += qRound(delta);
}
CADrawableNote* CADrawableNote::clone(CADrawableContext* newContext)
{
return new CADrawableNote(note(), (newContext) ? newContext : _drawableContext, xPos(), yPos() + height() / 2);
}
| 8,683
|
C++
|
.cpp
| 194
| 36.097938
| 290
| 0.612785
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,320
|
drawableaccidental.cpp
|
canorusmusic_canorus/src/layout/drawableaccidental.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QFont>
#include <QPainter>
#include "canorus.h"
#include "layout/drawableaccidental.h"
#include "layout/drawableclef.h"
#include "layout/drawablecontext.h"
#include "score/muselement.h"
/*!
Default constructor.
\param accs Type of the accidental: 0 - natural, -1 - flat, +1 - sharp, -2 doubleflat, +2 - cross etc.
\param musElement Pointer to the according musElement which the accidental represents (usually a CANote or CAKeySignature).
\param drawableContext Pointer to the according drawable context which the accidental belongs to (usually CADrawableStaff or CADrawableFiguredBass).
\param x Left X-coordinate of the accidental.
\param y Center Y-coordinate of the accidental.
*/
CADrawableAccidental::CADrawableAccidental(signed char accs, CAMusElement* musElement, CADrawableContext* drawableContext, double x, double y)
: CADrawableMusElement(musElement, drawableContext, x, y)
{
setDrawableMusElementType(DrawableAccidental);
setSelectable(false);
setWidth(8);
setHeight(14);
_accs = accs;
if (accs == 0) {
setYPos(y - height() / 2);
} else if (accs == 1) {
setYPos(y - height() / 2);
} else if (accs == -1) {
setYPos(y - height() / 2 - 5);
} else if (accs == 2) {
setHeight(6);
setYPos(y - height() / 2);
} else if (accs == -2) {
setYPos(y - height() / 2 - 5);
setXPos(x);
setWidth(12);
}
_centerX = x;
_centerY = y;
}
CADrawableAccidental::~CADrawableAccidental()
{
}
void CADrawableAccidental::draw(QPainter* p, CADrawSettings s)
{
QFont font("Emmentaler");
font.setPixelSize(qRound(34 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
switch (_accs) {
case 0:
p->drawText(s.x, s.y + qRound(height() / 2 * s.z), QString(CACanorus::fetaCodepoint("accidentals.natural")));
break;
case 1:
p->drawText(s.x, s.y + qRound((height() / 2 + 0.3) * s.z), QString(CACanorus::fetaCodepoint("accidentals.sharp")));
break;
case -1:
p->drawText(s.x, s.y + qRound((height() / 2 + 5) * s.z), QString(CACanorus::fetaCodepoint("accidentals.flat")));
break;
case 2:
p->drawText(s.x, s.y + qRound(height() / 2 * s.z), QString(CACanorus::fetaCodepoint("accidentals.doublesharp")));
break;
case -2:
p->drawText(s.x, s.y + qRound((height() / 2 + 5) * s.z), QString(CACanorus::fetaCodepoint("accidentals.flatflat")));
break;
}
}
CADrawableAccidental* CADrawableAccidental::clone(CADrawableContext* newContext)
{
return new CADrawableAccidental(_accs, _musElement, (newContext) ? newContext : _drawableContext, _centerX, _centerY);
}
| 2,912
|
C++
|
.cpp
| 76
| 33.776316
| 149
| 0.674929
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,321
|
drawablesyllable.cpp
|
canorusmusic_canorus/src/layout/drawablesyllable.cpp
|
/*!
Copyright (c) 2007-2022, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablesyllable.h"
#include "layout/drawablelyricscontext.h"
#include "score/lyricscontext.h"
#include <QFont>
#include <QFontMetrics>
#include <QPainter>
const double CADrawableSyllable::DEFAULT_TEXT_SIZE = 16;
const double CADrawableSyllable::DEFAULT_DASH_LENGTH = 5;
CADrawableSyllable::CADrawableSyllable(CASyllable* s, CADrawableLyricsContext* c, double x, double y)
: CADrawableMusElement(s, c, x, y)
{
setDrawableMusElementType(DrawableSyllable);
QFont font("Century Schoolbook L");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetrics fm(font);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = fm.horizontalAdvance(textToDrawableText(s->text()));
#else
int textWidth = fm.width(textToDrawableText(s->text()));
#endif
setWidth(textWidth < 11 ? 11 : textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
}
CADrawableSyllable::~CADrawableSyllable()
{
}
void CADrawableSyllable::draw(QPainter* p, const CADrawSettings s)
{
QPen pen(s.color);
pen.setWidth(qRound(1.2 * s.z));
pen.setCapStyle(Qt::RoundCap);
p->setPen(pen);
QFont font("Century Schoolbook L");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
QString text = syllable()->text();
// Show "space" dot when selected, if empty and not part of hyphen/melisma.
if (text.isEmpty() && !syllable()->hyphenStart() && !syllable()->melismaStart()) {
text = CADrawableMusElement::EMPTY_PLACEHOLDER;
}
// Strip melisma.
text = textToDrawableText(text);
p->drawText(s.x, s.y + qRound(height() * s.z), text);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = QFontMetrics(font).horizontalAdvance(text);
#else
int textWidth = QFontMetrics(font).width(text);
#endif
if (syllable()->hyphenStart() && (width() * s.z - textWidth) > qRound(DEFAULT_DASH_LENGTH * s.z)) {
p->drawLine(qRound(s.x + width() * s.z * 0.5 + 0.5 * textWidth - 0.5 * s.z * DEFAULT_DASH_LENGTH), s.y + qRound(height() * s.z * 0.7),
qRound(s.x + width() * s.z * 0.5 + 0.5 * textWidth + 0.5 * s.z * DEFAULT_DASH_LENGTH), s.y + qRound(height() * s.z * 0.7));
} else if (syllable()->melismaStart() && (width() * s.z - textWidth) > qRound(DEFAULT_DASH_LENGTH * s.z)) {
p->drawLine(s.x + textWidth + (!text.isEmpty()?1.5*s.z:0), s.y + qRound(height() * s.z),
qRound(s.x + width() * s.z), s.y + qRound(height() * s.z));
}
}
CADrawableSyllable* CADrawableSyllable::clone(CADrawableContext* c)
{
return new CADrawableSyllable(
syllable(),
(c ? static_cast<CADrawableLyricsContext*>(c) : static_cast<CADrawableLyricsContext*>(drawableContext())),
xPos(),
yPos());
}
| 3,013
|
C++
|
.cpp
| 69
| 39.608696
| 142
| 0.681446
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,322
|
drawablerest.cpp
|
canorusmusic_canorus/src/layout/drawablerest.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "layout/drawablerest.h"
#include "canorus.h"
#include "layout/drawablecontext.h"
#include "layout/drawablestaff.h"
#include "score/rest.h"
#include <QPainter>
CADrawableRest::CADrawableRest(CARest* rest, CADrawableContext* drawableContext, double x, double y)
: CADrawableMusElement(rest, drawableContext, x, y)
{
_drawableMusElementType = CADrawableMusElement::DrawableRest;
if (drawableContext->drawableContextType() != CADrawableContext::DrawableStaff)
return;
switch (rest->playableLength().musicLength()) {
case CAPlayableLength::HundredTwentyEighth:
setWidth(16);
setHeight(49);
break;
case CAPlayableLength::SixtyFourth:
setWidth(14);
setHeight(41);
break;
case CAPlayableLength::ThirtySecond:
setWidth(12);
setHeight(33);
setYPos(y + 2);
break;
case CAPlayableLength::Sixteenth:
setWidth(10);
setHeight(24);
setYPos(y + static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Eighth:
setWidth(8);
setHeight(17);
setYPos(y + static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Quarter:
setWidth(8);
setHeight(20);
setYPos(y + static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Half:
setWidth(12);
setHeight(5);
setYPos(y + 1.5 * static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Whole:
setWidth(12);
setHeight(5);
//values in constructor are the notehead center coords. yPos represents the top of the stem.
setYPos(y + static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Breve:
setWidth(4);
setHeight(9);
setYPos(y + static_cast<CADrawableStaff*>(drawableContext)->lineSpace());
break;
case CAPlayableLength::Undefined:
fprintf(stderr, "Warning: CADrawableRest::CADrawableRest - Unhandled Length %d", rest->playableLength().musicLength());
break;
}
_restWidth = _width;
if (rest->playableLength().dotted()) {
setWidth(width() + 3);
for (int i = 0; i < rest->playableLength().dotted(); i++)
setWidth(width() + 2);
}
}
CADrawableRest::~CADrawableRest()
{
}
CADrawableRest* CADrawableRest::clone(CADrawableContext* newContext)
{
return new CADrawableRest(rest(), (newContext) ? newContext : _drawableContext, xPos(), yPos());
}
void CADrawableRest::draw(QPainter* p, CADrawSettings s)
{
QFont font("Emmentaler");
font.setPixelSize(qRound(35 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
QPen pen;
switch (rest()->playableLength().musicLength()) {
case CAPlayableLength::HundredTwentyEighth: {
p->drawText(qRound(s.x + 4 * s.z), qRound(s.y + (2.6 * (static_cast<CADrawableStaff*>(_drawableContext))->lineSpace()) * s.z), QString(CACanorus::fetaCodepoint("rests.7")));
break;
}
case CAPlayableLength::SixtyFourth: {
p->drawText(qRound(s.x + 3 * s.z), qRound(s.y + (1.75 * (static_cast<CADrawableStaff*>(_drawableContext))->lineSpace()) * s.z), QString(CACanorus::fetaCodepoint("rests.6")));
break;
}
case CAPlayableLength::ThirtySecond: {
p->drawText(qRound(s.x + 2.5 * s.z), qRound(s.y + (1.8 * (static_cast<CADrawableStaff*>(_drawableContext))->lineSpace()) * s.z), QString(CACanorus::fetaCodepoint("rests.5")));
break;
}
case CAPlayableLength::Sixteenth: {
p->drawText(qRound(s.x + 1 * s.z), qRound(s.y + ((static_cast<CADrawableStaff*>(_drawableContext))->lineSpace() - 0.9) * s.z), QString(CACanorus::fetaCodepoint("rests.4")));
break;
}
case CAPlayableLength::Eighth: {
p->drawText(s.x, qRound(s.y + ((static_cast<CADrawableStaff*>(_drawableContext))->lineSpace() - 0.9) * s.z), QString(CACanorus::fetaCodepoint("rests.3")));
break;
}
case CAPlayableLength::Quarter: {
p->drawText(s.x, qRound(s.y + 0.5 * height() * s.z), QString(CACanorus::fetaCodepoint("rests.2")));
break;
}
case CAPlayableLength::Half: {
p->drawText(s.x, qRound(s.y + height() * s.z + 0.5), QString(CACanorus::fetaCodepoint("rests.1")));
break;
}
case CAPlayableLength::Whole: {
p->drawText(s.x, s.y, QString(CACanorus::fetaCodepoint("rests.0")));
break;
}
case CAPlayableLength::Breve: {
p->drawText(s.x, qRound(s.y + height() * s.z), QString(CACanorus::fetaCodepoint("rests.M1")));
break;
}
case CAPlayableLength::Undefined:
fprintf(stderr, "Warning: CADrawableRest::draw - Unhandled Length %d", rest()->playableLength().musicLength());
break;
}
///////////////
// Draw Dots //
///////////////
double delta = 4 * s.z;
for (int i = 0; i < rest()->playableLength().dotted(); i++) {
pen.setWidth(qRound(2.7 * s.z + 0.5) + 1);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(s.color);
p->setPen(pen);
p->drawPoint(qRound(s.x + _restWidth * s.z + delta), qRound(s.y + 0.3 * _height * s.z));
delta += 3 * s.z;
}
}
| 5,581
|
C++
|
.cpp
| 141
| 33.120567
| 183
| 0.639468
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,323
|
drawablenotecheckererror.cpp
|
canorusmusic_canorus/src/layout/drawablenotecheckererror.cpp
|
/*!
Copyright (c) 2015-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QPainter>
#include <QPen>
#include "layout/drawablenotecheckererror.h"
CADrawableNoteCheckerError::CADrawableNoteCheckerError(CANoteCheckerError* nce, CADrawable* dTarget)
: CADrawable(dTarget->xPos() - 5, dTarget->yPos() + dTarget->height() + 5)
{
(void)nce;
setWidth(dTarget->width() + 10);
setHeight(5);
}
void CADrawableNoteCheckerError::draw(QPainter* p, const CADrawSettings s)
{
QPen pen;
pen.setWidth(2);
pen.setCapStyle(Qt::SquareCap);
pen.setColor(s.color);
p->setPen(pen);
// draw wavy line
int Xstep = 2;
int Ystep = 1;
int oldX = s.x;
int x = oldX + 2;
int oldY = s.y;
int y = oldY + Ystep;
while (oldX < s.x + width() * s.z) {
p->drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
x += Xstep;
y += Ystep;
Ystep *= (-1);
}
}
CADrawable* CADrawableNoteCheckerError::clone()
{
return nullptr; //TODO: Kinda tricky, we require the instance of the new cloned drawable target
}
| 1,238
|
C++
|
.cpp
| 42
| 25.285714
| 100
| 0.664424
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,324
|
drawablestaff.cpp
|
canorusmusic_canorus/src/layout/drawablestaff.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QDebug>
#include <QPainter>
#include "layout/drawablebarline.h"
#include "layout/drawableclef.h"
#include "layout/drawablekeysignature.h"
#include "layout/drawablestaff.h"
#include "layout/drawabletimesignature.h"
#include "score/barline.h"
#include "score/clef.h"
#include "score/keysignature.h"
#include "score/note.h"
#include "score/timesignature.h"
const double CADrawableStaff::STAFFLINE_WIDTH = 0.8;
CADrawableStaff::CADrawableStaff(CAStaff* s, double x, double y)
: CADrawableContext(s, x, y)
{
_drawableContextType = CADrawableContext::DrawableStaff;
setWidth(0);
setHeight(37);
}
void CADrawableStaff::draw(QPainter* p, const CADrawSettings s)
{
QPen pen;
pen.setWidthF(STAFFLINE_WIDTH * s.z);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(s.color);
p->setPen(pen);
double dy = lineSpace() * s.z;
for (int i = 0; i < staff()->numberOfLines(); i++) {
p->drawLine(0, qRound(s.y + dy * i),
s.w, qRound(s.y + dy * i));
}
}
CADrawableStaff* CADrawableStaff::clone()
{
CADrawableStaff* d = new CADrawableStaff(staff(), xPos(), yPos());
return d;
}
/*!
Returns the center Y coordinate of the given note in this staff.
\param pitch Note pitch which the following coordinates are being calculated for.
\param clef Corresponding clef.
\return Center of a space/line of a staff in absolute world units.
*/
double CADrawableStaff::calculateCenterYCoord(int pitch, CAClef* clef)
{
// middle c in logical pitch is 28.
return yPos() + height() - (((pitch - 28) + (clef ? clef->c1() : -2)) / 2.0) * lineSpace();
}
/*!
This is an overloaded member function, provided for convenience.
Returns the center Y coordinate of the given note in this staff.
\param note Note which the following coordinates are being calculated.
\param x X coordinate of the note.
\return Center of a space/line of a staff in absolute world units.
*/
double CADrawableStaff::calculateCenterYCoord(CANote* note, double x)
{
CAClef* clef = getClef(x);
return calculateCenterYCoord(note->diatonicPitch().noteName(), clef);
}
/*!
This is an overloaded member function, provided for convenience.
Returns the center Y coordinate of the given note in this staff.
\param pitch Note pitch which the following coordinates are being calculated for.
\param x X coordinate of the note.
\return Center of a space/line of a staff in absolute world units.
*/
double CADrawableStaff::calculateCenterYCoord(int pitch, double x)
{
CAClef* clef = getClef(x);
return calculateCenterYCoord(pitch, clef);
}
/*!
This is an overloaded member function, provided for convenience.
Returns the center Y coordinate of the given note in this staff.
\param note Note which the following coordinates are being calculated.
\param clef Corresponding clef.
\return Center of a space/line of a staff in absolute world units.
*/
double CADrawableStaff::calculateCenterYCoord(CANote* note, CAClef* clef)
{
return calculateCenterYCoord(note->diatonicPitch().noteName(), clef);
}
/*!
Rounds the given Y coordinate to the nearest one so it fits a line or a space (ledger lines too, if needed) in a staff.
\return Center of the nearest space/line of a staff, whichever is closer in absolute world units.
*/
double CADrawableStaff::calculateCenterYCoord(double y)
{
double newY = (y - yPos()) / (lineSpace() / 2);
newY += 0.5 * ((y - yPos() < 0) ? -1 : 1); //round to nearest line/space
newY = static_cast<double>(static_cast<int>(newY));
return yPos() + ((newY) * (lineSpace() / 2));
}
/*!
Calculates the note pitch on the given clef and absolute world Y coordinate.
\param x X coordinate in absolute world units.
\param y Y coordinate in absolute world units.
\return Note pitch in logical units.
*/
int CADrawableStaff::calculatePitch(double x, double y)
{
CAClef* clef = getClef(x);
double yC1 = yPos() + height() - (clef ? clef->c1() : -2) * (lineSpace() / 2); // Y coordinate of c1 of the current staff
// middle c = 28
return qRound(28 - (y - yC1) / (lineSpace() / 2.0));
}
/*!
Adds a clef \a clef to the clef list for faster search of the current clef in the staff.
*/
void CADrawableStaff::addClef(CADrawableClef* clef)
{
int i;
for (i = 0; ((i < _drawableClefList.size()) && (clef->xPos() > _drawableClefList[i]->xPos())); i++)
;
_drawableClefList.insert(i, clef);
}
/*!
Removes the given clef from the clefs-lookup list.
Returns True, if the clef was successfully removed, False otherwise.
*/
bool CADrawableStaff::removeClef(CADrawableClef* clef)
{
return _drawableClefList.removeAll(clef);
}
/*!
Returns the pointer to the last clef placed before the given X-coordinate.
*/
CAClef* CADrawableStaff::getClef(double x)
{
int i;
for (i = 0; ((i < _drawableClefList.size()) && (x > _drawableClefList[i]->xPos())); i++)
;
return ((--i < 0) ? nullptr : _drawableClefList[i]->clef());
}
/*!
Returns accidentals at the given X-coordinate and pitch. eg. -1 for one flat, 2 for two sharps.
This is useful to determine the note's pitch to be placed in certain measure or part of the measure,
if accidentals have been placed before.
*/
int CADrawableStaff::getAccs(double x, int pitch)
{
CAKeySignature* key = getKeySignature(x);
//find nearest left element
int i;
for (i = 0; i < _drawableMusElementList.size() && _drawableMusElementList[i]->xPos() < x; i++)
;
i--;
while (i >= 0 && _drawableMusElementList[i]->drawableMusElementType() != CADrawableMusElement::DrawableBarline && _drawableMusElementList[i]->drawableMusElementType() != CADrawableMusElement::DrawableKeySignature && (!(_drawableMusElementList[i]->drawableMusElementType() == CADrawableMusElement::DrawableNote && (static_cast<CANote*>(_drawableMusElementList[i]->musElement())->diatonicPitch().noteName() == pitch)))) { // go back until the barline, key signature or note with accidentals is found
i--;
}
if (i == -1)
return 0;
if (_drawableMusElementList[i]->drawableMusElementType() == CADrawableMusElement::DrawableBarline || _drawableMusElementList[i]->drawableMusElementType() == CADrawableMusElement::DrawableKeySignature)
return (key ? key->accidentals()[pitch < 0 ? 6 - (-pitch - 1) % 7 : pitch % 7] : 0); // watch: % operator with negative numbers is implementation dependent
else // note before
return (static_cast<CANote*>(_drawableMusElementList[i]->musElement())->diatonicPitch().accs());
}
/*!
Adds a key signature \a keySig to the key signatures list for faster search of the current key signature in the staff.
*/
void CADrawableStaff::addKeySignature(CADrawableKeySignature* keySig)
{
int i;
for (i = 0; ((i < _drawableKeySignatureList.size()) && (keySig->xPos() > _drawableKeySignatureList[i]->xPos())); i++)
;
_drawableKeySignatureList.insert(i, keySig);
}
/*!
Removes the given key signature from the key signatures-lookup list.
Returns True, if the key signature was successfully removed, False otherwise.
*/
bool CADrawableStaff::removeKeySignature(CADrawableKeySignature* keySig)
{
return _drawableKeySignatureList.removeAll(keySig);
}
/*!
* Helper function for getBarline() when doing the binary search over elements.
*/
bool CADrawableStaff::xDrawableBarlineLessThan(const CADrawableBarline* a, const double x)
{
return (a->xPos() < x);
}
/*
Returns the pointer to the last barline placed before the given X-coordinate.
This function is usually called when drawing the ruler.
*/
CABarline* CADrawableStaff::getBarline(double x)
{
QList<CADrawableBarline*>::const_iterator it = std::lower_bound(_drawableBarlineList.constBegin(), _drawableBarlineList.constEnd(), x, CADrawableStaff::xDrawableBarlineLessThan);
if (it != _drawableBarlineList.constBegin()) {
it--;
}
return ((it != _drawableBarlineList.constEnd()) ? ((*it)->barline()) : nullptr);
}
/*!
Adds a barline \a barlineto the barline list for faster search when drawing the ruler.
*/
void CADrawableStaff::addBarline(CADrawableBarline* barline)
{
int i;
for (i = 0; ((i < _drawableBarlineList.size()) && (barline->xPos() > _drawableBarlineList[i]->xPos())); i++)
;
_drawableBarlineList.insert(i, barline);
}
/*!
Removes the given barline from the barline-lookup list.
Returns True, if the barline was successfully removed, False otherwise.
*/
bool CADrawableStaff::removeBarline(CADrawableBarline* barline)
{
return _drawableBarlineList.removeAll(barline);
}
/*
Returns the pointer to the last key signature placed before the given X-coordinate.
*/
CAKeySignature* CADrawableStaff::getKeySignature(double x)
{
int i;
for (i = 0; ((i < _drawableKeySignatureList.size()) && (x > _drawableKeySignatureList[i]->xPos())); i++)
;
return ((--i < 0) ? nullptr : _drawableKeySignatureList[i]->keySignature());
}
/*!
Adds a time signature \a timeSig to the time signatures list for faster search of the current time signature in the staff.
*/
void CADrawableStaff::addTimeSignature(CADrawableTimeSignature* timeSig)
{
int i;
for (i = 0; ((i < _drawableTimeSignatureList.size()) && (timeSig->xPos() > _drawableTimeSignatureList[i]->xPos())); i++)
;
_drawableTimeSignatureList.insert(i, timeSig);
}
/*!
Removes the given time signature from the time signatures-lookup list.
Returns True, if the time signature was successfully removed, False otherwise.
*/
bool CADrawableStaff::removeTimeSignature(CADrawableTimeSignature* timeSig)
{
return _drawableTimeSignatureList.removeAll(timeSig);
}
/*!
Returns the pointer to the last time signature placed before the given X-coordinate.
*/
CATimeSignature* CADrawableStaff::getTimeSignature(double x)
{
int i;
for (i = 0; ((i < _drawableTimeSignatureList.size()) && (x > _drawableTimeSignatureList[i]->xPos())); i++)
;
return ((--i < 0) ? nullptr : _drawableTimeSignatureList[i]->timeSignature());
}
void CADrawableStaff::addMElement(CADrawableMusElement* elt)
{
switch (elt->drawableMusElementType()) {
case CADrawableMusElement::DrawableClef:
addClef(static_cast<CADrawableClef*>(elt));
break;
case CADrawableMusElement::DrawableKeySignature:
addKeySignature(static_cast<CADrawableKeySignature*>(elt));
break;
case CADrawableMusElement::DrawableTimeSignature:
addTimeSignature(static_cast<CADrawableTimeSignature*>(elt));
break;
case CADrawableMusElement::DrawableBarline:
addBarline(static_cast<CADrawableBarline*>(elt));
break;
case CADrawableMusElement::DrawableNote:
case CADrawableMusElement::DrawableRest:
case CADrawableMusElement::DrawableMidiNote:
case CADrawableMusElement::DrawableAccidental:
case CADrawableMusElement::DrawableSlur:
case CADrawableMusElement::DrawableTuplet:
case CADrawableMusElement::DrawableSyllable:
case CADrawableMusElement::DrawableFunctionMark:
case CADrawableMusElement::DrawableFunctionMarkSupport:
case CADrawableMusElement::DrawableFiguredBassNumber:
case CADrawableMusElement::DrawableMark:
case CADrawableMusElement::DrawableChordName:
// These elements are just added to the list but not handled specifically
//fprintf(stderr,"Warning: CADrawableStaff::addMElement - Unhandled element %d\n",elt->drawableMusElementType());
break;
}
_drawableMusElementList << elt;
}
int CADrawableStaff::removeMElement(CADrawableMusElement* elt)
{
switch (elt->drawableMusElementType()) {
case CADrawableMusElement::DrawableClef:
removeClef(static_cast<CADrawableClef*>(elt));
break;
case CADrawableMusElement::DrawableKeySignature:
removeKeySignature(static_cast<CADrawableKeySignature*>(elt));
break;
case CADrawableMusElement::DrawableTimeSignature:
removeTimeSignature(static_cast<CADrawableTimeSignature*>(elt));
break;
case CADrawableMusElement::DrawableNote:
case CADrawableMusElement::DrawableRest:
case CADrawableMusElement::DrawableMidiNote:
case CADrawableMusElement::DrawableBarline:
case CADrawableMusElement::DrawableAccidental:
case CADrawableMusElement::DrawableSlur:
case CADrawableMusElement::DrawableTuplet:
case CADrawableMusElement::DrawableSyllable:
case CADrawableMusElement::DrawableFunctionMark:
case CADrawableMusElement::DrawableFunctionMarkSupport:
case CADrawableMusElement::DrawableFiguredBassNumber:
case CADrawableMusElement::DrawableMark:
case CADrawableMusElement::DrawableChordName:
qDebug() << "Warning: CADrawableStaff::removeMElement - Unhandled element" << elt->drawableMusElementType();
break;
}
return _drawableMusElementList.removeAll(elt);
}
| 13,041
|
C++
|
.cpp
| 320
| 37.2375
| 501
| 0.735991
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,325
|
drawablefiguredbasscontext.cpp
|
canorusmusic_canorus/src/layout/drawablefiguredbasscontext.cpp
|
/*!
Copyright (c) 2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablefiguredbasscontext.h"
#include "layout/drawablefiguredbassnumber.h"
#include <QBrush>
#include <QPainter>
CADrawableFiguredBassContext::CADrawableFiguredBassContext(CAFiguredBassContext* c, double x, double y)
: CADrawableContext(c, x, y)
{
setDrawableContextType(DrawableFiguredBassContext);
setWidth(0);
setHeight(3 * CADrawableFiguredBassNumber::DEFAULT_NUMBER_SIZE);
}
CADrawableFiguredBassContext::~CADrawableFiguredBassContext()
{
}
CADrawableFiguredBassContext* CADrawableFiguredBassContext::clone()
{
return new CADrawableFiguredBassContext(figuredBassContext(), xPos(), yPos());
}
void CADrawableFiguredBassContext::draw(QPainter* p, const CADrawSettings s)
{
QColor bColor = Qt::cyan;
bColor.setAlphaF(0.2);
p->fillRect(0, s.y, s.w, qRound(height() * s.z), QBrush(bColor));
}
| 1,062
|
C++
|
.cpp
| 29
| 34.206897
| 103
| 0.790652
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,326
|
drawablechordnamecontext.cpp
|
canorusmusic_canorus/src/layout/drawablechordnamecontext.cpp
|
/*!
Copyright (c) 2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablechordnamecontext.h"
#include "layout/drawablechordname.h"
#include "score/chordnamecontext.h"
#include <QBrush>
#include <QPainter>
/*!
Vertical space between the top edge of the chord name context and the top border of the chord name.
*/
const double CADrawableChordNameContext::DEFAULT_CHORDNAME_VERTICAL_SPACING = 2;
/*!
Drawable instance of the chord name context.
\sa CAChordNameContext
*/
CADrawableChordNameContext::CADrawableChordNameContext(CAChordNameContext* c, double x, double y)
: CADrawableContext(c, x, y)
{
setDrawableContextType(DrawableChordNameContext);
setWidth(0);
setHeight(CADrawableChordName::DEFAULT_TEXT_SIZE + 2 * DEFAULT_CHORDNAME_VERTICAL_SPACING);
}
CADrawableChordNameContext::~CADrawableChordNameContext()
{
}
CADrawableChordNameContext* CADrawableChordNameContext::clone()
{
return new CADrawableChordNameContext(chordNameContext(), xPos(), yPos());
}
void CADrawableChordNameContext::draw(QPainter* p, const CADrawSettings s)
{
QColor bColor = Qt::darkBlue;
bColor.setAlphaF(0.2);
p->fillRect(0, s.y, s.w, qRound(height() * s.z), QBrush(bColor));
}
| 1,366
|
C++
|
.cpp
| 38
| 33.710526
| 100
| 0.788476
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,327
|
drawablekeysignature.cpp
|
canorusmusic_canorus/src/layout/drawablekeysignature.cpp
|
/*!
Copyright (c) 2006-2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QComboBox> // needed for populateComboBox()
#include <QPainter>
#include "layout/drawableaccidental.h"
#include "layout/drawablekeysignature.h"
#include "layout/drawablestaff.h"
#include "score/clef.h"
#include "score/keysignature.h"
/*!
Default constructor.
\a y marks the top line Y coordinate of the staff in absolute world units.
*/
CADrawableKeySignature::CADrawableKeySignature(CAKeySignature* keySig, CADrawableStaff* drawableStaff, double x, double y)
: CADrawableMusElement(keySig, drawableStaff, x, y)
{
setDrawableMusElementType(CADrawableMusElement::DrawableKeySignature);
double newX = x;
CAClef* clef = drawableStaff->getClef(x);
int idx, idx2; // pitches of accidentals
double minY = y, maxY = y;
CAKeySignature* prevKeySig = drawableStaff->getKeySignature(x);
if (prevKeySig) {
// get initial neutral-sharp position
idx = 3;
idx2 = 0;
while (idx + (clef ? clef->c1() : -2) - 28 < -1 || idx2 + (clef ? clef->c1() : -2) - 28 < -1) {
idx += 7;
idx2 += 7;
}
for (int i = 0; i < 7; idx += (i % 2 ? 4 : -3), i++) { // place neutrals for sharps
if ((prevKeySig->accidentals()[idx % 7] != 1) || ((prevKeySig->accidentals()[idx % 7] == 1) && (keySig->accidentals()[idx % 7] == 1)))
continue;
int curIdx = idx;
if (curIdx + (clef ? clef->c1() : -2) - 28 < -1)
curIdx += 7;
if (curIdx + (clef ? clef->c1() : -2) - 28 > drawableStaff->staff()->numberOfLines() * 2 - 1)
curIdx -= 7;
CADrawableAccidental* acc = new CADrawableAccidental(0, keySig, drawableStaff, newX, drawableStaff->calculateCenterYCoord(curIdx, x));
_drawableAccidentalList << acc;
newX += (acc->width() + 5);
if (acc->yPos() < minY)
minY = acc->yPos();
if (acc->yPos() + acc->height() > maxY)
maxY = acc->yPos() + acc->height();
}
// get initial neutral-flat position
idx = 6;
idx2 = 9;
while (idx + (clef ? clef->c1() : -2) - 28 < 0 || idx2 + (clef ? clef->c1() : -2) - 28 < 0) {
idx += 7;
idx2 += 7;
}
for (int i = 0; i < 7; idx += (i % 2 ? -4 : 3), i++) { // place neutrals for flats
if ((prevKeySig->accidentals()[idx % 7] != -1) || ((prevKeySig->accidentals()[idx % 7] == -1) && (keySig->accidentals()[idx % 7] == -1)))
continue;
int curIdx = idx;
if (curIdx + (clef ? clef->c1() : -2) - 28 < -1)
curIdx += 7;
if (curIdx + (clef ? clef->c1() : -2) - 28 > drawableStaff->staff()->numberOfLines() * 2 - 1)
curIdx -= 7;
CADrawableAccidental* acc = new CADrawableAccidental(0, keySig, drawableStaff, newX, drawableStaff->calculateCenterYCoord(curIdx, x));
_drawableAccidentalList << acc;
newX += (acc->width() + 5);
if (acc->yPos() < minY)
minY = acc->yPos();
if (acc->yPos() + acc->height() > maxY)
maxY = acc->yPos() + acc->height();
}
}
// get initial sharp position
idx = 3;
idx2 = 0;
while (idx + (clef ? clef->c1() : -2) - 28 < -1 || idx2 + (clef ? clef->c1() : -2) - 28 < -1) {
idx += 7;
idx2 += 7;
}
for (int i = 0; i < 7; idx += (i % 2 ? 4 : -3), i++) { // place sharps
if (keySig->accidentals()[idx % 7] != 1)
continue;
int curIdx = idx;
if (curIdx + (clef ? clef->c1() : -2) - 28 < -1)
curIdx += 7;
if (curIdx + (clef ? clef->c1() : -2) - 28 > drawableStaff->staff()->numberOfLines() * 2 - 1)
curIdx -= 7;
CADrawableAccidental* acc = new CADrawableAccidental(1, keySig, drawableStaff, newX, drawableStaff->calculateCenterYCoord(curIdx, x));
_drawableAccidentalList << acc;
newX += (acc->width() + 5);
if (acc->yPos() < minY)
minY = acc->yPos();
if (acc->yPos() + acc->height() > maxY)
maxY = acc->yPos() + acc->height();
}
// get initial flat position
idx = 6;
idx2 = 9;
while (idx + (clef ? clef->c1() : -2) - 28 < 0 || idx2 + (clef ? clef->c1() : -2) - 28 < 0) {
idx += 7;
idx2 += 7;
}
for (int i = 0; i < 7; idx += (i % 2 ? -4 : 3), i++) { // place flats,
if (keySig->accidentals()[idx % 7] != -1)
continue;
int curIdx = idx;
if ((curIdx + (clef ? clef->c1() : -2) - 28) < -1)
curIdx += 7;
if ((curIdx + (clef ? clef->c1() : -2) - 28) > (drawableStaff->staff()->numberOfLines() * 2 - 1))
curIdx -= 7;
CADrawableAccidental* acc = new CADrawableAccidental(-1, keySig, drawableStaff, newX, drawableStaff->calculateCenterYCoord(curIdx, x));
_drawableAccidentalList << acc;
newX += (acc->width() + 5);
if (acc->yPos() < minY)
minY = acc->yPos();
if (acc->yPos() + acc->height() > maxY)
maxY = acc->yPos() + acc->height();
}
setWidth(newX - x);
setHeight(maxY - minY);
setYPos(minY);
}
CADrawableKeySignature::~CADrawableKeySignature()
{
for (int i = 0; i < _drawableAccidentalList.size(); i++)
delete _drawableAccidentalList[i];
_drawableAccidentalList.clear();
}
void CADrawableKeySignature::draw(QPainter* p, CADrawSettings s)
{
int xOrig = s.x;
int yOrig = s.y;
for (int i = 0; i < _drawableAccidentalList.size(); i++) {
s.x = xOrig + qRound((_drawableAccidentalList[i]->xPos() - xPos()) * s.z);
s.y = yOrig + qRound((_drawableAccidentalList[i]->yPos() - yPos()) * s.z);
_drawableAccidentalList[i]->draw(p, s);
}
}
CADrawableKeySignature* CADrawableKeySignature::clone(CADrawableContext* newContext)
{
return (new CADrawableKeySignature(keySignature(), static_cast<CADrawableStaff*>((newContext) ? newContext : _drawableContext), xPos(), _drawableContext->yPos()));
}
| 6,313
|
C++
|
.cpp
| 143
| 35.881119
| 167
| 0.550881
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,328
|
drawablemark.cpp
|
canorusmusic_canorus/src/layout/drawablemark.cpp
|
/*!
Copyright (c) 2007-2022, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QFont>
#include <QPainter>
#include "layout/drawablecontext.h"
#include "layout/drawablemark.h"
#include "layout/drawablenote.h" // needed for tempo mark
#include "interface/mididevice.h" // needed for instrument change
#include "canorus.h"
#include "score/articulation.h"
#include "score/bookmark.h"
#include "score/crescendo.h"
#include "score/dynamic.h"
#include "score/fermata.h"
#include "score/instrumentchange.h"
#include "score/mark.h"
#include "score/note.h" // needed for tempo mark
#include "score/repeatmark.h"
#include "score/ritardando.h"
#include "score/tempo.h"
#include "score/text.h"
const double CADrawableMark::DEFAULT_TEXT_SIZE = 16;
const double CADrawableMark::DEFAULT_PIXMAP_SIZE = 25;
/*!
\class CADrawableMark
\brief Drawable instance of marks
This class draws the actual marks on the canvas.
*/
/*!
Default constructor.
\param mark Pointer to the model mark.
\param x Left border of the associated element.
\param y Bottom border of the mark.
*/
CADrawableMark::CADrawableMark(CAMark* mark, CADrawableContext* dContext, double x, double y)
: CADrawableMusElement(mark, dContext, x, y)
{
setDrawableMusElementType(CADrawableMusElement::DrawableMark);
_tempoNote = nullptr;
_tempoDNote = nullptr;
_pixmap = nullptr;
switch (mark->markType()) {
case CAMark::Text: {
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetrics fm(font);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = fm.horizontalAdvance(static_cast<CAText*>(this->mark())->text());
#else
int textWidth = fm.width(static_cast<CAText*>(this->mark())->text());
#endif
setWidth(textWidth < 11 ? 11 : textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
case CAMark::BookMark: {
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetrics fm(font);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = fm.horizontalAdvance(static_cast<CABookMark*>(this->mark())->text());
#else
int textWidth = fm.width(static_cast<CABookMark*>(this->mark())->text());
#endif
setWidth(DEFAULT_PIXMAP_SIZE + textWidth);
setHeight(qRound(DEFAULT_TEXT_SIZE));
_pixmap = new QPixmap("images:mark/bookmark.svg");
break;
}
case CAMark::Dynamic: {
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetrics fm(font);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = fm.horizontalAdvance(static_cast<CADynamic*>(this->mark())->text());
#else
int textWidth = fm.width(static_cast<CADynamic*>(this->mark())->text());
#endif
setWidth(textWidth < 11 ? 11 : textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
case CAMark::Crescendo: {
setWidth(mark->timeLength() / 10);
setHeight(static_cast<CACrescendo*>(mark)->finalVolume() / 10);
setHScalable(true);
break;
}
case CAMark::Pedal: {
setWidth(mark->timeLength() / 10);
setHeight(20);
setHScalable(true);
break;
}
case CAMark::Fermata: {
setWidth(20);
setHeight(15);
break;
}
case CAMark::InstrumentChange: {
QFont font("FreeSans");
font.setStyle(QFont::StyleItalic);
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetrics fm(font);
_pixmap = new QPixmap("images:mark/instrumentchange.svg");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int textWidth = fm.horizontalAdvance(CAMidiDevice::instrumentName(static_cast<CAInstrumentChange*>(this->mark())->instrument()));
#else
int textWidth = fm.width(CAMidiDevice::instrumentName(static_cast<CAInstrumentChange*>(this->mark())->instrument()));
#endif
setWidth(DEFAULT_PIXMAP_SIZE + textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
case CAMark::RehersalMark: {
setWidth(11);
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
case CAMark::Tempo: {
setWidth(40);
setHeight(qRound(DEFAULT_TEXT_SIZE));
_tempoNote = new CANote(CADiatonicPitch(), static_cast<CATempo*>(mark)->beat(), nullptr, 0);
_tempoDNote = new CADrawableNote(_tempoNote, dContext, x, y);
break;
}
case CAMark::Ritardando: {
setWidth(mark->timeLength() / 10);
setHeight(qRound(DEFAULT_TEXT_SIZE));
setHScalable(true);
break;
}
case CAMark::Fingering: {
setXPos(xPos() + 6);
QFont font("Emmentaler");
font.setPixelSize(11);
QFontMetrics fm(font);
QString text = fingerListToString(static_cast<CAFingering*>(mark)->fingerList());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
setWidth(fm.horizontalAdvance(text)); // set minimum text width at least 11 points
#else
setWidth(fm.width(text)); // set minimum text width at least 11 points
#endif
setHeight(11);
break;
}
case CAMark::RepeatMark: {
if (static_cast<CARepeatMark*>(mark)->repeatMarkType() == CARepeatMark::Volta)
setWidth(50);
else if (static_cast<CARepeatMark*>(mark)->repeatMarkType() == CARepeatMark::DalCoda || static_cast<CARepeatMark*>(mark)->repeatMarkType() == CARepeatMark::DalSegno || static_cast<CARepeatMark*>(mark)->repeatMarkType() == CARepeatMark::DalVarCoda)
setWidth(40);
else
setWidth(25);
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
default: {
setWidth(11); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
break;
}
}
}
CADrawableMark::~CADrawableMark()
{
if (_tempoDNote)
delete _tempoDNote;
if (_tempoNote)
delete _tempoNote;
if (_pixmap)
delete _pixmap;
}
void CADrawableMark::draw(QPainter* p, CADrawSettings s)
{
p->setPen(QPen(s.color));
switch (mark()->markType()) {
case CAMark::Dynamic: {
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
p->drawText(s.x, s.y + qRound(height() * s.z), static_cast<CADynamic*>(mark())->text());
break;
}
case CAMark::Crescendo: {
if (static_cast<CACrescendo*>(mark())->crescendoType() == CACrescendo::Crescendo) {
p->drawLine(s.x, qRound(s.y + (height() * s.z) / 2), qRound(s.x + width() * s.z), s.y);
p->drawLine(s.x, qRound(s.y + (height() * s.z) / 2), qRound(s.x + width() * s.z), qRound(s.y + (height() * s.z)));
} else {
p->drawLine(s.x, s.y, qRound(s.x + width() * s.z), qRound(s.y + (height() * s.z) / 2));
p->drawLine(s.x, qRound(s.y + (height() * s.z)), qRound(s.x + width() * s.z), qRound(s.y + (height() * s.z) / 2));
}
break;
}
case CAMark::Text: {
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
QString text = static_cast<CAText*>(mark())->text();
if (text.isEmpty()) {
text = CADrawableMusElement::EMPTY_PLACEHOLDER;
}
p->drawText(s.x, s.y + qRound(height() * s.z), text);
break;
}
case CAMark::BookMark: {
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
QString text = static_cast<CAText*>(mark())->text();
if (text.isEmpty()) {
text = CADrawableMusElement::EMPTY_PLACEHOLDER;
}
p->drawPixmap(s.x, s.y, _pixmap->scaled(qRound(DEFAULT_PIXMAP_SIZE * s.z), qRound(DEFAULT_PIXMAP_SIZE * s.z)));
p->drawText(s.x + qRound((DEFAULT_PIXMAP_SIZE + 1) * s.z), s.y + qRound(height() * s.z), text);
break;
}
case CAMark::RehersalMark: {
QFont font("FreeSans");
font.setBold(true);
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
p->drawRect(s.x, s.y, qRound(width() * s.z), qRound(height() * s.z));
p->drawText(s.x, s.y + qRound(height() * s.z), QString(static_cast<char>('A' + rehersalMarkNumber())));
break;
}
case CAMark::InstrumentChange: {
p->drawPixmap(s.x, s.y, _pixmap->scaled(qRound(DEFAULT_PIXMAP_SIZE * s.z), qRound(DEFAULT_PIXMAP_SIZE * s.z)));
QFont font("FreeSans");
font.setItalic(true);
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
p->drawText(s.x + qRound((DEFAULT_PIXMAP_SIZE + 1) * s.z), s.y + qRound(height() * s.z), CAMidiDevice::instrumentName(static_cast<CAInstrumentChange*>(mark())->instrument()));
break;
}
case CAMark::Fermata: {
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 1.1 * s.z));
p->setFont(font);
int inverted = 0;
if (mark()->associatedElement()->musElementType() == CAMusElement::Note && static_cast<CANote*>(mark()->associatedElement())->actualSlurDirection() == CASlur::SlurDown)
inverted = 1;
int x = qRound(s.x + (width() * s.z) * 0.4);
int y = qRound(s.y + (inverted ? 0 : (height() * s.z)));
switch (static_cast<CAFermata*>(mark())->fermataType()) {
case CAFermata::NormalFermata:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.ufermata") + inverted));
break;
case CAFermata::ShortFermata:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.ushortfermata") + inverted));
break;
case CAFermata::LongFermata:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.ulongfermata") + inverted));
break;
case CAFermata::VeryLongFermata:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.uverylongfermata") + inverted));
break;
}
break;
}
case CAMark::Tempo: {
_tempoDNote->draw(p, s);
s.x += qRound(_tempoDNote->width() * s.z);
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
p->drawText(s.x, s.y + qRound(height() * s.z), QString(" = ") + QString::number(static_cast<CATempo*>(mark())->bpm()));
break;
}
case CAMark::Ritardando: {
QFont font("FreeSans");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
font.setItalic(true);
p->setFont(font);
p->drawText(s.x, s.y + qRound(height() * s.z), static_cast<CARitardando*>(mark())->ritardandoType() == CARitardando::Ritardando ? "rit." : "accel.");
break;
}
case CAMark::RepeatMark: {
CARepeatMark* r = static_cast<CARepeatMark*>(mark());
// draw "Dal" if needed
if (r->repeatMarkType() == CARepeatMark::DalSegno || r->repeatMarkType() == CARepeatMark::DalCoda || r->repeatMarkType() == CARepeatMark::DalVarCoda) {
QFont font("Century Schoolbook L");
font.setStyle(QFont::StyleItalic);
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
p->drawText(s.x, s.y + qRound(1.5 * s.z), QString("Dal"));
s.x += qRound(36 * s.z);
}
// draw the actual sign
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 1.5 * s.z));
if (CARepeatMark::repeatMarkTypeToString(r->repeatMarkType()).startsWith("Dal")) {
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 1.2 * s.z));
}
p->setFont(font);
switch (r->repeatMarkType()) {
case CARepeatMark::Segno:
case CARepeatMark::DalSegno:
p->drawText(s.x, s.y - qRound(2 * s.z), QString(CACanorus::fetaCodepoint("scripts.segno")));
break;
case CARepeatMark::Coda:
case CARepeatMark::DalCoda:
p->drawText(s.x, s.y - qRound(2 * s.z), QString(CACanorus::fetaCodepoint("scripts.coda")));
break;
case CARepeatMark::VarCoda:
case CARepeatMark::DalVarCoda:
p->drawText(s.x, s.y - qRound(2 * s.z), QString(CACanorus::fetaCodepoint("scripts.varcoda")));
break;
case CARepeatMark::Volta:
break;
case CARepeatMark::Undefined:
fprintf(stderr, "Warning: CADrawableMark::draw - Unhandled RM-Type %d", static_cast<CARepeatMark*>(mark())->repeatMarkType());
break;
}
if (r->repeatMarkType() == CARepeatMark::Volta) {
p->drawLine(s.x, qRound(s.y + height() * s.z), s.x, s.y);
p->drawLine(s.x, s.y, qRound(s.x + width() * s.z), s.y);
p->drawText(s.x + qRound(5 * s.z), qRound(s.y + (height() - 5) * s.z), QString::number(r->voltaNumber()) + ".");
}
break;
}
case CAMark::Fingering: {
QFont font("Emmentaler");
CAFingering* f = static_cast<CAFingering*>(mark());
font.setPixelSize(f->fingerList()[0] > 5 ? qRound(DEFAULT_TEXT_SIZE * 2 * s.z) : qRound(DEFAULT_TEXT_SIZE * 1.3 * s.z));
font.setItalic(static_cast<CAFingering*>(mark())->isOriginal());
p->setFont(font);
QString text = fingerListToString(static_cast<CAFingering*>(mark())->fingerList());
p->drawText(s.x, s.y + qRound(height() * s.z), text);
break;
}
case CAMark::Pedal: {
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 1.6 * s.z));
p->setFont(font);
p->drawText(s.x, s.y + qRound(height() * s.z), QString(CACanorus::fetaCodepoint("pedal.Ped")));
p->drawText(s.x + qRound((width() - 10) * s.z), s.y + qRound(height() * s.z), QString(CACanorus::fetaCodepoint("pedal.*")));
break;
}
case CAMark::Articulation: {
QFont font("Emmentaler");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 1.4 * s.z));
p->setFont(font);
int x = s.x + qRound((width() / 2.0) * s.z);
int y = s.y + qRound(height() * s.z);
switch (static_cast<CAArticulation*>(mark())->articulationType()) {
case CAArticulation::Accent:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.sforzato")));
break;
case CAArticulation::Marcato:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.umarcato")));
break;
case CAArticulation::Staccatissimo:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.ustaccatissimo")));
break;
case CAArticulation::Espressivo:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.espr")));
break;
case CAArticulation::Staccato:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.staccato")));
break;
case CAArticulation::Tenuto:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.tenuto")));
break;
case CAArticulation::Breath:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.rcomma")));
break;
case CAArticulation::Portato:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.uportato")));
break;
case CAArticulation::UpBow:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.upbow")));
break;
case CAArticulation::DownBow:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.downbow")));
break;
case CAArticulation::Flageolet:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.flageolet")));
break;
case CAArticulation::Open:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.open")));
break;
case CAArticulation::Stopped:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.stopped")));
break;
case CAArticulation::Turn:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.turn")));
break;
case CAArticulation::ReverseTurn:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.reverseturn")));
break;
case CAArticulation::Trill:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.trill")));
break;
case CAArticulation::Prall:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.prall")));
break;
case CAArticulation::Mordent:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.mordent")));
break;
case CAArticulation::PrallPrall:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.prallprall")));
break;
case CAArticulation::PrallMordent:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.prallmordent")));
break;
case CAArticulation::UpPrall:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.upprall")));
break;
case CAArticulation::DownPrall:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.downprall")));
break;
case CAArticulation::UpMordent:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.upmordent")));
break;
case CAArticulation::DownMordent:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.downmordent")));
break;
case CAArticulation::PrallDown:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.pralldown")));
break;
case CAArticulation::PrallUp:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.prallup")));
break;
case CAArticulation::LinePrall:
p->drawText(x, y, QString(CACanorus::fetaCodepoint("scripts.lineprall")));
break;
case CAArticulation::Undefined:
fprintf(stderr, "Warning: CADrawableMark::draw - Unhandled A-Type %d", static_cast<CAArticulation*>(mark())->articulationType());
break;
}
break;
}
case CAMark::Undefined:
fprintf(stderr, "Warning: CADrawableMark::draw - Unhandled Type %d", mark()->markType());
break;
}
}
CADrawableMark* CADrawableMark::clone(CADrawableContext* newContext)
{
return new CADrawableMark(mark(), newContext ? newContext : drawableContext(), xPos(), yPos());
}
/*!
Converts the list of fingers to Emmentaler string.
*/
QString CADrawableMark::fingerListToString(const QList<CAFingering::CAFingerNumber> list)
{
QString text;
for (int i = 0; i < list.size(); i++) {
if (list[i] > 0 && list[i] < 6)
text += QString::number(list[i]);
else if (list[i] == CAFingering::Thumb)
text += QString(CACanorus::fetaCodepoint("scripts.thumb"));
else if (list[i] == CAFingering::LHeel)
text += QString(CACanorus::fetaCodepoint("scripts.upedalheel"));
else if (list[i] == CAFingering::RHeel)
text += QString(CACanorus::fetaCodepoint("scripts.dpedalheel"));
else if (list[i] == CAFingering::LToe)
text += QString(CACanorus::fetaCodepoint("scripts.upedaltoe"));
else if (list[i] == CAFingering::RToe)
text += QString(CACanorus::fetaCodepoint("scripts.dpedaltoe"));
}
return text;
}
| 19,976
|
C++
|
.cpp
| 466
| 34.688841
| 255
| 0.613152
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,329
|
drawablemuselement.cpp
|
canorusmusic_canorus/src/layout/drawablemuselement.cpp
|
/*!
Copyright (c) 2006-2022, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "layout/drawablemuselement.h"
const QString CADrawableMusElement::EMPTY_PLACEHOLDER = "·";
CADrawableMusElement::CADrawableMusElement(CAMusElement* m, CADrawableContext* drawableContext, double x, double y)
: CADrawable(x, y)
{
setDrawableType(CADrawable::DrawableMusElement);
_musElement = m;
_drawableContext = drawableContext;
}
| 576
|
C++
|
.cpp
| 14
| 38.357143
| 115
| 0.789568
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,330
|
drawableslur.cpp
|
canorusmusic_canorus/src/layout/drawableslur.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "layout/drawableslur.h"
#include <QPainter>
#include <stdio.h>
CADrawableSlur::CADrawableSlur(CASlur* slur, CADrawableContext* c, double x1, double y1, double xMid, double yMid, double x2, double y2)
: CADrawableMusElement(slur, c, x1, 0)
{
setDrawableMusElementType(DrawableSlur);
setX1(x1);
setY1(y1);
setXMid(xMid);
setYMid(yMid);
setX2(x2);
setY2(y2);
updateGeometry(); // sets width, height, xPos, yPos
setNeededSpaceWidth(0);
setNeededSpaceHeight(0);
}
CADrawableSlur::~CADrawableSlur()
{
}
void CADrawableSlur::updateGeometry()
{
setXPos(min(x1(), xMid(), x2()));
setWidth(max(x1(), xMid(), x2()) - xPos());
setYPos(min(y1(), yMid(), y2()));
setHeight(max(y1(), yMid(), y2()) - yPos());
}
/*!
Returns the minimum of all the three integers given.
*/
double CADrawableSlur::min(double x, double y, double z)
{
if (x <= y && x <= z)
return x;
else if (y <= x && y <= z)
return y;
else
return z;
}
/*!
Returns the maximum of all the three integers given.
*/
double CADrawableSlur::max(double x, double y, double z)
{
if (x >= y && x >= z)
return x;
else if (y >= x && y >= z)
return y;
else
return z;
}
void CADrawableSlur::draw(QPainter* p, const CADrawSettings s)
{
QPen pen(s.color);
pen.setWidth(qRound(1.2 * s.z));
pen.setCapStyle(Qt::RoundCap);
switch (slur()->slurStyle()) {
case CASlur::SlurSolid:
pen.setStyle(Qt::SolidLine);
break;
case CASlur::SlurDotted:
pen.setStyle(Qt::DotLine);
break;
case CASlur::Undefined:
fprintf(stderr, "Warning: CADrawableSlur::draw - Unhandled Style %d", slur()->slurStyle());
break;
}
p->setPen(pen);
bool aliasing = p->testRenderHint(QPainter::Antialiasing);
p->setRenderHint(QPainter::Antialiasing, true);
double minY = min(y1(), yMid(), y2());
double yLeft = s.y + (y1() - minY) * s.z;
double yMidl = s.y + (yMid() - minY) * s.z;
double xMidl = s.x + (xMid() - xPos()) * s.z;
double yRight = s.y + (y2() - minY) * s.z;
double deltaY1 = (yMidl - yLeft);
double deltaY2 = (yRight - yMidl);
double deltaX1 = xMidl - s.x;
double deltaX2 = qRound(s.x + width() * s.z - xMidl);
// generate an array of points for the rounded slur using the exponent shape
QPoint points[21];
points[0] = QPoint(s.x, qRound(yLeft));
points[1] = QPoint(qRound(s.x + 0.1 * deltaX1), qRound(yLeft + deltaY1 * 0.34));
points[2] = QPoint(qRound(s.x + 0.2 * deltaX1), qRound(yLeft + deltaY1 * 0.53));
points[3] = QPoint(qRound(s.x + 0.3 * deltaX1), qRound(yLeft + deltaY1 * 0.71));
points[4] = QPoint(qRound(s.x + 0.4 * deltaX1), qRound(yLeft + deltaY1 * 0.79));
points[5] = QPoint(qRound(s.x + 0.5 * deltaX1), qRound(yLeft + deltaY1 * 0.86));
points[6] = QPoint(qRound(s.x + 0.6 * deltaX1), qRound(yLeft + deltaY1 * 0.90));
points[7] = QPoint(qRound(s.x + 0.7 * deltaX1), qRound(yLeft + deltaY1 * 0.94));
points[8] = QPoint(qRound(s.x + 0.8 * deltaX1), qRound(yLeft + deltaY1 * 0.95));
points[9] = QPoint(qRound(s.x + 0.9 * deltaX1), qRound(yLeft + deltaY1 * 0.97));
points[10] = QPoint(static_cast<int>(xMidl), qRound(yMidl + deltaY2 * 0.02));
points[11] = QPoint(qRound(xMidl + 0.1 * deltaX2), qRound(yMidl + deltaY2 * 0.03));
points[12] = QPoint(qRound(xMidl + 0.2 * deltaX2), qRound(yMidl + deltaY2 * 0.05));
points[13] = QPoint(qRound(xMidl + 0.3 * deltaX2), qRound(yMidl + deltaY2 * 0.06));
points[14] = QPoint(qRound(xMidl + 0.4 * deltaX2), qRound(yMidl + deltaY2 * 0.10));
points[15] = QPoint(qRound(xMidl + 0.5 * deltaX2), qRound(yMidl + deltaY2 * 0.14));
points[16] = QPoint(qRound(xMidl + 0.6 * deltaX2), qRound(yMidl + deltaY2 * 0.21));
points[17] = QPoint(qRound(xMidl + 0.7 * deltaX2), qRound(yMidl + deltaY2 * 0.29));
points[18] = QPoint(qRound(xMidl + 0.8 * deltaX2), qRound(yMidl + deltaY2 * 0.47));
points[19] = QPoint(qRound(xMidl + 0.9 * deltaX2), qRound(yMidl + deltaY2 * 0.66));
points[20] = QPoint(qRound(s.x + width() * s.z), static_cast<int>(yRight));
p->drawPolyline(points, 21);
p->setRenderHint(QPainter::Antialiasing, aliasing);
}
CADrawableSlur* CADrawableSlur::clone(CADrawableContext* newContext)
{
return new CADrawableSlur(slur(), newContext ? newContext : drawableContext(), xPos(), y1(), xMid(), yMid(), xPos() + width(), y2());
}
| 4,690
|
C++
|
.cpp
| 114
| 36.754386
| 137
| 0.635666
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,331
|
drawablechordname.cpp
|
canorusmusic_canorus/src/layout/drawablechordname.cpp
|
/*!
Copyright (c) 2019-2022, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawablechordname.h"
#include "layout/drawablechordnamecontext.h"
#include "score/chordnamecontext.h"
#include <QFont>
#include <QFontMetrics>
#include <QPainter>
const double CADrawableChordName::DEFAULT_TEXT_SIZE = 16;
CADrawableChordName::CADrawableChordName(CAChordName* s, CADrawableChordNameContext* c, double x, double y)
: CADrawableMusElement(s, c, x, y)
{
setDrawableMusElementType(DrawableChordName);
// some work to compute the drawable width
QFont font("Century Schoolbook L");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE));
QFontMetricsF fm(font);
qreal textWidth;
if (!drawableDiatonicPitch().isEmpty()) {
textWidth = fm.width(drawableDiatonicPitch());
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * 0.75));
fm = QFontMetricsF(font);
textWidth += fm.width(chordName()->qualityModifier());
} else {
// syntax error, print qualityModifier() which includes everything
textWidth = fm.width(chordName()->qualityModifier());
}
setWidth(textWidth < 11 ? 11 : textWidth); // set minimum text width at least 11 points
setHeight(qRound(DEFAULT_TEXT_SIZE));
}
CADrawableChordName::~CADrawableChordName()
{
}
void CADrawableChordName::draw(QPainter* p, const CADrawSettings s)
{
QPen pen(s.color);
pen.setWidth(qRound(1.2 * s.z));
pen.setCapStyle(Qt::RoundCap);
p->setPen(pen);
QFont font("Century Schoolbook L");
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z));
p->setFont(font);
QString dChordPitch = drawableDiatonicPitch();
if (dChordPitch.isEmpty()) {
// syntax error, print qualityModifier() which includes everything
p->drawText(s.x, s.y + qRound(height() * s.z), chordName()->qualityModifier());
return;
}
p->drawText(s.x, s.y + qRound(height() * s.z), dChordPitch);
QFontMetricsF fm(font);
qreal w = fm.width(dChordPitch);
font.setPixelSize(qRound(DEFAULT_TEXT_SIZE * s.z * 0.75));
p->setFont(font);
p->drawText(s.x + w, s.y + qRound(height() * s.z * 0.5), chordName()->qualityModifier());
}
CADrawableChordName* CADrawableChordName::clone(CADrawableContext* c)
{
return new CADrawableChordName(
chordName(),
(c ? static_cast<CADrawableChordNameContext*>(c) : static_cast<CADrawableChordNameContext*>(drawableContext())),
xPos(),
yPos());
}
/*!
* \brief Converts CADiatonicPitch to a chord-style pitch, e.g. "cis" -> "C#"
* \return Chord-style pitch as QString
*/
QString CADrawableChordName::drawableDiatonicPitch()
{
QString chordPitch = CADiatonicPitch::diatonicPitchToString(chordName()->diatonicPitch());
if (chordPitch.isEmpty()) {
return CADrawableMusElement::EMPTY_PLACEHOLDER;
}
chordPitch = chordPitch[0].toUpper(); // chord-style pitch is upper case
// now add sharps or flats
if (chordName()->diatonicPitch().accs() < 0) {
chordPitch += QString("b").repeated(chordName()->diatonicPitch().accs() * (-1));
} else if (chordName()->diatonicPitch().accs() > 0) {
chordPitch += QString("#").repeated(chordName()->diatonicPitch().accs());
}
return chordPitch;
}
| 3,413
|
C++
|
.cpp
| 85
| 35.6
| 120
| 0.699577
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,332
|
drawableclef.cpp
|
canorusmusic_canorus/src/layout/drawableclef.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <iostream>
#include <QFont>
#include <QPainter>
#include "layout/drawableclef.h"
#include "layout/drawablestaff.h"
#include "canorus.h"
#include "score/clef.h"
const int CADrawableClef::CLEF_EIGHT_SIZE = 8;
/*!
\class CADrawableClef
\brief Drawable instance of CAClef
This class draws the clef to the canvas.
*/
/*!
Default constructor.
\param clef Pointer to the logical CAClef.
\param x X coordinate of the left-margin of the clef.
\param y Y coordinate of the top of the staff. (WARNING! Not top of the clef!)
*/
CADrawableClef::CADrawableClef(CAClef* musElement, CADrawableStaff* drawableStaff, double x, double y)
: CADrawableMusElement(musElement, drawableStaff, x, y)
{
setDrawableMusElementType(CADrawableMusElement::DrawableClef);
double lineSpace = drawableStaff->lineSpace();
double bottom = drawableStaff->yPos() + drawableStaff->height();
switch (clef()->clefType()) {
case CAClef::G:
setWidth(21);
setHeight(68);
setYPos(bottom - (((clef()->c1() + clef()->offset()) / 2.0) * lineSpace) - 0.89 * height());
break;
case CAClef::F:
setWidth(22);
setHeight(26);
setYPos(bottom - (((clef()->c1() + clef()->offset()) / 2.0) * lineSpace) + 1.1 * lineSpace);
break;
case CAClef::C:
setWidth(23);
setHeight(34);
setYPos(bottom - (((clef()->c1() + clef()->offset()) / 2.0) * lineSpace) - 0.5 * height());
break;
case CAClef::PercussionHigh:
case CAClef::PercussionLow:
case CAClef::Tab: // TODO
setWidth(23);
setHeight(34);
break;
}
// make space for little 8 above/below, if needed
if (clef()->offset())
setHeight(height() + CLEF_EIGHT_SIZE);
if (clef()->offset() > 0)
setYPos(yPos() - CLEF_EIGHT_SIZE);
}
void CADrawableClef::draw(QPainter* p, CADrawSettings s)
{
QFont font("Emmentaler");
font.setPixelSize(qRound(35 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
/*
There are two glyphs for each clef type: a normal clef (placed at the beginning of the system) and a smaller one (at the center of the system, key change).
clefs.G, clefs.G_change, ...
*/
switch (clef()->clefType()) {
case CAClef::G:
p->drawText(s.x, qRound(s.y + (clef()->offset() > 0 ? CLEF_EIGHT_SIZE * s.z : 0) + 0.63 * (height() - (clef()->offset() ? CLEF_EIGHT_SIZE : 0)) * s.z), QString(CACanorus::fetaCodepoint("clefs.G")));
break;
case CAClef::F:
p->drawText(s.x, qRound(s.y + (clef()->offset() > 0 ? CLEF_EIGHT_SIZE * s.z : 0) + 0.32 * (height() - (clef()->offset() ? CLEF_EIGHT_SIZE : 0)) * s.z), QString(CACanorus::fetaCodepoint("clefs.F")));
break;
case CAClef::C:
p->drawText(s.x, qRound(s.y + (clef()->offset() > 0 ? CLEF_EIGHT_SIZE * s.z : 0) + 0.5 * (height() - (clef()->offset() ? CLEF_EIGHT_SIZE : 0)) * s.z), QString(CACanorus::fetaCodepoint("clefs.C")));
break;
case CAClef::Tab:
case CAClef::PercussionHigh:
case CAClef::PercussionLow:
fprintf(stderr, "Warning: CADrawableClef::draw - Unhandled type %d", clef()->clefType());
break;
}
if (clef()->offset()) {
QFont number("Century Schoolbook L");
number.setPixelSize(qRound((CLEF_EIGHT_SIZE + 5) * s.z));
number.setStyle(QFont::StyleItalic);
p->setFont(number);
if (clef()->offset() > 0) {
p->drawText(qRound(s.x + (width() / 2 - 4) * s.z), qRound(s.y + CLEF_EIGHT_SIZE * s.z), QString::number(clef()->offset() + 1));
} else {
p->drawText(qRound(s.x + (width() / 2 - 4) * s.z), qRound(s.y + height() * s.z), QString::number(qAbs(clef()->offset() - 1)));
}
}
}
CADrawableClef* CADrawableClef::clone(CADrawableContext* newContext)
{
return (new CADrawableClef(clef(), static_cast<CADrawableStaff*>((newContext) ? newContext : _drawableContext), xPos(), _drawableContext->yPos()));
}
| 4,190
|
C++
|
.cpp
| 101
| 36.158416
| 206
| 0.630066
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,333
|
drawabletuplet.cpp
|
canorusmusic_canorus/src/layout/drawabletuplet.cpp
|
/*!
Copyright (c) 2008-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "layout/drawabletuplet.h"
#include "layout/drawablecontext.h"
#include <QFont>
#include <QPainter>
#include <QPen>
CADrawableTuplet::CADrawableTuplet(CATuplet* tuplet, CADrawableContext* c, double x1, double y1, double x2, double y2)
: CADrawableMusElement(tuplet, c, x1, 0)
{
setDrawableMusElementType(DrawableTuplet);
setWidth(x2 - x1);
setHeight((abs(y2 - y1) > 5) ? abs(y2 - y1) : 8);
setYPos((c && qMin(y1, y2) > c->yPos()) ? qMin(y1, y2) : (qMin(y1, y2) - height()));
}
CADrawableTuplet::~CADrawableTuplet()
{
}
void CADrawableTuplet::draw(QPainter* p, const CADrawSettings s)
{
QPen pen(s.color);
pen.setWidth(qRound(1.2 * s.z));
pen.setCapStyle(Qt::RoundCap);
p->setPen(pen);
double minY = qMin(yPos(), yPos()) - 8;
double yLeft = s.y + (yPos() - minY) * s.z;
double yMidl = s.y + (yPos() - minY) * s.z;
double xMidl = s.x + (width() / 2.0) * s.z;
double yRight = s.y + (yPos() - minY) * s.z;
double deltaY1 = yMidl - yLeft;
double deltaY2 = yRight - yMidl;
double deltaX1 = xMidl - s.x;
double deltaX2 = s.x + width() * s.z - xMidl;
// generate an array of points for the rounded slur using the exponent shape
QPoint points[9];
points[0] = QPoint(s.x, qRound(yLeft));
points[1] = QPoint(qRound(s.x + 0.1 * deltaX1), qRound(yLeft + deltaY1 * 0.34));
points[2] = QPoint(qRound(s.x + 0.2 * deltaX1), qRound(yLeft + deltaY1 * 0.53));
points[3] = QPoint(qRound(s.x + 0.3 * deltaX1), qRound(yLeft + deltaY1 * 0.71));
points[4] = QPoint(qRound(s.x + 0.4 * deltaX1), qRound(yLeft + deltaY1 * 0.79));
points[5] = QPoint(qRound(s.x + 0.5 * deltaX1), qRound(yLeft + deltaY1 * 0.86));
points[6] = QPoint(qRound(s.x + 0.6 * deltaX1), qRound(yLeft + deltaY1 * 0.90));
points[7] = QPoint(qRound(s.x + 0.7 * deltaX1), qRound(yLeft + deltaY1 * 0.94));
points[8] = QPoint(qRound(s.x + 0.8 * deltaX1), qRound(yLeft + deltaY1 * 0.95));
p->drawPolyline(points, 9);
points[0] = QPoint(qRound(xMidl + 0.2 * deltaX2), qRound(yMidl + deltaY2 * 0.05));
points[1] = QPoint(qRound(xMidl + 0.3 * deltaX2), qRound(yMidl + deltaY2 * 0.06));
points[2] = QPoint(qRound(xMidl + 0.4 * deltaX2), qRound(yMidl + deltaY2 * 0.10));
points[3] = QPoint(qRound(xMidl + 0.5 * deltaX2), qRound(yMidl + deltaY2 * 0.14));
points[4] = QPoint(qRound(xMidl + 0.6 * deltaX2), qRound(yMidl + deltaY2 * 0.21));
points[5] = QPoint(qRound(xMidl + 0.7 * deltaX2), qRound(yMidl + deltaY2 * 0.29));
points[6] = QPoint(qRound(xMidl + 0.8 * deltaX2), qRound(yMidl + deltaY2 * 0.47));
points[7] = QPoint(qRound(xMidl + 0.9 * deltaX2), qRound(yMidl + deltaY2 * 0.66));
points[8] = QPoint(qRound(s.x + width() * s.z), static_cast<int>(yRight));
p->drawPolyline(points, 9);
QFont font("Emmentaler");
font.setPixelSize(qRound(16 * 1.3 * s.z));
font.setItalic(true);
p->setFont(font);
p->drawText(s.x + qRound((width() / 2.0 - 3) * s.z), s.y + qRound((height() / 2.0 + 9) * s.z), QString::number(tuplet()->number()));
}
CADrawableTuplet* CADrawableTuplet::clone(CADrawableContext* newContext)
{
return new CADrawableTuplet(tuplet(), newContext ? newContext : drawableContext(), x1(), y1(), x2(), y2());
}
| 3,471
|
C++
|
.cpp
| 68
| 47.132353
| 136
| 0.642983
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,334
|
layoutengine.cpp
|
canorusmusic_canorus/src/layout/layoutengine.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QDebug>
#include <QList>
#include <QMap>
#include "layout/layoutengine.h"
#include "widgets/scoreview.h"
#include "layout/drawableaccidental.h"
#include "layout/drawablebarline.h"
#include "layout/drawableclef.h"
#include "layout/drawablekeysignature.h"
#include "layout/drawablemark.h"
#include "layout/drawablemidinote.h"
#include "layout/drawablenote.h"
#include "layout/drawablenotecheckererror.h"
#include "layout/drawablerest.h"
#include "layout/drawableslur.h"
#include "layout/drawablestaff.h"
#include "layout/drawabletimesignature.h"
#include "layout/drawabletuplet.h"
#include "layout/drawablelyricscontext.h"
#include "layout/drawablesyllable.h"
#include "layout/drawablefiguredbasscontext.h"
#include "layout/drawablefiguredbassnumber.h"
#include "layout/drawablefunctionmark.h"
#include "layout/drawablefunctionmarkcontext.h"
#include "layout/drawablechordname.h"
#include "layout/drawablechordnamecontext.h"
#include "score/sheet.h"
#include "score/keysignature.h"
#include "score/staff.h"
#include "score/timesignature.h"
#include "score/voice.h"
#include "score/articulation.h"
#include "score/barline.h"
#include "score/lyricscontext.h"
#include "score/mark.h"
#include "score/midinote.h"
#include "score/note.h"
#include "score/rest.h"
#include "score/syllable.h"
#include "score/functionmark.h"
#include "score/functionmarkcontext.h"
#include "score/chordname.h"
#include "score/chordnamecontext.h"
#include "interface/mididevice.h" // needed for midiPitch->diatonicPitch
#define INITIAL_X_OFFSET 20 // space between the left border and the first music element
#define MINIMUM_SPACE 10 // minimum space between the music elements
QList<CADrawableMusElement*> CALayoutEngine::scalableElts;
int* CALayoutEngine::streamsRehersalMarks;
/*!
\class CAEngraver
\brief Class for correctly placing the abstract notes to the score canvas.
This class is a bridge between the data part of Canorus and the UI.
Out of data CAMusElement* and CAContext* objects, it creates their CADrawable* instances.
*/
/*!
Repositions the notes in the abstract sheet of the given score view \a v so they fit nicely.
This function doesn't clear the view, but only adds the elements.
*/
void CALayoutEngine::reposit(CAScoreView* v)
{
//int i;
CASheet* sheet = v->sheet();
//list of all the music element lists (ie. streams) taken from all the contexts
QList<QList<CAMusElement*>> musStreamList; // streams music elements
QList<CAContext*> contexts; // which context does the stream belong to
int dy = 50;
QList<int> nonFirstVoiceIdxs; //list of indexes of musStreamLists which the voices aren't the first voice. This is used later for determining should a sign be created or not (if it has been created in 1st voice already, don't recreate it in the other voices in the same staff).
QMap<CAContext*, CADrawableContext*> drawableContextMap;
for (int i = 0; i < sheet->contextList().size(); i++) {
switch (sheet->contextList()[i]->contextType()) {
case CAContext::Staff: {
if (i > 0)
dy += 70;
CAStaff* staff = static_cast<CAStaff*>(sheet->contextList()[i]);
/// \todo replace raw pointer with shared or unique pointer
drawableContextMap[staff] = new CADrawableStaff(staff, 0, dy);
v->addCElement(drawableContextMap[staff]);
//add all the voices lists to the common list
for (int j = 0; j < staff->voiceList().size(); j++) {
musStreamList << staff->voiceList()[j]->musElementList();
contexts << staff;
if (staff->voiceList()[j]->voiceNumber() != 1)
nonFirstVoiceIdxs << musStreamList.size() - 1;
}
dy += drawableContextMap[staff]->height();
break;
}
case CAContext::LyricsContext: {
CALyricsContext* lyricsContext = static_cast<CALyricsContext*>(sheet->contextList()[i]);
if (i > 0 && (sheet->contextList()[i - 1]->contextType() != CAContext::LyricsContext || static_cast<CALyricsContext*>(sheet->contextList()[i - 1])->associatedVoice()->staff() != lyricsContext->associatedVoice()->staff())) {
dy += 70; // the previous context wasn't lyrics or was not related to the current lyrics
}
drawableContextMap[lyricsContext] = new CADrawableLyricsContext(lyricsContext, 0, dy);
v->addCElement(drawableContextMap[lyricsContext]);
// convert QList<CASyllable*> to QList<CAMusElement*>
QList<CAMusElement*> syllableList;
for (int i = 0; i < lyricsContext->syllableList().size(); i++) {
syllableList << lyricsContext->syllableList()[i];
}
musStreamList << syllableList;
contexts << lyricsContext;
dy += drawableContextMap[lyricsContext]->height();
break;
}
case CAContext::FiguredBassContext: {
if (i > 0)
dy += 70;
CAFiguredBassContext* fbContext = static_cast<CAFiguredBassContext*>(sheet->contextList()[i]);
drawableContextMap[fbContext] = new CADrawableFiguredBassContext(fbContext, 0, dy);
v->addCElement(drawableContextMap[fbContext]);
QList<CAFiguredBassMark*> fbmList = fbContext->figuredBassMarkList();
// TODO: Is there a faster way to cast QList<CAFiguredBassMark*> to QList<CAMusElement*>?
QList<CAMusElement*> musList;
for (int j = 0; j < fbmList.size(); j++)
musList << fbmList[j];
musStreamList << musList;
contexts << fbContext;
dy += drawableContextMap[fbContext]->height();
break;
}
case CAContext::FunctionMarkContext: {
if (i > 0 && sheet->contextList()[i - 1]->contextType() != CAContext::FiguredBassContext) {
dy += 70;
}
CAFunctionMarkContext* fmContext = static_cast<CAFunctionMarkContext*>(sheet->contextList()[i]);
drawableContextMap[fmContext] = new CADrawableFunctionMarkContext(fmContext, 0, dy);
v->addCElement(drawableContextMap[fmContext]);
QList<CAFunctionMark*> fmList = fmContext->functionMarkList();
// TODO: Is there a faster way to cast QList<CAFunctionMark*> to QList<CAMusElement*>?
QList<CAMusElement*> musList;
for (int j = 0; j < fmList.size(); j++)
musList << fmList[j];
musStreamList << musList;
contexts << fmContext;
dy += drawableContextMap[fmContext]->height();
break;
}
case CAContext::ChordNameContext: {
if (i > 0)
dy += 70;
CAChordNameContext* cnContext = static_cast<CAChordNameContext*>(sheet->contextList()[i]);
drawableContextMap[cnContext] = new CADrawableChordNameContext(cnContext, 0, dy);
v->addCElement(drawableContextMap[cnContext]);
QList<CAChordName*> cnList = cnContext->chordNameList();
// TODO: Is there a faster way to cast QList<CAChordName*> to QList<CAMusElement*>?
QList<CAMusElement*> musList;
for (int j = 0; j < cnList.size(); j++)
musList << cnList[j];
musStreamList << musList;
contexts << cnContext;
dy += drawableContextMap[cnContext]->height();
break;
}
}
}
unsigned int streams = static_cast<unsigned int>(musStreamList.size());
int* streamsIdx = new int[streams];
for (unsigned int i = 0; i < streams; i++)
streamsIdx[i] = 0;
int* streamsX = new int[streams];
for (unsigned int i = 0; i < streams; i++)
streamsX[i] = INITIAL_X_OFFSET;
int* streamsRehersalMarks = new int[streams];
for (unsigned int i = 0; i < streams; i++)
streamsRehersalMarks[i] = 0;
CALayoutEngine::streamsRehersalMarks = streamsRehersalMarks;
/// \todo replace raw pointer with shared or unique pointer
CAClef** lastClef = new CAClef*[streams];
for (unsigned int i = 0; i < streams; i++)
lastClef[i] = nullptr;
/// \todo replace raw pointer with shared or unique pointer
CAKeySignature** lastKeySig = new CAKeySignature*[streams];
for (unsigned int i = 0; i < streams; i++)
lastKeySig[i] = nullptr;
/// \todo replace raw pointer with shared or unique pointer
CATimeSignature** lastTimeSig = new CATimeSignature*[streams];
for (unsigned int i = 0; i < streams; i++)
lastTimeSig[i] = nullptr;
scalableElts.clear();
int timeStart = 0;
bool done = false;
/// \todo replace raw pointer with shared or unique pointer
CADrawableFunctionMarkSupport** lastDFMTonicizations = new CADrawableFunctionMarkSupport*[streams];
for (unsigned int i = 0; i < streams; i++)
lastDFMTonicizations[i] = nullptr;
while (!done) {
//if all the indices are at the end of the streams, finish.
unsigned int idx;
for (idx = 0; (idx < streams) && (streamsIdx[idx] == musStreamList[static_cast<int>(idx)].size()); idx++)
;
if (idx == streams) {
done = true;
continue;
}
//Synchronize minimum X-es between the contexts
int maxX = 0;
for (unsigned int i = 0; i < streams; i++)
maxX = (streamsX[i] > maxX) ? streamsX[i] : maxX;
for (unsigned int i = 0; i < streams; i++)
if (musStreamList[static_cast<int>(i)].size() && musStreamList[static_cast<int>(i)].last()->musElementType() != CAMusElement::FunctionMark)
streamsX[i] = maxX;
//go through all the streams and remember the time of the soonest element that will happen
timeStart = -1; //reset the timeStart - the next one minimum will be set in the following loop
for (unsigned int idx = 0; idx < streams; idx++) {
if ((musStreamList[static_cast<int>(idx)].size() > streamsIdx[idx]) && ((timeStart == -1) || (musStreamList[static_cast<int>(idx)].at(streamsIdx[idx])->timeStart() < timeStart)))
timeStart = musStreamList[static_cast<int>(idx)].at(streamsIdx[idx])->timeStart();
}
//timeStart now holds the nearest next time we're going to draw
//go through all the streams and check if the following element has this time
CAMusElement* elt;
CADrawableContext* drawableContext;
//bool placedSymbol = false; //used if waiting for notes to gather and a non-time-consuming symbol has been placed
for (unsigned int i = 0; i < streams; i++) {
//loop until the first playable element
//multiple elements can have the same start time. eg. Clef + Key signature + Time signature + First note
while ((streamsIdx[i] < musStreamList[static_cast<int>(i)].size()) && ((elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]))->timeStart() == timeStart) && (!elt->isPlayable()) && (elt->musElementType() != CAMusElement::Barline) && //barlines should be aligned
(elt->musElementType() != CAMusElement::FunctionMark) && //function marks are placed separately
(elt->musElementType() != CAMusElement::FiguredBassMark) && //figured bass marks are placed separately
(elt->musElementType() != CAMusElement::Syllable) && //syllables are placed separately
(elt->musElementType() != CAMusElement::ChordName) //chord names are placed separately
) {
drawableContext = drawableContextMap[elt->context()];
//place signs in first voices
if ((drawableContext->drawableContextType() == CADrawableContext::DrawableStaff) && (!nonFirstVoiceIdxs.contains(static_cast<int>(i)))) {
switch (elt->musElementType()) {
case CAMusElement::Clef: {
/// \todo replace raw pointer with shared or unique pointer
CADrawableClef* clef = new CADrawableClef(
static_cast<CAClef*>(elt),
static_cast<CADrawableStaff*>(drawableContext),
streamsX[i],
drawableContext->yPos());
v->addMElement(clef);
// set the last clefs in all voices in the same staff
for (int j = 0; j < contexts.size(); j++)
if (contexts[j] == contexts[static_cast<int>(i)])
lastClef[j] = clef->clef();
streamsX[i] += (clef->neededWidth() + MINIMUM_SPACE);
//placedSymbol = true;
placeMarks(clef, v, static_cast<int>(i));
break;
}
case CAMusElement::KeySignature: {
CADrawableKeySignature* keySig = new CADrawableKeySignature(
static_cast<CAKeySignature*>(elt),
static_cast<CADrawableStaff*>(drawableContext),
streamsX[i],
drawableContext->yPos());
v->addMElement(keySig);
// set the last key sigs in all voices in the same staff
for (int j = 0; j < contexts.size(); j++)
if (contexts[j] == contexts[static_cast<int>(i)])
lastKeySig[j] = keySig->keySignature();
streamsX[i] += (keySig->neededWidth() + MINIMUM_SPACE);
//placedSymbol = true;
placeMarks(keySig, v, static_cast<int>(i));
break;
}
case CAMusElement::TimeSignature: {
CADrawableTimeSignature* timeSig = new CADrawableTimeSignature(
static_cast<CATimeSignature*>(elt),
static_cast<CADrawableStaff*>(drawableContext),
streamsX[i],
drawableContext->yPos());
v->addMElement(timeSig);
// set the last time signatures in all voices in the same staff
for (int j = 0; j < contexts.size(); j++)
if (contexts[j] == contexts[static_cast<int>(i)])
lastTimeSig[j] = timeSig->timeSignature();
streamsX[i] += (timeSig->neededWidth() + MINIMUM_SPACE);
//placedSymbol = true;
placeMarks(timeSig, v, static_cast<int>(i));
break;
}
default:
qDebug() << "Warning: CALayoutEngine::reposit - Unhandled Element" << elt->musElementType();
break;
} // SWITCH
} // IF firstVoice
streamsIdx[i]++;
}
}
// Draw function key name, if needed
QList<CADrawableFunctionMarkSupport*> lastDFMKeyNames;
for (unsigned int i = 0;
(i < streams) && (streamsIdx[i] < musStreamList[static_cast<int>(i)].size()) && (musStreamList[static_cast<int>(i)].at(streamsIdx[i])->timeStart() == timeStart);
i++) {
CAMusElement* elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]);
if (elt->musElementType() == CAMusElement::FunctionMark && ((CAFunctionMark*)elt)->function() != CAFunctionMark::Undefined) {
drawableContext = drawableContextMap[elt->context()];
if (streamsIdx[i] - 1 < 0 || static_cast<CAFunctionMark*>(musStreamList[i].at(streamsIdx[i] - 1))->key() != static_cast<CAFunctionMark*>(elt)->key()) {
//draw new function mark key, if it was changed or if it's the first function in the score
CADrawableFunctionMarkSupport* support = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Key,
CADiatonicKey::diatonicKeyToString(static_cast<CAFunctionMark*>(elt)->key()),
drawableContext,
streamsX[i],
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Middle));
streamsX[i] += (support->neededWidth());
v->addMElement(support);
lastDFMKeyNames << support;
}
}
}
// Synchronize minimum X-es between the contexts - all the noteheads or barlines should be horizontally aligned.
for (unsigned int i = 0; i < streams; i++)
maxX = (streamsX[i] > maxX) ? streamsX[i] : maxX;
for (unsigned int i = 0; i < streams; i++)
if (musStreamList[static_cast<int>(i)].size() && musStreamList[static_cast<int>(i)].last()->musElementType() != CAMusElement::FunctionMark)
streamsX[i] = maxX;
// Place barlines
for (unsigned int i = 0; i < streams; i++) {
if (!(musStreamList[static_cast<int>(i)].size() > streamsIdx[i]) || //if the stream is already at the end, continue to the next stream
((elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]))->timeStart() != timeStart))
continue;
if ((elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]))->musElementType() == CAMusElement::Barline) {
if (nonFirstVoiceIdxs.contains(static_cast<int>(i))) { //if the current stream is non-first voice, continue, as the barlines are drawn from the first voice only
streamsIdx[i] = streamsIdx[i] + 1;
continue;
}
drawableContext = drawableContextMap[elt->context()];
CADrawableBarline* bar = new CADrawableBarline(
static_cast<CABarline*>(elt),
static_cast<CADrawableStaff*>(drawableContext),
streamsX[i],
drawableContext->yPos());
v->addMElement(bar);
//placedSymbol = true;
streamsX[i] += (bar->neededWidth() + MINIMUM_SPACE);
streamsIdx[i] = streamsIdx[i] + 1;
placeMarks(bar, v, static_cast<int>(i));
placeNoteCheckerErrors(bar, v);
}
}
// Synchronize minimum X-es between the contexts - all the noteheads or barlines should be horizontally aligned.
for (unsigned int i = 0; i < streams; i++)
maxX = (streamsX[i] > maxX) ? streamsX[i] : maxX;
for (unsigned int i = 0; i < streams; i++)
if (musStreamList[static_cast<int>(i)].size() && musStreamList[static_cast<int>(i)].last()->musElementType() != CAMusElement::FunctionMark)
streamsX[i] = maxX;
// Place accidentals and key names of the function marks, if needed.
// These elements are so called Support elements. They can't be selected and they're not really connected usually to any logical element, but they're needed when drawing.
double maxWidth = 0;
double maxAccidentalXEnd = 0;
QList<CADrawableAccidental*> lastAccidentals;
for (unsigned int i = 0; i < streams; i++) {
// loop until the element has come, which has bigger timeStart
CADrawableMusElement* newElt = nullptr;
int oldStreamIdx = streamsIdx[i];
while ((streamsIdx[i] < musStreamList[static_cast<int>(i)].size()) && ((elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]))->timeStart() == timeStart) && (elt->isPlayable())) {
drawableContext = drawableContextMap[elt->context()];
if (elt->musElementType() == CAMusElement::Note && static_cast<CADrawableStaff*>(drawableContext)->getAccs(streamsX[i], static_cast<CANote*>(elt)->diatonicPitch().noteName()) != static_cast<CANote*>(elt)->diatonicPitch().accs()) {
newElt = new CADrawableAccidental(
static_cast<signed char>(static_cast<CANote*>(elt)->diatonicPitch().accs()),
static_cast<CANote*>(elt),
static_cast<CADrawableStaff*>(drawableContext),
streamsX[i],
static_cast<CADrawableStaff*>(drawableContext)->calculateCenterYCoord(static_cast<CANote*>(elt), lastClef[i]));
v->addMElement(newElt);
lastAccidentals << static_cast<CADrawableAccidental*>(newElt);
if (newElt->neededWidth() > maxWidth)
maxWidth = static_cast<int>(newElt->neededWidth());
if (maxAccidentalXEnd < newElt->neededWidth() + newElt->xPos())
maxAccidentalXEnd = static_cast<int>(newElt->neededWidth() + newElt->xPos());
}
streamsIdx[i]++;
}
streamsIdx[i] = oldStreamIdx;
streamsX[i] += ((maxWidth != 0.0) ? (maxWidth + 1) : 0); // append the needed space for the last used note
}
// Synchronize minimum X-es between the contexts - all the noteheads or barlines should be horizontally aligned.
for (unsigned int i = 0; i < streams; i++)
maxX = (streamsX[i] > maxX) ? streamsX[i] : maxX;
for (unsigned int i = 0; i < streams; i++)
streamsX[i] = maxX;
// Align support elements (accidentals, function key names) to the right
for (int i = 0; i < lastDFMKeyNames.size(); i++)
lastDFMKeyNames[i]->setXPos(maxX - lastDFMKeyNames[i]->neededWidth() - 2);
double deltaXPos = maxX - maxAccidentalXEnd;
for (int i = 0; i < lastAccidentals.size(); i++) {
lastAccidentals[i]->setXPos(lastAccidentals[i]->xPos() + deltaXPos - 1);
}
// Place noteheads and other elements aligned to noteheads (syllables, function marks)
for (unsigned int i = 0; i < streams; i++) {
// loop until the element has come, which has bigger timeStart
while ((streamsIdx[i] < musStreamList[static_cast<int>(i)].size()) && ((elt = musStreamList[static_cast<int>(i)].at(streamsIdx[i]))->timeStart() == timeStart) && (elt->isPlayable() || elt->musElementType() == CAMusElement::FiguredBassMark || elt->musElementType() == CAMusElement::FunctionMark || elt->musElementType() == CAMusElement::Syllable || elt->musElementType() == CAMusElement::ChordName)) {
drawableContext = drawableContextMap[elt->context()];
CADrawableMusElement* newElt = nullptr;
switch (elt->musElementType()) {
case CAMusElement::Note: {
newElt = new CADrawableNote(
static_cast<CANote*>(elt),
drawableContext,
streamsX[i],
static_cast<CADrawableStaff*>(drawableContext)->calculateCenterYCoord(static_cast<CANote*>(elt), lastClef[i]));
// Create Ties
if (static_cast<CADrawableNote*>(newElt)->note()->tieStart()) {
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->tieStart()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->actualSlurDirection();
CADrawableSlur* tie = nullptr;
if (dir == CASlur::SlurUp) {
tie = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->tieStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos(),
newElt->xPos() + 20, newElt->yPos() - 5,
newElt->xPos() + 40, newElt->yPos());
} else if (dir == CASlur::SlurDown) {
tie = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->tieStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos() + newElt->height(),
newElt->xPos() + 20, newElt->yPos() + newElt->height() + 5,
newElt->xPos() + 40, newElt->yPos() + newElt->height());
}
v->addMElement(tie);
}
if (static_cast<CADrawableNote*>(newElt)->note()->tieEnd()) {
// Set the slur coordinates for the second note
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->tieEnd()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->tieEnd()->noteStart()->actualSlurDirection();
CADrawableSlur* dSlur = static_cast<CADrawableSlur*>(v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->tieEnd()));
dSlur->setX2(newElt->xPos());
dSlur->setXMid(qRound(0.5 * dSlur->xPos() + 0.5 * newElt->xPos()));
if (dir == CASlur::SlurUp) {
dSlur->setY2(newElt->yPos());
dSlur->setYMid(qMin(dSlur->y2(), dSlur->y1()) - 5);
} else if (dir == CASlur::SlurDown) {
dSlur->setY2(newElt->yPos() + newElt->height());
dSlur->setYMid(qMax(dSlur->y2(), dSlur->y1()) + 5);
}
}
// Create Slurs
if (static_cast<CADrawableNote*>(newElt)->note()->slurStart()) {
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->slurStart()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->actualSlurDirection();
CADrawableSlur* slur = nullptr;
if (dir == CASlur::SlurUp) {
slur = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->slurStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos(),
newElt->xPos() + 20, newElt->yPos() - 15,
newElt->xPos() + 40, newElt->yPos());
} else if (dir == CASlur::SlurDown) {
slur = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->slurStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos() + newElt->height(),
newElt->xPos() + 20, newElt->yPos() + newElt->height() + 15,
newElt->xPos() + 40, newElt->yPos() + newElt->height());
}
v->addMElement(slur);
}
if (static_cast<CADrawableNote*>(newElt)->note()->slurEnd()) {
// Set the slur coordinates for the second note
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->slurEnd()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->slurEnd()->noteStart()->actualSlurDirection();
CADrawableSlur* dSlur = static_cast<CADrawableSlur*>(v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->slurEnd()));
if (dSlur) {
dSlur->setX2(newElt->xPos());
dSlur->setXMid(qRound(0.5 * dSlur->xPos() + 0.5 * newElt->xPos()));
if (dir == CASlur::SlurUp) {
dSlur->setY2(newElt->yPos());
dSlur->setYMid(qMin(dSlur->y2(), dSlur->y1()) - 15);
} else if (dir == CASlur::SlurDown) {
dSlur->setY2(newElt->yPos() + newElt->height());
dSlur->setYMid(qMax(dSlur->y2(), dSlur->y1()) + 15);
}
}
}
// Create Phrasing Slurs
if (static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurStart()) {
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurStart()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->actualSlurDirection();
CADrawableSlur* phrasingSlur = nullptr;
if (dir == CASlur::SlurUp) {
phrasingSlur = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos(),
newElt->xPos() + 20, newElt->yPos() - 19,
newElt->xPos() + 40, newElt->yPos());
} else if (dir == CASlur::SlurDown) {
phrasingSlur = new CADrawableSlur(
static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurStart(), drawableContext,
newElt->xPos() + newElt->width(), newElt->yPos() + newElt->height(),
newElt->xPos() + 20, newElt->yPos() + newElt->height() + 19,
newElt->xPos() + 40, newElt->yPos() + newElt->height());
}
v->addMElement(phrasingSlur);
}
if (static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurEnd()) {
// Set the slur coordinates for the second note
CASlur::CASlurDirection dir = static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurEnd()->slurDirection();
if (dir == CASlur::SlurPreferred || dir == CASlur::SlurNeutral)
dir = static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurEnd()->noteStart()->actualSlurDirection();
CADrawableSlur* dSlur = static_cast<CADrawableSlur*>(v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->phrasingSlurEnd()));
dSlur->setX2(newElt->xPos());
dSlur->setXMid(qRound(0.5 * dSlur->xPos() + 0.5 * newElt->xPos()));
if (dir == CASlur::SlurUp) {
dSlur->setY2(newElt->yPos());
dSlur->setYMid(qMin(dSlur->y2(), dSlur->y1()) - 19);
} else if (dir == CASlur::SlurDown) {
dSlur->setY2(newElt->yPos() + newElt->height());
dSlur->setYMid(qMax(dSlur->y2(), dSlur->y1()) + 19);
}
}
v->addMElement(newElt);
// add tuplet - same as for the rests
if (static_cast<CADrawableNote*>(newElt)->note()->isLastInTuplet()) {
double x1 = v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->tuplet()->firstNote())->xPos();
double x2 = newElt->xPos() + newElt->width();
double y1 = v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->tuplet()->firstNote())->yPos();
if (y1 > drawableContext->yPos() && y1 < drawableContext->yPos() + drawableContext->height()) {
y1 = drawableContext->yPos() + drawableContext->height() + 10; // inside the staff
} else if (y1 < drawableContext->yPos()) {
y1 -= 10; // above the staff
} else {
y1 += 10; // under the staff
}
double y2 = v->findMElement(static_cast<CADrawableNote*>(newElt)->note()->tuplet()->lastNote())->yPos();
if (y2 > drawableContext->yPos() && y2 < drawableContext->yPos() + drawableContext->height()) {
y2 = drawableContext->yPos() + drawableContext->height() + 10; // inside the staff
} else if (y2 < drawableContext->yPos()) {
y2 -= 10; // above the staff
} else {
y2 += 10; // under the staff
}
CADrawableTuplet* dTuplet = new CADrawableTuplet(static_cast<CADrawableNote*>(newElt)->note()->tuplet(), drawableContext, x1, y1, x2, y2);
v->addMElement(dTuplet);
}
if (static_cast<CANote*>(elt)->isLastInChord())
streamsX[i] += (newElt->neededWidth() + MINIMUM_SPACE);
placeMarks(newElt, v, static_cast<int>(i));
break;
}
case CAMusElement::Rest: {
newElt = new CADrawableRest(
static_cast<CARest*>(elt),
drawableContext,
streamsX[i],
drawableContext->yPos());
v->addMElement(newElt);
streamsX[i] += (newElt->neededWidth() + MINIMUM_SPACE);
// add tuplet - same as for the notes
if (static_cast<CADrawableRest*>(newElt)->rest()->isLastInTuplet()) {
double x1 = v->findMElement(static_cast<CADrawableRest*>(newElt)->rest()->tuplet()->firstNote())->xPos();
double x2 = newElt->xPos() + newElt->width();
double y1 = v->findMElement(static_cast<CADrawableRest*>(newElt)->rest()->tuplet()->firstNote())->yPos();
if (y1 > drawableContext->yPos() && y1 < drawableContext->yPos() + drawableContext->height()) {
y1 = drawableContext->yPos() + drawableContext->height() + 10; // inside the staff
} else if (y1 < drawableContext->yPos()) {
y1 -= 10; // above the staff
} else {
y1 += 10; // under the staff
}
double y2 = v->findMElement(static_cast<CADrawableRest*>(newElt)->rest()->tuplet()->lastNote())->yPos();
if (y2 > drawableContext->yPos() && y2 < drawableContext->yPos() + drawableContext->height()) {
y2 = drawableContext->yPos() + drawableContext->height() + 10; // inside the staff
} else if (y2 < drawableContext->yPos()) {
y2 -= 10; // above the staff
} else {
y2 += 10; // under the staff
}
/// \todo replace raw pointer with shared or unique pointer
CADrawableTuplet* dTuplet = new CADrawableTuplet(static_cast<CADrawableRest*>(newElt)->rest()->tuplet(), drawableContext, x1, y1, x2, y2);
v->addMElement(dTuplet);
}
placeMarks(newElt, v, static_cast<int>(i));
break;
}
case CAMusElement::MidiNote: {
CADrawableStaff* dStaff = static_cast<CADrawableStaff*>(drawableContext);
CAMidiNote* midiNote = static_cast<CAMidiNote*>(elt);
int pitch = 0;
if (lastKeySig[i]) {
pitch = CADiatonicPitch::diatonicPitchFromMidiPitchKey(midiNote->midiPitch(), lastKeySig[i]->diatonicKey()).noteName();
} else {
pitch = CADiatonicPitch::diatonicPitchFromMidiPitch(midiNote->midiPitch()).noteName();
}
/// \todo replace raw pointer with shared or unique pointer
newElt = new CADrawableMidiNote(midiNote, dStaff, streamsX[i], dStaff->calculateCenterYCoord(pitch, streamsX[i]));
break;
}
case CAMusElement::Syllable: {
/// \todo replace raw pointer with shared or unique pointer
newElt = new CADrawableSyllable(
static_cast<CASyllable*>(elt),
static_cast<CADrawableLyricsContext*>(drawableContext),
streamsX[i],
drawableContext->yPos() + qRound(CADrawableLyricsContext::DEFAULT_TEXT_VERTICAL_SPACING));
CAMusElement* prevSyllable = drawableContext->context()->previous(elt);
CADrawableMusElement* prevDSyllable = (prevSyllable ? v->findMElement(prevSyllable) : nullptr);
if (prevDSyllable) {
prevDSyllable->setWidth(newElt->xPos() - prevDSyllable->xPos());
}
v->addMElement(newElt);
streamsX[i] += (newElt->neededWidth() + MINIMUM_SPACE);
break;
}
case CAMusElement::FiguredBassMark: {
CAFiguredBassMark* fbm = static_cast<CAFiguredBassMark*>(elt);
for (int j = fbm->numbers().size() - 1; j >= 0; j--) {
/// \todo replace raw pointer with shared or unique pointer
newElt = new CADrawableFiguredBassNumber(
fbm,
fbm->numbers()[j],
static_cast<CADrawableFiguredBassContext*>(drawableContext),
// shift figured bass mark more right, if only one character
streamsX[i] + ((!fbm->accs().contains(fbm->numbers()[j]) || fbm->numbers()[j] == 0) ? 3 : 0),
drawableContext->yPos() + CADrawableFiguredBassNumber::DEFAULT_NUMBER_SIZE * (fbm->numbers().size() - 1 - j));
v->addMElement(newElt);
}
streamsX[i] += (newElt ? newElt->neededWidth() : 0 + MINIMUM_SPACE);
break;
}
case CAMusElement::FunctionMark: {
CAFunctionMark* function = static_cast<CAFunctionMark*>(elt);
// Make a new line, if parallel function present
if (streamsIdx[i] - 1 >= 0 && musStreamList[i].at(streamsIdx[i] - 1)->timeStart() == musStreamList[i].at(streamsIdx[i])->timeStart()) {
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->nextLine();
/// \todo replace raw pointer with shared or unique pointer
CADrawableFunctionMarkSupport* newKey = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Key,
CADiatonicKey::diatonicKeyToString(function->key()),
drawableContext,
streamsX[i],
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Middle));
newKey->setXPos(streamsX[i] - newKey->width() - 2);
v->addMElement(newKey);
}
// Place the function itself, if it's independent
/// \todo replace raw pointer with shared or unique pointer
newElt = new CADrawableFunctionMark(
function,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
streamsX[i],
(function->tonicDegree() == CAFunctionMark::T && (!function->isPartOfEllipse())) ? static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Middle) : static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Upper));
// Place alterations
CADrawableFunctionMarkSupport* alterations = nullptr;
if (function->addedDegrees().size() || function->alteredDegrees().size()) {
/// \todo replace raw pointer with shared or unique pointer
alterations = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Alterations,
function,
drawableContext,
streamsX[i],
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Lower) + 3);
// center-align alterations to function, if placed
if (newElt)
alterations->setXPos(newElt->xPos() + newElt->width() / 2.0 - alterations->width() / 2.0 + 0.5);
else //center-align to note
alterations->setXPos(streamsX[i] + 5 - alterations->width() / 2.0 + 0.5);
}
// Place tonicization. The same tonicization is always placed from streamsIdx[i]-nth to streamsIdx[i]-1th element, where streamsIdx[i] is the current index.
int j = streamsIdx[i] - 1; //index of the previous elt
CADrawableFunctionMarkSupport* tonicization = nullptr;
for (; j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->function() == CAFunctionMark::Undefined; j--)
; //ignore any alterations back there
if (j >= 0 && (
// place tonicization, if tonic degree is not default
static_cast<CAFunctionMark*>(musStreamList[i].at(j))->tonicDegree() != CAFunctionMark::T && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->tonicDegree() != CAFunctionMark::Undefined
// and it's not still the same
&& (function->tonicDegree() != static_cast<CAFunctionMark*>(musStreamList[i].at(j))->tonicDegree() || function->key() != static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key())
// always place tonicization, if ellipse is present
//|| ((CAFunctionMark*)musStreamList[i].at(j))->isPartOfEllipse()
)) {
//CAFunctionMark::CAFunctionType type = ((CAFunctionMark*)musStreamList[i].at(j))->tonicDegree();
CAFunctionMark* right = static_cast<CAFunctionMark*>(musStreamList[i].at(j));
// find the n-th element back
while (--j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->tonicDegree() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->tonicDegree() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->key())
;
CAFunctionMark* tonicStart = static_cast<CAFunctionMark*>(musStreamList[i].at(++j));
CADrawableFunctionMark* left = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(tonicStart));
if (tonicStart != static_cast<CAMusElement*>(musStreamList[i].at(streamsIdx[i] - 1))) { // tonicization isn't single (more than 1 tonic element)
/// \todo replace raw pointer with shared or unique pointer
tonicization = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Tonicization,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Middle),
static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(right)));
} else { // tonicization is single (one tonic)
/// \todo replace raw pointer with shared or unique pointer
tonicization = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Tonicization,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Middle));
tonicization->setXPos(left->xPos() + 0.5 * left->width() - 0.5 * tonicization->width() + 0.5); // align center
}
}
// Place horizontal modulation rectangle, if needed
j = streamsIdx[i] - 1;
CADrawableFunctionMarkSupport* hModulationRect = nullptr;
if (newElt && j >= 0) {
if (static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() != function->key() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->timeStart() != function->timeStart()) {
CADrawableFunctionMark* left = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(musStreamList[i].at(j)));
/// \todo replace raw pointer with shared or unique pointer
hModulationRect = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Rectangle,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
left->yPos(),
static_cast<CADrawableFunctionMark*>(newElt));
if (streamsIdx[i] % 2)
hModulationRect->setRectWider(true); //make it wider, so it potentially doesn't overlap with other rectangles around
}
}
// Place vertical modulation rectangle, if needed
// This must be done *before* the extender lines are placed!
j = streamsIdx[i] - 1;
CADrawableFunctionMarkSupport* vModulationRect = nullptr;
while (--j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() != static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->key() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->timeStart() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->timeStart())
;
if (++j >= 0 && j != streamsIdx[i] - 1) {
CADrawableFunctionMark* left = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(musStreamList[i].at(j)));
/// \todo replace raw pointer with shared or unique pointer
vModulationRect = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Rectangle,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
left->yPos(),
static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(musStreamList[i].at(streamsIdx[i] - 1))));
}
// Place horizontal chord area rectangle for the previous elements, if element neighbours are of the same chordarea/function
j = streamsIdx[i] - 1;
CADrawableFunctionMarkSupport* hChordAreaRect = nullptr;
if (j >= 0 && // don't draw rectangle, if the current element would still be in the rectangle
(
(static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() == function->key() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->function() != function->function() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->function() != function->chordArea() && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->chordArea() != function->chordArea())
|| static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() != function->key()
|| j == musStreamList[i].size())) {
bool oneFunctionOnly = true;
while (--j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->chordArea() != CAFunctionMark::Undefined && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->key() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->key() && (static_cast<CAFunctionMark*>(musStreamList[i].at(j))->chordArea() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->chordArea() || static_cast<CAFunctionMark*>(musStreamList[i].at(j))->function() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->chordArea() || static_cast<CAFunctionMark*>(musStreamList[i].at(j))->chordArea() == static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->function()))
if (static_cast<CAFunctionMark*>(musStreamList[i].at(j))->function() != static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->function())
oneFunctionOnly = false;
if (++j != streamsIdx[i] - 1 && !oneFunctionOnly) {
CADrawableFunctionMark* left = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(musStreamList[i].at(j)));
/// \todo replace raw pointer with shared or unique pointer
hChordAreaRect = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Rectangle,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
left->yPos(),
static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(musStreamList[i].at(streamsIdx[i] - 1))));
}
}
// Place chordarea mark below in paranthesis, if no neighbours are of same chordarea
CADrawableFunctionMarkSupport* chordArea = nullptr;
j = streamsIdx[i];
if (newElt && function->chordArea() != CAFunctionMark::Undefined && function->chordArea() != function->function() && // chord area is the same as function name - don't draw chordarea then
(j - 1 < 0 || ((static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->key() == function->key() && static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->chordArea() != function->chordArea() && static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->function() != function->chordArea() && static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->chordArea() != function->function()) || static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->tonicDegree() != function->tonicDegree() || static_cast<CAFunctionMark*>(musStreamList[i].at(j - 1))->key() != function->key())) && (j + 1 >= musStreamList[i].size() || ((static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->key() == function->key() && static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->chordArea() != function->chordArea() && static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->function() != function->chordArea() && static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->chordArea() != function->function()) || static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->tonicDegree() != function->tonicDegree() || static_cast<CAFunctionMark*>(musStreamList[i].at(j + 1))->key() != function->key()))) {
/// \todo replace raw pointer with shared or unique pointer
chordArea = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::ChordArea,
static_cast<CADrawableFunctionMark*>(newElt),
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
streamsX[i],
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Lower));
chordArea->setXPos(newElt->xPos() - (chordArea->width() - newElt->width()) / 2.0 + 0.5);
}
// Place ellipse
j = streamsIdx[i] - 1;
CADrawableFunctionMarkSupport* ellipse = nullptr;
if (j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->isPartOfEllipse() //place ellipse, if it has it
&& (!function->isPartOfEllipse())) { //and it's not lasting anymore
//find the n-th element back
while (--j >= 0 && static_cast<CAFunctionMark*>(musStreamList[i].at(j))->isPartOfEllipse())
;
CAFunctionMark* ellipseStart = static_cast<CAFunctionMark*>(musStreamList[i].at(++j));
CADrawableFunctionMark* left = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(ellipseStart));
/// \todo replace raw pointer with shared or unique pointer
ellipse = new CADrawableFunctionMarkSupport(
CADrawableFunctionMarkSupport::Ellipse,
left,
static_cast<CADrawableFunctionMarkContext*>(drawableContext),
left->xPos(),
static_cast<CADrawableFunctionMarkContext*>(drawableContext)->yPosLine(CADrawableFunctionMarkContext::Lower),
static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(static_cast<CAMusElement*>(musStreamList[i].at(streamsIdx[i] - 1)))));
}
// Set extender line and change the width of the previous function mark
if (newElt && streamsIdx[i] - 1 >= 0 && musStreamList[static_cast<int>(i)].at(streamsIdx[i] - 1)->timeStart() != musStreamList[static_cast<int>(i)].at(streamsIdx[i])->timeStart()) {
CAFunctionMark* prevElt = static_cast<CAFunctionMark*>(musStreamList[static_cast<int>(i)].at(streamsIdx[i] - 1));
CADrawableFunctionMark* prevDFM = static_cast<CADrawableFunctionMark*>(drawableContext->findMElement(prevElt));
// draw extender line instead of the function, if functions are the same
if (function->function() != CAFunctionMark::Undefined && function->function() == prevElt->function() && function->tonicDegree() == prevElt->tonicDegree() && function->key() == prevElt->key()) {
static_cast<CADrawableFunctionMark*>(newElt)->setExtenderLineOnly(true);
static_cast<CADrawableFunctionMark*>(newElt)->setExtenderLineVisible(true);
prevDFM->setExtenderLineVisible(true);
if (tonicization) {
//tonicization->setExtenderLineVisible( true );
if (prevElt->key() == function->key())
tonicization->setWidth(newElt->xPos() - tonicization->xPos());
else
tonicization->setWidth(lastDFMKeyNames.last()->xPos() - tonicization->xPos());
}
if (lastDFMTonicizations[i]) {
//lastDFMTonicizations[i]->setExtenderLineVisible(true);
if (prevElt->key() == function->key())
lastDFMTonicizations[i]->setWidth(newElt->xPos() - lastDFMTonicizations[i]->xPos());
else
lastDFMTonicizations[i]->setWidth(lastDFMKeyNames[i]->xPos() - lastDFMTonicizations[i]->xPos());
}
}
if (prevDFM && prevDFM->isExtenderLineVisible()) {
if (prevElt->key() == function->key())
prevDFM->setWidth(newElt->xPos() - prevDFM->xPos());
else
prevDFM->setWidth(lastDFMKeyNames.last()->xPos() - prevDFM->xPos());
}
}
if (newElt)
v->addMElement(newElt); // when only alterations are made and no function placed, IF is needed
if (tonicization) {
v->addMElement(tonicization);
lastDFMTonicizations[i] = tonicization;
}
if (ellipse)
v->addMElement(ellipse);
if (hModulationRect)
v->addMElement(hModulationRect);
if (vModulationRect)
v->addMElement(vModulationRect);
if (hChordAreaRect)
v->addMElement(hChordAreaRect);
if (chordArea)
v->addMElement(chordArea);
if (alterations)
v->addMElement(alterations);
if (newElt && streamsIdx[i] + 1 < musStreamList[static_cast<int>(i)].size() && musStreamList[static_cast<int>(i)].at(streamsIdx[i] + 1)->timeStart() != musStreamList[static_cast<int>(i)].at(streamsIdx[i])->timeStart())
streamsX[i] += (newElt->neededWidth());
break;
}
case CAMusElement::ChordName: {
/// \todo replace raw pointer with shared or unique pointer
newElt = new CADrawableChordName(
static_cast<CAChordName*>(elt),
static_cast<CADrawableChordNameContext*>(drawableContext),
streamsX[i],
drawableContext->yPos() + qRound(CADrawableChordNameContext::DEFAULT_CHORDNAME_VERTICAL_SPACING));
CAMusElement* prevChordName = drawableContext->context()->previous(elt);
CADrawableMusElement* prevDChordName = (prevChordName ? v->findMElement(prevChordName) : nullptr);
if (prevDChordName) {
prevDChordName->setWidth(newElt->xPos() - prevDChordName->xPos());
}
v->addMElement(newElt);
placeNoteCheckerErrors(newElt, v);
streamsX[i] += (newElt->neededWidth() + MINIMUM_SPACE);
break;
}
default:
qDebug() << "Warning: CALayoutEngine::reposit2 - Unhandled Element" << elt->musElementType();
break;
}
streamsIdx[i]++;
}
}
}
// reposit the scalable elements (eg. crescendo)
for (int i = 0; i < scalableElts.size(); i++) {
scalableElts[i]->setXPos(v->timeToCoords(scalableElts[i]->musElement()->timeStart()));
scalableElts[i]->setWidth(v->timeToCoords(scalableElts[i]->musElement()->timeEnd()) - scalableElts[i]->xPos());
v->addMElement(scalableElts[i]);
}
delete[] streamsIdx;
delete[] streamsX;
delete[] streamsRehersalMarks;
delete[] lastClef;
delete[] lastKeySig;
delete[] lastTimeSig;
delete[] lastDFMTonicizations;
}
/*!
Place marks for the given music element.
*/
void CALayoutEngine::placeMarks(CADrawableMusElement* e, CAScoreView* v, int streamIdx)
{
CAMusElement* elt = e->musElement();
double xCoord = e->xPos();
for (int i = 0, j = 0, k = 0; i < elt->markList().size(); i++) { // j/k are vertical offsets above/below the staff
if (elt->markList()[i]->isCommon() && elt->musElementType() == CAMusElement::Note && !static_cast<CANote*>(elt)->isFirstInChord()) {
continue;
}
CAMark* mark = elt->markList()[i];
double yCoord;
CAFingering* fingering = dynamic_cast<CAFingering*>(mark);
if (mark->markType() == CAMark::Pedal || (fingering && (fingering->fingerList()[0] == CAFingering::LHeel || fingering->fingerList()[0] == CAFingering::LToe)) || (elt->musElementType() == CAMusElement::Note && static_cast<CANote*>(elt)->actualSlurDirection() == CASlur::SlurDown && ((mark->markType() == CAMark::Text) || (mark->markType() == CAMark::Fermata) || (mark->markType() == CAMark::Articulation)))) {
// place mark below
xCoord = e->xPos();
yCoord = qMax(e->yPos() + e->height(), e->drawableContext()->yPos() + e->drawableContext()->height()) + 20 * (k + 1);
k++;
} else if (elt->musElementType() == CAMusElement::Note && static_cast<CANote*>(elt)->isPartOfChord() && fingering && fingering->fingerList()[0] < 6) {
// place mark beside the note
xCoord = e->xPos() + e->width();
yCoord = e->yPos() - 2;
} else if (mark->markType() == CAMark::Articulation && static_cast<CAArticulation*>(mark)->articulationType() == CAArticulation::Breath) {
// place breath mark above right
xCoord = e->xPos() + 1.2 * e->width();
yCoord = qMin(e->yPos() - 2.5 * e->height(), e->drawableContext()->yPos() - 20);
} else if (mark->markType() == CAMark::Articulation) {
// place other articulation marks above center
xCoord = e->xPos() + e->width() / 2.0 - 3;
yCoord = qMin(e->yPos(), e->drawableContext()->yPos()) - 20 * (j + 1);
j++;
} else {
// place mark above
xCoord = e->xPos();
yCoord = qMin(e->yPos(), e->drawableContext()->yPos()) - 20 * (j + 1);
j++;
}
/// \todo replace raw pointer with shared or unique pointer
CADrawableMark* m = new CADrawableMark(mark, e->drawableContext(), xCoord, yCoord);
if (mark->markType() == CAMark::RehersalMark)
m->setRehersalMarkNumber(streamsRehersalMarks[streamIdx]++);
if (m->isHScalable() || m->isVScalable()) {
scalableElts << m;
} else {
v->addMElement(m);
}
}
}
void CALayoutEngine::placeNoteCheckerErrors(CADrawableMusElement* dMusElt, CAScoreView* v)
{
QList<CANoteCheckerError*> ncErrors = dMusElt->musElement()->noteCheckerErrorList();
for (int i = 0; i < ncErrors.size(); i++) {
v->addDrawableNoteCheckerError(
/// \todo replace raw pointer with shared or unique pointer
new CADrawableNoteCheckerError(ncErrors[i], dMusElt));
}
}
| 64,913
|
C++
|
.cpp
| 942
| 49.863057
| 1,216
| 0.546235
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,335
|
drawablefunctionmark.cpp
|
canorusmusic_canorus/src/layout/drawablefunctionmark.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QDebug>
#include <QFont>
#include <QPainter>
#include <stdio.h>
#include "layout/drawablefunctionmark.h"
#include "layout/drawablefunctionmarkcontext.h"
#include "score/functionmark.h"
/*!
\class CADrawableFunctionMark
\brief The drawable instance of the function mark.
These music elements are ordinary music elements selectable by the user.
\sa CADrawableFunctionMarkSupport
*/
CADrawableFunctionMark::CADrawableFunctionMark(CAFunctionMark* function, CADrawableFunctionMarkContext* context, double x, double y)
: CADrawableMusElement(function, context, x, y)
{
setDrawableMusElementType(CADrawableMusElement::DrawableFunctionMark);
_extenderLineVisible = false;
_extenderLineOnly = false;
//CAMusElement *prevMusElt;
setWidth(11); // default width
// function mark is stable
if ( // tonic degree is tonic
functionMark()->tonicDegree() == CAFunctionMark::T &&
// and the function mark is not part of the ellipse
(!functionMark()->isPartOfEllipse()))
switch (functionMark()->function()) { /// \todo Width determination should be done automatically using QPainter::boundingRect() method
//character widths are calculated using FreeSans font, pixelSize 19
case CAFunctionMark::I:
_text = "I";
_width = 5;
break;
case CAFunctionMark::II:
_text = "II";
_width = 10;
break;
case CAFunctionMark::III:
_text = "III";
_width = 15;
break;
case CAFunctionMark::IV:
_text = "IV";
_width = 18;
break;
case CAFunctionMark::V:
_text = "V";
_width = 13;
break;
case CAFunctionMark::VI:
_text = "VI";
_width = 18;
break;
case CAFunctionMark::VII:
_text = "VII";
_width = 23;
break;
case CAFunctionMark::T:
_text = "T";
_width = 12;
break;
case CAFunctionMark::S:
_text = "S";
_width = 13;
break;
case CAFunctionMark::D:
_text = "D";
_width = 14;
break;
case CAFunctionMark::F:
_text = "F";
_width = 12;
break;
case CAFunctionMark::N:
_text = "N";
_width = 14;
break;
case CAFunctionMark::L:
_text = "L";
_width = 11;
break;
case CAFunctionMark::K:
_text = "K";
_width = 12;
break;
case CAFunctionMark::Undefined:
break;
}
else
// function mark is not stable - its tonic degree is not Tonic
switch (functionMark()->function()) { /// \todo Width determination should be done automatically using QPainter::boundingRect() method
//character widths are calculated using FreeSans font, pixelSize 17
case CAFunctionMark::I:
_text = "I";
_width = 5;
break;
case CAFunctionMark::II:
_text = "II";
_width = 10;
break;
case CAFunctionMark::III:
_text = "III";
_width = 15;
break;
case CAFunctionMark::IV:
_text = "IV";
_width = 16;
break;
case CAFunctionMark::V:
_text = "V";
_width = 11;
break;
case CAFunctionMark::VI:
_text = "VI";
_width = 16;
break;
case CAFunctionMark::VII:
_text = "VII";
_width = 21;
break;
case CAFunctionMark::T:
_text = "T";
_width = 10;
break;
case CAFunctionMark::S:
_text = "S";
_width = 11;
break;
case CAFunctionMark::D:
_text = "D";
_width = 12;
break;
case CAFunctionMark::F:
_text = "F";
_width = 10;
break;
case CAFunctionMark::N:
_text = "N";
_width = 12;
break;
case CAFunctionMark::L:
_text = "L";
_width = 9;
break;
case CAFunctionMark::K:
_text = "K";
_width = 10;
break;
case CAFunctionMark::Undefined:
break;
}
if (function->isMinor()) { //prepend a small circle
_text.prepend(QString(0x02DA));
setWidth(width() + 6);
setXPos(xPos() - 6);
}
setHeight(15);
}
CADrawableFunctionMark::~CADrawableFunctionMark()
{
}
void CADrawableFunctionMark::draw(QPainter* p, CADrawSettings s)
{
int rightBorder = s.x + qRound(width() * s.z);
QFont font("FreeSans");
if (functionMark()->tonicDegree() == CAFunctionMark::T)
font.setPixelSize(qRound(19 * s.z));
else
font.setPixelSize(qRound(17 * s.z));
p->setPen(QPen(s.color));
p->setFont(font);
if (!isExtenderLineOnly()) {
p->drawText(s.x, s.y + qRound(height() * s.z), _text);
s.x += qRound(p->boundingRect(0, 0, 0, 0, 0, _text).width() + 1 * s.z);
}
if (isExtenderLineVisible())
p->drawLine(s.x, s.y + qRound((height() / 2.0) * s.z),
rightBorder, s.y + qRound((_height / 2.0) * s.z));
}
CADrawableFunctionMark* CADrawableFunctionMark::clone(CADrawableContext* newContext)
{
return new CADrawableFunctionMark(functionMark(), (newContext) ? static_cast<CADrawableFunctionMarkContext*>(newContext) : drawableFunctionMarkContext(), (static_cast<CAFunctionMark*>(_musElement))->isMinor() ? xPos() + 6 : xPos(), yPos());
}
/*!
\class CADrawableFunctionMarkSupport
\brief Rectangles, key names, numbers below/above function, lines etc.
Support class which draws the key of the function, rectangle around it, chord area, ellipse etc.
These drawable music elements aren't selectable, but they can't be drawn by a single CADrawableFunctionMark because they're usually dependent on more than one function mark.
\sa CADrawableFunctionMark
*/
/*!
KeyName constructor.
*/
CADrawableFunctionMarkSupport::CADrawableFunctionMarkSupport(CADrawableFunctionMarkSupportType type, const QString key, CADrawableContext* c, double x, double y)
: CADrawableMusElement(nullptr, c, x, y)
{ // support functions point to no music element
_drawableMusElementType = CADrawableMusElement::DrawableFunctionMarkSupport;
_drawableFunctionMarkSupportType = type;
_key = key;
_function1 = nullptr;
_function2 = nullptr;
if (type == Key) {
setWidth(0); /// \todo Width determination should be done automatically using QPainter::boundingRect() method
for (int i = 0; i < key.size(); i++) { // character widths are calculated using FreeSans font, pixelSize 17
if (key[i] == 'C')
_width += 12;
else if (key[i] == 'D')
_width += 12;
else if (key[i] == 'E')
_width += 11;
else if (key[i] == 'F')
_width += 10;
else if (key[i] == 'G')
_width += 13;
else if (key[i] == 'A')
_width += 11;
else if (key[i] == 'B')
_width += 11;
else if (key[i] == 'c')
_width += 9;
else if (key[i] == 'd')
_width += 9;
else if (key[i] == 'e')
_width += 9;
else if (key[i] == 'f')
_width += 5;
else if (key[i] == 'g')
_width += 9;
else if (key[i] == 'a')
_width += 9;
else if (key[i] == 'b')
_width += 9;
else if (key[i] == 'i')
_width += 5;
else if (key[i] == 's')
_width += 9;
}
_width += 5; // colon after the key name (:)
_height = 14;
}
setSelectable(false);
}
/*!
ChordArea, Tonicization, Modulation/ChordArea Rectangle, Ellipse constructor.
*/
CADrawableFunctionMarkSupport::CADrawableFunctionMarkSupport(CADrawableFunctionMarkSupportType type, CADrawableFunctionMark* f1, CADrawableContext* c, double x, double y, CADrawableFunctionMark* f2)
: CADrawableMusElement(nullptr, c, x, y)
{ // support functions point to no music element
_drawableMusElementType = CADrawableMusElement::DrawableFunctionMarkSupport;
_drawableFunctionMarkSupportType = type;
_function1 = f1;
_function2 = f2;
setWidth(0);
_extenderLineVisible = false;
_rectWider = false;
if (f1->functionMark()->isTonicDegreeMinor()) {
_width += 6;
}
if (type == ChordArea) {
// character widths are calculated using FreeSans font, pixelSize 17
/// \todo Width determination should be done automatically using QPainter::boundingRect() method
if (f1->functionMark()->chordArea() == CAFunctionMark::T) {
_width = 10;
} else if (f1->functionMark()->chordArea() == CAFunctionMark::S) {
_width = 11;
} else if (f1->functionMark()->chordArea() == CAFunctionMark::D) {
_width = 12;
}
_width += 12; //paranthesis
_height = 14;
} else if (type == Tonicization) {
// character widths are calculated using FreeSans font, pixelSize 19
/// \todo Width determination should be done automatically using QPainter::boundingRect() method
if (!f2) {
switch (f1->functionMark()->tonicDegree()) {
case CAFunctionMark::I:
_width += 5;
break;
case CAFunctionMark::II:
_width += 10;
break;
case CAFunctionMark::III:
_width += 15;
break;
case CAFunctionMark::IV:
_width += 16;
break;
case CAFunctionMark::V:
_width += 11;
break;
case CAFunctionMark::VI:
_width += 16;
break;
case CAFunctionMark::VII:
_width += 21;
break;
case CAFunctionMark::T:
_width += 10;
break;
case CAFunctionMark::S:
_width += 11;
break;
case CAFunctionMark::D:
_width += 12;
break;
case CAFunctionMark::F:
case CAFunctionMark::K:
case CAFunctionMark::L:
case CAFunctionMark::N:
case CAFunctionMark::Undefined:
fprintf(stderr, "Warning: CADrawableFunctionMarkSupport::CADrawableFunctionMarkSupport - Unhandled mark %d", f1->functionMark()->tonicDegree());
break;
}
} else {
_width = f2->xPos() + f2->width() - f1->xPos(); // multiple tonicization
}
_height = 15;
} else if (type == Rectangle) {
if (f2->xPos() + f2->width() - f1->xPos() < f1->xPos() + f1->width() - f2->xPos())
_width = f1->xPos() + f1->width() - f2->xPos() + 6; // used for vertical modulation
else
_width = f2->xPos() + f2->width() - f1->xPos() + 6; // used for horizontal modulation/chordarea rectangle
_xPos -= 3;
_height = (f2->yPos() + f2->height() - f1->yPos() + 6 > f1->yPos() + f1->height() - f2->yPos() + 6) ? f2->yPos() + f2->height() - f1->yPos() + 6 : f1->yPos() + f1->height() - f2->yPos() + 6;
_yPos = f2->yPos() < f1->yPos() ? f2->yPos() - 3 : f1->yPos() - 3;
} else if (type == Ellipse) {
_width = f2->xPos() + f2->width() - f1->xPos();
_height = 14;
}
setSelectable(false);
}
/*!
Alterations constructor.
*/
CADrawableFunctionMarkSupport::CADrawableFunctionMarkSupport(CADrawableFunctionMarkSupportType type, CAFunctionMark* function, CADrawableContext* c, double x, double y)
: CADrawableMusElement(function, c, x, y)
{
_drawableMusElementType = CADrawableMusElement::DrawableFunctionMarkSupport;
_drawableFunctionMarkSupportType = type;
_function1 = nullptr;
_function2 = nullptr;
_extenderLineVisible = false;
_rectWider = false;
_height = function->addedDegrees().size() * 13 + function->alteredDegrees().size() * 8;
if (function->function() == CAFunctionMark::Undefined) // paranthesis needed as well
_width = 9 + qRound(0.6 * _height);
else
_width = 6;
setSelectable(false);
}
CADrawableFunctionMarkSupport::~CADrawableFunctionMarkSupport()
{
}
void CADrawableFunctionMarkSupport::draw(QPainter* p, const CADrawSettings s)
{
QFont font("FreeSans");
QString text;
CAFunctionMark::CAFunctionType type = CAFunctionMark::CAFunctionType::Undefined;
bool minor = false;
//prepare drawing stuff
switch (_drawableFunctionMarkSupportType) {
case Key:
font.setPixelSize(qRound(17 * s.z));
break;
case ChordArea:
font.setPixelSize(qRound(17 * s.z));
type = _function1->functionMark()->chordArea();
minor = _function1->functionMark()->isChordAreaMinor();
break;
case Tonicization:
font.setPixelSize(qRound(19 * s.z));
type = _function1->functionMark()->tonicDegree();
minor = _function1->functionMark()->isTonicDegreeMinor();
break;
case Ellipse:
font.setPixelSize(qRound(14 * s.z));
break;
case Alterations:
font.setPixelSize(qRound(9 * s.z));
break;
case Rectangle:
break;
}
// fill in the text values for functions
if (_drawableFunctionMarkSupportType == Tonicization || _drawableFunctionMarkSupportType == ChordArea) {
switch (type) {
// character widths are calculated using FreeSans font, pixelSize 19
case CAFunctionMark::I:
text = "I";
break;
case CAFunctionMark::II:
text = "II";
break;
case CAFunctionMark::III:
text = "III";
break;
case CAFunctionMark::IV:
text = "IV";
break;
case CAFunctionMark::V:
text = "V";
break;
case CAFunctionMark::VI:
text = "VI";
break;
case CAFunctionMark::VII:
text = "VII";
break;
case CAFunctionMark::T:
text = "T";
break;
case CAFunctionMark::S:
text = "S";
break;
case CAFunctionMark::D:
text = "D";
break;
case CAFunctionMark::F:
text = "F";
break;
case CAFunctionMark::N:
text = "N";
break;
case CAFunctionMark::L:
text = "L";
break;
case CAFunctionMark::K:
text = "K";
break;
case CAFunctionMark::Undefined:
break;
}
if (minor)
text.prepend(QString(0x02DA));
}
p->setPen(QPen(s.color));
p->setFont(font);
// draw
switch (_drawableFunctionMarkSupportType) {
case Key:
p->drawText(s.x, s.y + qRound(_height * s.z), _key + ":");
break;
case ChordArea:
p->drawText(s.x, s.y + qRound(_height * s.z), QString("(") + text + ")");
break;
case Tonicization:
if (!_function2) { // tonicization is below a single function
p->drawText(s.x, s.y + qRound(_height * s.z), text);
if (_extenderLineVisible)
p->drawLine(s.x + p->boundingRect(0, 0, 0, 0, 0, text).width(), qRound(s.y + height() * s.z / 2.0),
qRound(s.x + width() * s.z), qRound(s.y + height() * s.z / 2.0));
} else {
p->drawText( // tonicization is below multiple functions
// get the x-coordinate where to start text rendering
qRound(s.x + (_function2->xPos() + _function2->width() - _function1->xPos()) * s.z / 2.0 - p->boundingRect(0, 0, 0, 0, 0, text).width() / 2.0),
s.y + qRound(_height * s.z),
text);
// draw line below side functions
p->drawLine(s.x, s.y, qRound(s.x + (_function2->xPos() + _function2->width() - _function1->xPos()) * s.z), s.y);
// draw extender line of the support function
if (_extenderLineVisible)
p->drawLine(s.x + qRound((_function2->xPos() + _function2->width() - _function1->xPos()) * s.z / 2.0 + p->boundingRect(0, 0, 0, 0, 0, text).width() / 2.0 + 1 * s.z), qRound(s.y + height() * s.z / 2.0),
qRound(s.x + width() * s.z), qRound(s.y + height() * s.z / 2.0));
}
break;
case Ellipse:
// draw vertical lines
p->drawLine(s.x, qRound(s.y + 2 * s.z), s.x, qRound(s.y + height() * s.z / 2.0)); //left vertical line
p->drawLine(qRound(s.x + width() * s.z), qRound(s.y + 2 * s.z), qRound(s.x + width() * s.z), qRound(s.y + height() * s.z / 2.0)); //right vertical line
// draw horizontal lines
p->drawLine(s.x, qRound(s.y + height() * s.z / 2.0), qRound(s.x + width() * s.z / 2.0 - p->boundingRect(0, 0, 0, 0, 0, "E").width() / 2.0 - 2 * s.z), qRound(s.y + height() * s.z / 2.0)); //left horizontal line
p->drawLine(qRound(s.x + width() * s.z / 2.0 + p->boundingRect(0, 0, 0, 0, 0, "E").width() / 2.0 + 2 * s.z), qRound(s.y + height() * s.z / 2.0), qRound(s.x + width() * s.z), qRound(s.y + height() * s.z / 2.0)); //right horizontal line
p->drawText(qRound(s.x + width() * s.z / 2.0 - p->boundingRect(0, 0, 0, 0, 0, "E").width() / 2.0), qRound(s.y + height() * s.z - 1 * s.z), "E");
break;
case Rectangle:
p->drawRect(s.x, s.y, qRound(width() * s.z), qRound(height() * s.z));
break;
case Alterations:
CAFunctionMark* f1 = static_cast<CAFunctionMark*>(_musElement);
int curX = s.x, curY = s.y;
if (f1->function() == CAFunctionMark::Undefined)
curX += qRound(0.3 * _height * s.z); // make space for left paranthesis, if needed
// draw added degrees
for (int i = 0; i < f1->addedDegrees().size(); i++) {
// draw upper number
p->drawText(qRound(curX + 2 * s.z), qRound(curY + 8 * s.z), f1->addedDegrees().at(i) < 0 ? QString::number(f1->addedDegrees().at(i) * (-1)) : QString::number(f1->addedDegrees().at(i)));
// draw additional + or - for added or substracted degree
p->drawText(qRound(curX + 2 * s.z), qRound(curY + 13 * s.z), f1->addedDegrees().at(i) < 0 ? "-" : "+");
curY += qRound(13 * s.z);
}
// draw altered degrees
for (int i = 0; i < f1->alteredDegrees().size(); i++) {
//draw numbers with + or - prefixed
p->drawText(curX, qRound(curY + 8 * s.z), f1->alteredDegrees().at(i) > 0 ? QString("+") + QString::number(+f1->alteredDegrees().at(i)) : QString::number(f1->alteredDegrees().at(i)));
curY += qRound(8 * s.z);
}
// draw paranthesis, if needed
if (f1->function() == CAFunctionMark::Undefined) {
curX -= qRound(0.3 * _height * s.z);
font.setPixelSize(qRound(_height * s.z));
p->setFont(font);
p->drawText(curX, qRound(curY - _height * s.z / 6.0), "(");
p->drawText(qRound(curX + (_width - 0.3 * _height) * s.z), qRound(curY - _height * s.z / 6.0), ")");
}
}
}
CADrawableFunctionMarkSupport* CADrawableFunctionMarkSupport::clone(CADrawableContext* newContext)
{
switch (_drawableFunctionMarkSupportType) {
case Key:
return new CADrawableFunctionMarkSupport(Key, _key, (newContext) ? newContext : _drawableContext, _xPos, _yPos);
case ChordArea:
case Tonicization:
return new CADrawableFunctionMarkSupport(_drawableFunctionMarkSupportType, _function1, (newContext) ? newContext : _drawableContext, _xPos, _yPos, _function2);
case Ellipse:
return new CADrawableFunctionMarkSupport(Ellipse, _function1, (newContext) ? newContext : _drawableContext, qRound(_xPos - _function1->width() / 2.0), _yPos, _function2);
case Rectangle:
return new CADrawableFunctionMarkSupport(Rectangle, _function1, (newContext) ? newContext : _drawableContext, _xPos + 3, _yPos + 3, _function2);
case Alterations:
return new CADrawableFunctionMarkSupport(Alterations, static_cast<CAFunctionMark*>(_musElement), (newContext) ? newContext : _drawableContext, _xPos, _yPos);
}
qWarning() << "clone: unknown drawableFunctionMarkSupportType " << _drawableFunctionMarkSupportType;
return nullptr;
}
| 21,084
|
C++
|
.cpp
| 528
| 30.450758
| 244
| 0.558535
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,336
|
drawablebarline.cpp
|
canorusmusic_canorus/src/layout/drawablebarline.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QPainter>
#include <QPen>
#include "layout/drawablebarline.h"
#include "layout/drawablestaff.h"
#include "score/barline.h"
const double CADrawableBarline::SPACE_BETWEEN_BARLINES = 3;
const double CADrawableBarline::BARLINE_WIDTH = 1.5;
const double CADrawableBarline::DOTTED_BARLINE_WIDTH = 2;
const double CADrawableBarline::BOLD_BARLINE_WIDTH = 4;
const double CADrawableBarline::REPEAT_DOTS_WIDTH = 3;
CADrawableBarline::CADrawableBarline(CABarline* m, CADrawableStaff* staff, double x, double y)
: CADrawableMusElement(m, staff, x, y)
{
setDrawableMusElementType(CADrawableMusElement::DrawableBarline);
switch (m->barlineType()) {
case CABarline::Single:
setWidth(BARLINE_WIDTH);
break;
case CABarline::Double:
setWidth(3 * BARLINE_WIDTH + SPACE_BETWEEN_BARLINES);
break;
case CABarline::End:
setWidth(BARLINE_WIDTH + SPACE_BETWEEN_BARLINES + BOLD_BARLINE_WIDTH);
break;
case CABarline::RepeatOpen:
setWidth(BOLD_BARLINE_WIDTH + 2 * SPACE_BETWEEN_BARLINES + BARLINE_WIDTH + REPEAT_DOTS_WIDTH);
break;
case CABarline::RepeatClose:
setWidth(REPEAT_DOTS_WIDTH + 2 * SPACE_BETWEEN_BARLINES + BARLINE_WIDTH + BOLD_BARLINE_WIDTH);
break;
case CABarline::RepeatCloseOpen:
setWidth(2 * REPEAT_DOTS_WIDTH + 3 * SPACE_BETWEEN_BARLINES + BOLD_BARLINE_WIDTH + 2 * BARLINE_WIDTH);
break;
case CABarline::Dotted:
setWidth(DOTTED_BARLINE_WIDTH);
break;
case CABarline::Undefined:
break;
}
setHeight(staff->height());
setNeededSpaceWidth(4);
}
CADrawableBarline::~CADrawableBarline()
{
}
void CADrawableBarline::draw(QPainter* p, CADrawSettings s)
{
QPen pen(s.color);
pen.setCapStyle(Qt::FlatCap);
QBrush brush(s.color, Qt::SolidPattern);
p->setBrush(brush);
switch (barline()->barlineType()) {
case CABarline::Single:
// draw single barline
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x + pen.width(), s.y,
s.x + pen.width(), qRound(s.y + height() * s.z));
break;
case CABarline::Double:
// draw double barline
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x + pen.width(), s.y,
s.x + pen.width(), qRound(s.y + height() * s.z));
p->drawLine(qRound(s.x + BARLINE_WIDTH * s.z + SPACE_BETWEEN_BARLINES * s.z) + 2 * pen.width(), s.y,
qRound(s.x + BARLINE_WIDTH * s.z + SPACE_BETWEEN_BARLINES * s.z) + 2 * pen.width(), qRound(s.y + height() * s.z));
break;
case CABarline::End:
// draw thin barline
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x + pen.width(), s.y,
s.x + pen.width(), qRound(s.y + height() * s.z));
// draw bold barline
pen.setWidth(qRound(BOLD_BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(qRound(s.x + BARLINE_WIDTH * s.z + SPACE_BETWEEN_BARLINES * s.z + 0.5 * BOLD_BARLINE_WIDTH * s.z), s.y,
qRound(s.x + BARLINE_WIDTH * s.z + SPACE_BETWEEN_BARLINES * s.z + 0.5 * BOLD_BARLINE_WIDTH * s.z), qRound(s.y + height() * s.z));
break;
case CABarline::RepeatOpen:
pen.setWidth(qRound(BOLD_BARLINE_WIDTH * s.z));
p->setPen(pen);
// draw bold barline
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BOLD_BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES + BARLINE_WIDTH / 2) * s.z);
// draw single barline
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES) * s.z);
// draw upper dot
p->drawEllipse(s.x,
qRound(s.y + 4 * SPACE_BETWEEN_BARLINES * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
// draw lower dot
p->drawEllipse(s.x,
qRound(s.y + (height() - REPEAT_DOTS_WIDTH - 4 * SPACE_BETWEEN_BARLINES) * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
break;
case CABarline::RepeatClose:
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
// draw upper dot
p->drawEllipse(s.x,
qRound(s.y + 4 * SPACE_BETWEEN_BARLINES * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
// draw lower dot
p->drawEllipse(s.x,
qRound(s.y + (height() - REPEAT_DOTS_WIDTH - 4 * SPACE_BETWEEN_BARLINES) * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
s.x += qRound((REPEAT_DOTS_WIDTH + SPACE_BETWEEN_BARLINES + BARLINE_WIDTH / 2) * s.z);
// draw single barline
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES + BOLD_BARLINE_WIDTH / 2) * s.z);
// draw bold barline
pen.setWidth(qRound(BOLD_BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
break;
case CABarline::RepeatCloseOpen:
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
// draw upper dot
p->drawEllipse(s.x,
qRound(s.y + 4 * SPACE_BETWEEN_BARLINES * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
// draw lower dot
p->drawEllipse(s.x,
qRound(s.y + (height() - REPEAT_DOTS_WIDTH - 4 * SPACE_BETWEEN_BARLINES) * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
s.x += qRound((REPEAT_DOTS_WIDTH + SPACE_BETWEEN_BARLINES + BARLINE_WIDTH / 2) * s.z);
// draw single barline
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES + BOLD_BARLINE_WIDTH / 2) * s.z);
// draw bold barline
pen.setWidth(qRound(BOLD_BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BOLD_BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES + BARLINE_WIDTH / 2) * s.z);
pen.setWidth(qRound(BARLINE_WIDTH * s.z));
p->setPen(pen);
// draw single barline
p->drawLine(s.x, s.y,
s.x, qRound(s.y + height() * s.z));
s.x += qRound((BARLINE_WIDTH / 2 + SPACE_BETWEEN_BARLINES) * s.z);
// draw upper dot
p->drawEllipse(s.x,
qRound(s.y + 4 * SPACE_BETWEEN_BARLINES * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
// draw lower dot
p->drawEllipse(s.x,
qRound(s.y + (height() - REPEAT_DOTS_WIDTH - 4 * SPACE_BETWEEN_BARLINES) * s.z),
qRound(REPEAT_DOTS_WIDTH * s.z), qRound(REPEAT_DOTS_WIDTH * s.z));
break;
case CABarline::Dotted:
pen.setStyle(Qt::DotLine);
pen.setCapStyle(Qt::RoundCap);
pen.setWidth(qRound(DOTTED_BARLINE_WIDTH * s.z));
p->setPen(pen);
p->drawLine(s.x + pen.width(), s.y,
s.x + pen.width(), qRound(s.y + height() * s.z));
break;
case CABarline::Undefined:
break;
}
p->setBrush(QBrush(s.color, Qt::NoBrush)); // reset the painter's brush
}
CADrawableBarline* CADrawableBarline::clone(CADrawableContext* newContext)
{
return new CADrawableBarline(static_cast<CABarline*>(_musElement),
static_cast<CADrawableStaff*>((newContext) ? newContext : _drawableContext), _xPos, _yPos);
}
| 8,035
|
C++
|
.cpp
| 184
| 35.766304
| 141
| 0.600306
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,337
|
articulation.cpp
|
canorusmusic_canorus/src/score/articulation.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/articulation.h"
/*!
\class CAArticulation
\brief Note articulation marks
Every note can have one or more articulation marks.
Other music elements can't have articulation marks.
If the note is part of the chord, all notes in the chord should have
the same articulation.
*/
CAArticulation::CAArticulation(CAArticulationType t, CANote* n)
: CAMark(CAMark::Articulation, n)
{
setArticulationType(t);
}
CAArticulation::~CAArticulation()
{
}
CAArticulation* CAArticulation::clone(CAMusElement* elt)
{
return new CAArticulation(articulationType(), (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr);
}
int CAArticulation::compare(CAMusElement*)
{
return 0;
}
const QString CAArticulation::articulationTypeToString(CAArticulationType t)
{
switch (t) {
case Accent:
return "Accent";
case Marcato:
return "Marcato";
case Staccatissimo:
return "Staccatissimo";
case Espressivo:
return "Espressivo";
case Staccato:
return "Staccato";
case Tenuto:
return "Tenuto";
case Portato:
return "Portato";
case Breath:
return "Breath";
case UpBow:
return "UpBow";
case DownBow:
return "DownBow";
case Flageolet:
return "Flageolet";
case Open:
return "Open";
case Stopped:
return "Stopped";
case Turn:
return "Turn";
case ReverseTurn:
return "ReverseTurn";
case Trill:
return "Trill";
case Prall:
return "Prall";
case Mordent:
return "Mordent";
case PrallPrall:
return "PrallPrall";
case PrallMordent:
return "PrallMordent";
case UpPrall:
return "UpPrall";
case DownPrall:
return "DownPrall";
case UpMordent:
return "UpMordent";
case DownMordent:
return "DownMordent";
case PrallDown:
return "PrallDown";
case PrallUp:
return "PrallUp";
case LinePrall:
return "LinePrall";
default:
return "Undefined";
}
}
CAArticulation::CAArticulationType CAArticulation::articulationTypeFromString(const QString s)
{
if (s == "Accent")
return Accent;
else if (s == "Marcato")
return Marcato;
else if (s == "Staccatissimo")
return Staccatissimo;
else if (s == "Espressivo")
return Espressivo;
else if (s == "Staccato")
return Staccato;
else if (s == "Tenuto")
return Tenuto;
else if (s == "Portato")
return Portato;
else if (s == "Breath")
return Breath;
else if (s == "UpBow")
return UpBow;
else if (s == "DownBow")
return DownBow;
else if (s == "Flageolet")
return Flageolet;
else if (s == "Open")
return Open;
else if (s == "Stopped")
return Stopped;
else if (s == "Turn")
return Turn;
else if (s == "ReverseTurn")
return ReverseTurn;
else if (s == "Trill")
return Trill;
else if (s == "Prall")
return Prall;
else if (s == "Mordent")
return Mordent;
else if (s == "PrallPrall")
return PrallPrall;
else if (s == "PrallMordent")
return PrallMordent;
else if (s == "UpPrall")
return UpPrall;
else if (s == "DownPrall")
return DownPrall;
else if (s == "UpMordent")
return UpMordent;
else if (s == "DownMordent")
return DownMordent;
else if (s == "PrallDown")
return PrallDown;
else if (s == "PrallUp")
return PrallUp;
else if (s == "LinePrall")
return LinePrall;
else
return Undefined;
}
| 3,933
|
C++
|
.cpp
| 150
| 20.426667
| 135
| 0.628314
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,338
|
muselement.cpp
|
canorusmusic_canorus/src/score/muselement.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/muselement.h"
#include "score/articulation.h"
#include "score/context.h"
#include "score/mark.h"
#include "score/notecheckererror.h"
#include "score/playable.h"
#include "score/staff.h"
/*!
\class CAMusElement
\brief An abstract class which represents every music element in the score.
This class is a base class for every music element in the score.
Music elements can be of various types, note, rest, barline, clef, lyrics syllable,
function mark, figured bass mark etc.
See CAMusElementType for details.
Every music element belongs to a so called parent area in the score called context.
See CAContext for details.
Since Canorus tends to be built in Model-View-Controller style, every music element
has one or more of its drawable instances. These classes are named CADrawableClassName,
where ClassName is type of the music element. eg. CADrawableClef, CADrawableBarline etc.
\sa CAMusElementType, CAContext, CADrawableMusElement
*/
/*!
Constructs a music element with parent context (staff, lyrics, functionmarks) \a context,
start time \a time and length \a length.
*/
CAMusElement::CAMusElement(CAContext* context, int time, int length)
{
_context = context;
_timeStart = time;
_timeLength = length;
_musElementType = CAMusElement::Undefined;
_visible = true;
_color = QColor(); // invalid color by default
}
/*!
Destroys a music element.
This removes the music element from the parent context as well!
*/
CAMusElement::~CAMusElement()
{
while (!_markList.isEmpty()) {
if (!_markList.first()->isCommon() || musElementType() != CAMusElement::Note) {
delete _markList.takeFirst();
} else {
_markList.takeFirst();
}
}
// needed when removing a shared-voice music element - when an instance is removed, it should be removed from all the voices as well! -Matevz
if (context() && !isPlayable())
context()->remove(this);
while (_noteCheckerErrorList.size()) {
delete _noteCheckerErrorList.front(); // also removes instances from _noteCheckerErrorList and CASheet->noteCheckerErrorList
}
}
/*!
Returns true, if the current element is playable; otherwise false.
Playable elements are music elements with _timeLength variable greater
than 0 (notes, rests). They inherit CAPlayable.
\sa _timeLength, CAPlayable
*/
bool CAMusElement::isPlayable()
{
return (musElementType() == Note || musElementType() == Rest); //dynamic_cast<CAPlayable*>(this);
}
/*!
Converts a music element \a type to QString.
\sa CAMusElementType, musElementTypeFromString()
*/
const QString CAMusElement::musElementTypeToString(CAMusElement::CAMusElementType type)
{
switch (type) {
case (Undefined):
return "undefined";
case (Note):
return "note";
case (Rest):
return "rest";
case (Barline):
return "barline";
case (Clef):
return "clef";
case (TimeSignature):
return "time-signature";
case (KeySignature):
return "key-signature";
case (Slur):
return "slur";
case (FunctionMark):
return "function-mark";
case (Syllable):
return "syllable";
case (MidiNote):
return "midi-note";
case (Tuplet):
return "tuplet";
case (Mark):
return "mark";
case (FiguredBassMark):
return "figured-bass-mark";
case (ChordName):
return "chord-name";
}
// Do not add a default case as else newly added elements might be forgotten here!
return QString();
}
/*!
Converts QString \a type to music element type.
\sa CAMusElementType, musElementTypeToString()
*/
CAMusElement::CAMusElementType CAMusElement::musElementTypeFromString(const QString type)
{
if (type == "undefined")
return Undefined;
if (type == "note")
return Note;
if (type == "rest")
return Rest;
if (type == "barline")
return Barline;
if (type == "clef")
return Clef;
if (type == "time-signature")
return TimeSignature;
if (type == "key-signature")
return KeySignature;
if (type == "slur")
return Slur;
if (type == "function-mark")
return FunctionMark;
if (type == "syllable")
return Syllable;
if (type == "mark")
return Mark;
if (type == "figured-bass-mark")
return FiguredBassMark;
if (type == "tuplet")
return Tuplet;
if (type == "midi-note")
return MidiNote;
if (type == "chord-name")
return ChordName;
return Undefined;
}
/*!
Adds a \a mark to the mark list in correct order.
*/
void CAMusElement::addMark(CAMark* mark)
{
if (!mark || _markList.contains(mark))
return;
int l;
for (l = 0; l < markList().size() && mark->markType() > markList()[l]->markType(); l++)
; // Marks must be sorted by their mark type.
if (mark->markType() == CAMark::Articulation) {
for (; l < markList().size() && markList()[l]->markType() == CAMark::Articulation && static_cast<CAArticulation*>(mark)->articulationType() > static_cast<CAArticulation*>(markList()[l])->articulationType(); l++)
; // Articulation marks must be sorted by their articulation mark type.
}
_markList.insert(l, mark);
}
/*!
Adds a list of marks to the mark list in correct order.
*/
void CAMusElement::addMarks(QList<CAMark*> marks)
{
for (int i = 0; i < marks.size(); i++)
addMark(marks[i]);
}
/*!
\enum CAMusElement::CAMusElementType
Includes different types for describing the CAMusElement:
- Note - A music element which represents CANote.
- NoteBracket - A music element which represents CANoteBracket (the bracket which connects the stems).
- Chord - A virtual music element which represents CAChord.
- Rest - A music element which represents CARest.
- BarLine - A music elemnet which represents CABarLine.
- Clef - A music element which represents CAClef.
- TimeSignature - A music element which represents CATimeSignature.
- KeySignature - A music element which represents CAKeySignature.
- Slur - A music element which represents CASlur.
- Tie - A music element which represents CATie.
- PhrazingSlur - A music element which represents CAPhrazingSlur.
- ExpressionMark - A music element which represents any technical text marks about how the score should be played - CAExpressionMark (eg. Legato)
- VolumeSign - A music element which represents any volue sign (forte, piano etc.).
- Text - A music element which represents any text notes and authors additions to the score. (eg. These 3 measures still need to be fixed)
- ChordName - A music elements which represents a chord name CAChordName (e.g. Cm, d#:dim)
\sa musElementType()
*/
/*!
\fn CAMusElement::musElementType()
Returns the music element type.
\sa CAMusElementType
*/
/*!
\fn CAMusElement::context()
Returns pointer to the CAContext which the music element belongs to.
\sa CAContext
*/
/*!
\fn CAMusElement::timeStart()
Returns the time in the score when the music element appears in time.
The returned time is in absolute time units.
\sa _timeStart, setTimeStart()
*/
/*!
\fn CAMusElement::setTimeStart(int time)
Sets the time in the score when the music element appears for this music element to \a time.
The given time is in absolute time units.
\sa _timeStart, timeStart()
*/
/*!
\fn CAMusElement::timeLength()
Returns the time how long the music element lasts in the score.
The returned time is in absolute time units.
\sa _timeLength, setTimeLength(), timeEnd()
*/
/*!
\fn CAMusElement::setTimeLength(int length)
Sets the length in the score for this music element to \a time.
The given time is in absolute time units.
\sa _timeLength, timeLength()
*/
/*!
\fn CAMusElement::timeEnd()
Returns the time when the music element stops playing.
This is always the sum of _timeStart + _timeLength.
The returned time is in absolute time units.
\sa _timeStart, _timeLength
*/
/*!
\fn CAMusElement::name()
Returns the name of the music element.
*/
/*!
\fn CAMusElement::setName(QString name)
Sets the name of the music element to \a name.
\sa _name, name()
*/
/*!
\fn CAMusElement::clone()
Clones a music element with exact properties including the context.
*/
/*!
\fn CAMusElement::compare(CAMusElement *elt)
Compares the music element with the given \a elt and returns number of
differences in their properties.
Returns 0, if the music elements are exact; -1 if the music element type differs;
otherwise number greater than 0.
This method is usually used when opening a score document where music elements are
written in various voices (eg. barlines), but are eventually merged and written only
once per staff.
*/
/*!
\var CAMusElement::_musElementType
Stores the type of the music element.
\sa CAMusElementType
*/
/*!
\var CAMusElement::_context
Pointer to the context which the music element belongs to.
\sa context()
*/
/*!
\var CAMusElement::_timeStart
Where does the music element starts in time.
Time is stored in absolute time units and is not affected by different tempos or
other expressions.
\sa timeStart(), setTimeStart()
*/
/*!
\var CAMusElement::_timeLength
How long does this music element lasts.
Time is stored in absolute time units and is not affected by different tempos or
other expressions.
Non-playable elements (barlines, clefs, key signatures etc.) have this time always 0.
Playable elements (notes, rests) have this time always greater than 0.
\sa timeLength(), setTimeLength(), CAPlayable::CAPlayableLength
*/
/*!
\var CAMusElement::_name
Specific name of the music element in QString.
Names are optional and are not necessary unique.
\sa name(), setName()
*/
| 10,006
|
C++
|
.cpp
| 288
| 31.125
| 219
| 0.71671
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,339
|
lyricscontext.cpp
|
canorusmusic_canorus/src/score/lyricscontext.cpp
|
/*!
Copyright (c) 2007-2023, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/lyricscontext.h"
#include "score/syllable.h"
#include "score/voice.h"
/*!
\class CALyricsContext
\brief One stanza line of lyrics
This class represents a single stanza of the lyrics. It consists of various syllables (text under every note)
sorted by their timeStarts.
Every LyricsContext has its associated voice. This is the voice which the syllables are assigned to (one syllable per chord).
Assocciated voice is a common LilyPond syntax \\lyricsto.
If the user wants to create multiple stanzas, it should create multiple lyrics contexts - one for each stanza.
\param _stanzaNumber stores the stanza number. If _stanzaNumber equals 0, no number is printed (default).
\sa _syllableMap, CASyllable
*/
CALyricsContext::CALyricsContext(const QString name, int stanzaNumber, CAVoice* v)
: CAContext(name, (v && v->staff()) ? v->staff()->sheet() : nullptr)
{
setContextType(LyricsContext);
_associatedVoice = nullptr;
setAssociatedVoice(v); // also reposits syllables
setStanzaNumber(stanzaNumber);
}
CALyricsContext::CALyricsContext(const QString name, int stanzaNumber, CASheet* s)
: CAContext(name, s)
{
setContextType(LyricsContext);
_associatedVoice = nullptr;
setAssociatedVoice(nullptr); // also reposits syllables
setStanzaNumber(stanzaNumber);
}
CALyricsContext::~CALyricsContext()
{
if (associatedVoice())
associatedVoice()->removeLyricsContext(this);
clear();
}
void CALyricsContext::clear()
{
while (!_syllableList.isEmpty())
delete _syllableList.takeFirst();
}
CALyricsContext* CALyricsContext::clone(CASheet* s)
{
CALyricsContext* newLc = new CALyricsContext(name(), stanzaNumber(), s);
newLc->cloneLyricsContextProperties(this);
for (int i = 0; i < _syllableList.size(); i++) {
CASyllable* newSyllable = static_cast<CASyllable*>(_syllableList[i]->clone(newLc));
newLc->addSyllable(newSyllable);
}
return newLc;
}
/*!
Sets the properties of the given lyrics context to this lyrics context.
*/
void CALyricsContext::cloneLyricsContextProperties(CALyricsContext* lc)
{
setName(lc->name());
setStanzaNumber(lc->stanzaNumber());
setSheet(lc->sheet());
setAssociatedVoice(lc->associatedVoice());
}
CAMusElement* CALyricsContext::next(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Syllable)
return nullptr;
int i = _syllableList.indexOf(static_cast<CASyllable*>(elt));
if (i != -1 && ++i < _syllableList.size())
return _syllableList[i];
else
return nullptr;
}
CAMusElement* CALyricsContext::previous(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Syllable)
return nullptr;
int i = _syllableList.indexOf(static_cast<CASyllable*>(elt));
if (i != -1 && --i > -1)
return _syllableList[i];
else
return nullptr;
}
/*!
Removes the given syllable from the list.
*/
bool CALyricsContext::remove(CAMusElement* elt)
{
if (!elt || elt->musElementType() != CAMusElement::Syllable)
return false;
bool success = false;
success = _syllableList.removeAll(static_cast<CASyllable*>(elt));
if (success)
delete elt;
return success;
}
CAMusElement *CALyricsContext::insertEmptyElement(int timeStart)
{
int i;
for (i = 0; i < _syllableList.size() && _syllableList[i]->timeStart() < timeStart; i++)
;
CASyllable *newSyl = new CASyllable("", ((i > 0) ? (_syllableList[i - 1]->hyphenStart()) : (false)), ((i > 0) ? (_syllableList[i - 1]->melismaStart()) : (false)), this, timeStart, 1);
_syllableList.insert(i, newSyl);
for (i++; i < _syllableList.size(); i++)
_syllableList[i]->setTimeStart(_syllableList[i]->timeStart() + 1);
return newSyl;
}
/*!
Keeps the content and order of the syllables, but changes startTimes and lengths according to the notes in associatedVoice.
This function is usually called when associatedVoice is changed or the whole lyricsContext is initialized for the first time.
If the notes and syllables aren't synchronized (too little syllables for notes) it adds empty syllables.
*/
void CALyricsContext::repositionElements()
{
if (associatedVoice()) {
QList<CANote*> noteList = associatedVoice()->getNoteList();
// synchronize syllable times with notes
int i, j;
for (i = 0, j = 0; i < noteList.size() && j < _syllableList.size(); i++, j++) {
if (!noteList[i]->isFirstInChord()) { // skip until the first note in the chord
j--;
continue;
}
_syllableList[j]->setTimeStart(noteList[i]->timeStart());
_syllableList[j]->setTimeLength(noteList[i]->timeLength());
}
// CASE 1: more syllables than chords
int lastNonEmpty = j-1; // index of the last non-empty syllable
for (; j < _syllableList.size(); j++) {
if (!_syllableList[j]->text().isEmpty()) {
lastNonEmpty = j;
}
// add some common dummy time so that we preserve the order and the leftover syllables are vertically aligned
if (j>0) {
_syllableList[j]->setTimeStart(_syllableList[j - 1]->timeStart() + _syllableList[j - 1]->timeLength());
_syllableList[j]->setTimeLength(256);
}
}
// remove empty "leftover" syllables from the end so that lastNonEmpty will be last
while (_syllableList.size()-1 != lastNonEmpty) {
delete _syllableList.takeLast();
}
// CASE 2: more chords than syllables
for (; i < noteList.size(); i++) { // add empty syllables at the end, if missing
if (!noteList[i]->isFirstInChord()) { // skip until the first note in the chord
continue;
}
insertEmptyElement(noteList[i]->timeStart());
}
}
}
/*!
Removes the syllable at the given \a timeStart and updates the timeStarts for syllables after it.
This function is usually called when removing the note.
Returns True if the syllable was found and removed; False otherwise.
*/
CASyllable* CALyricsContext::removeSyllableAtTimeStart(int timeStart)
{
int i;
for (i = 0; i < _syllableList.size() && _syllableList[i]->timeStart() != timeStart; i++)
;
if (i < _syllableList.size()) {
CASyllable* syllable = _syllableList[i];
// update times
for (int j = i + 1; j < _syllableList.size(); j++)
_syllableList[j]->setTimeStart(_syllableList[j]->timeStart() - syllable->timeLength());
delete _syllableList.takeAt(i);
return syllable;
} else {
return nullptr;
}
}
/*!
Adds a syllable to the context. The syllable at that location is replaced (default) by the new one, if
\a replace is True.
Time starts after the inserted syllable are increased for the length of the inserted syllable.
Syllables are always sorted by their startTimes.
\sa _syllableList
*/
bool CALyricsContext::addSyllable(CASyllable* syllable, bool replace)
{
int i;
for (i = 0; i < _syllableList.size() && _syllableList[i]->timeStart() < syllable->timeStart(); i++)
;
//int s = _syllableList.size();
if (i < _syllableList.size() && replace) {
delete _syllableList.takeAt(i);
}
_syllableList.insert(i, syllable);
for (i++; i < _syllableList.size(); i++)
_syllableList[i]->setTimeStart(_syllableList[i]->timeStart() + syllable->timeLength());
return true;
}
/*!
Finds the syllable with exactly the given \a timeStart or Null, if such a
syllables doesn't exist.
*/
CASyllable* CALyricsContext::syllableAtTimeStart(int timeStart)
{
int i;
for (i = 0; i < _syllableList.size() && _syllableList[i]->timeStart() != timeStart; i++)
;
if (i < _syllableList.size())
return _syllableList[i];
else
return nullptr;
}
/*!
Sets a new associated voice and repositiones the syllables.
*/
void CALyricsContext::setAssociatedVoice(CAVoice* v)
{
if (_associatedVoice)
_associatedVoice->removeLyricsContext(this);
if (v)
v->addLyricsContext(this);
_associatedVoice = v;
repositionElements();
}
| 8,476
|
C++
|
.cpp
| 222
| 32.855856
| 187
| 0.672634
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,340
|
dynamic.cpp
|
canorusmusic_canorus/src/score/dynamic.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/dynamic.h"
#include "score/note.h"
/*!
\class CADynamic
\brief Absolute dynamic marks
Absolute dynamic marks eg. piano, pp, sfz, forte.
*/
CADynamic::CADynamic(QString text, int volume, CANote* note)
: CAMark(CAMark::Dynamic, note)
{
setText(text);
setVolume(volume);
}
CADynamic::~CADynamic()
{
}
CADynamic* CADynamic::clone(CAMusElement* elt)
{
return new CADynamic(text(), volume(), (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr);
}
int CADynamic::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::Dynamic)
return -1;
if (static_cast<CADynamic*>(elt)->text() != text())
return 1;
return 0;
}
const QString CADynamic::dynamicTextToString(CADynamicText t)
{
switch (t) {
case ppppp:
return "ppppp";
case pppp:
return "pppp";
case ppp:
return "ppp";
case pp:
return "pp";
case p:
return "p";
case fffff:
return "fffff";
case ffff:
return "ffff";
case fff:
return "fff";
case ff:
return "ff";
case f:
return "f";
case fp:
return "fp";
case mf:
return "mf";
case mp:
return "mp";
case rfz:
return "rfz";
case sff:
return "sff";
case sf:
return "sf";
case sfz:
return "sfz";
case spp:
return "spp";
case sp:
return "sp";
case Custom:
return "";
}
return "";
}
CADynamic::CADynamicText CADynamic::dynamicTextFromString(const QString t)
{
if (t == "ppppp")
return ppppp;
if (t == "pppp")
return pppp;
if (t == "ppp")
return ppp;
if (t == "pp")
return pp;
if (t == "p")
return p;
if (t == "fffff")
return fffff;
if (t == "ffff")
return ffff;
if (t == "fff")
return fff;
if (t == "ff")
return ff;
if (t == "f")
return f;
if (t == "fp")
return fp;
if (t == "mf")
return mf;
if (t == "mp")
return mp;
if (t == "rfz")
return rfz;
if (t == "sff")
return sff;
if (t == "sf")
return sf;
if (t == "sfz")
return sfz;
if (t == "spp")
return spp;
if (t == "sp")
return sp;
return Custom;
}
| 2,693
|
C++
|
.cpp
| 123
| 16.349593
| 128
| 0.555729
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,341
|
sheet.cpp
|
canorusmusic_canorus/src/score/sheet.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QHash> // used for mapping when cloning the sheet to a new sheet
#include <QObject> // QObject::tr
#include "score/context.h"
#include "score/document.h"
#include "score/lyricscontext.h"
#include "score/notecheckererror.h"
#include "score/sheet.h"
#include "score/staff.h"
#include "score/tempo.h"
#include "score/voice.h"
/*!
\class CASheet
\brief Represents a single sheet of paper in the document
CASheet represents a sheet of paper for the composer. The idea was taken out from
spreadsheet applications. Each sheet is usually in its own tab.
CASheet parent is CADocument and CASheet includes various contexts CAContext, let it
be staffs, lyrics, function marks etc.
\sa CADocument, CAContext
*/
/*!
Creats a new sheet named \a name with parent document \a doc.
*/
CASheet::CASheet(const QString name, CADocument* doc)
{
_name = name;
_document = doc;
}
CASheet::~CASheet()
{
}
/*!
Clones the current sheet with all its content.
If a new parent document \a doc is given, it also sets the document.
*/
CASheet* CASheet::clone(CADocument* doc)
{
CASheet* newSheet = new CASheet(name(), doc);
QHash<CAContext*, CAContext*> contextMap; // map between oldContexts<->cloned contexts
QHash<CAVoice*, CAVoice*> voiceMap; // map between oldVoices<->cloned voices
// create clones of contexts
for (int i = 0; i < contextList().size(); i++) {
CAContext* newContext = contextList()[i]->clone(newSheet);
if (newContext->contextType() == CAContext::Staff) {
for (int j = 0; j < static_cast<CAStaff*>(contextList()[i])->voiceList().size(); j++) {
voiceMap[static_cast<CAStaff*>(contextList()[i])->voiceList()[j]] = static_cast<CAStaff*>(newContext)->voiceList()[j];
}
}
contextMap[contextList()[i]] = newContext;
newSheet->addContext(newContext);
}
// assign contexts between each other (like associated voice of lyrics context etc.)
for (int i = 0; i < contextList().size(); i++) {
if (newSheet->contextList()[i]->contextType() == CAContext::LyricsContext) {
CAVoice* voice = voiceMap[static_cast<CALyricsContext*>(newSheet->contextList()[i])->associatedVoice()];
static_cast<CALyricsContext*>(newSheet->contextList()[i])->setAssociatedVoice(voice);
if (voice)
voice->removeLyricsContext(static_cast<CALyricsContext*>(contextList()[i]));
}
}
return newSheet;
}
/*!
Appends a new staff to the sheet with one empty voice.
*/
CAStaff* CASheet::addStaff()
{
CAStaff* s = new CAStaff(QObject::tr("Staff%1").arg(staffList().size() + 1), this);
s->addVoice();
_contextList.append(s);
return s;
}
void CASheet::clear()
{
for (int i = 0; i < _contextList.size(); i++) {
_contextList[i]->clear();
delete _contextList[i];
}
_contextList.clear();
}
/*!
Returns the first context with the given \a name.
*/
CAContext* CASheet::findContext(const QString name)
{
for (int i = 0; i < _contextList.size(); i++)
if (_contextList[i]->name() == name)
return _contextList[i];
return nullptr;
}
/*!
* Finds unique context name given the mask and starting with 1.
*
* This is used when inserting a new context and we want to assign it a unique name.
*
* \param mask Context name with %1 placeholder for unique number
* \return Unique context name
*/
QString CASheet::findUniqueContextName(const QString mask)
{
int i = 1;
while (findContext(mask.arg(i))) {
i++;
}
return mask.arg(i);
}
/*!
Returns a list of notes and rests (chord) for all the voices in all the staffs
in the given time slice \a time.
This is useful for determination of the harmony at certain point in time.
\sa CAStaff:getChord(), CAVoice::getChord()
*/
QList<CAPlayable*> CASheet::getChord(int time)
{
QList<CAPlayable*> chordList;
QList<CAStaff*> staffs = staffList();
for (int i = staffs.size() - 1; i >= 0; i--) {
chordList << staffs[i]->getChord(time);
}
return chordList;
}
/*!
Returns the Tempo element active at the given time.
*/
CATempo* CASheet::getTempo(int time)
{
CATempo* tempo = nullptr;
for (int i = 0; i < staffList().size(); i++) {
CATempo* t = staffList()[i]->getTempo(time);
if (t && (!tempo || t->timeStart() > tempo->timeStart())) {
tempo = t;
}
}
return tempo;
}
/*!
Returns the list of all the voices in the sheets staffs.
*/
QList<CAVoice*> CASheet::voiceList()
{
QList<CAVoice*> list;
QList<CAStaff*> staffs = staffList();
for (int i = 0; i < staffs.size(); i++)
list << staffs[i]->voiceList();
return list;
}
QList<CAStaff*> CASheet::staffList()
{
QList<CAStaff*> staffList;
for (int i = 0; i < _contextList.size(); i++) {
if (_contextList[i]->contextType() == CAContext::Staff) {
staffList << static_cast<CAStaff*>(_contextList[i]);
}
}
return staffList;
}
/*!
Inserts the given context \a c after the context \a after.
*/
void CASheet::insertContextAfter(CAContext* after, CAContext* c)
{
int idx = _contextList.indexOf(after);
if (idx == -1) {
_contextList.prepend(c);
} else {
_contextList.insert(idx + 1, c);
}
}
/*!
* Removes any note checker errors in the current sheet.
* This function is usually called when changing the score and before re-running
* the note checker.
*/
void CASheet::clearNoteCheckerErrors()
{
for (int i = 0; i < _noteCheckerErrorList.size(); i++) {
delete _noteCheckerErrorList[i]; // delete also remove an instance from _noteCheckerErrorList
i--;
}
}
| 5,939
|
C++
|
.cpp
| 184
| 28.184783
| 134
| 0.665326
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,342
|
document.cpp
|
canorusmusic_canorus/src/score/document.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/document.h"
#include "control/resourcectl.h"
#include "core/archive.h"
#include "score/context.h"
#include "score/resource.h"
#include "score/sheet.h"
#include "score/staff.h"
/*!
\class CADocument
\brief Class which represents the current document.
CADocument is a top-most class in score hierarchy and represents the
document in the current main window.
Document consists of multiple sheets.
\sa CASheet
*/
/*!
Creates an empty document.
\sa addSheet()
*/
CADocument::CADocument()
{
setDateCreated(QDateTime::currentDateTime());
setDateLastModified(QDateTime::currentDateTime());
setTimeEdited(0);
setArchive(new CAArchive());
setModified(false);
}
/*!
Clones this document and all its sheets and returns a pointer to its clone.
*/
CADocument* CADocument::clone()
{
CADocument* newDocument = new CADocument();
// set properties
newDocument->setTitle(title());
newDocument->setSubtitle(subtitle());
newDocument->setComposer(composer());
newDocument->setArranger(arranger());
newDocument->setPoet(poet());
newDocument->setCopyright(copyright());
newDocument->setDateCreated(dateCreated());
newDocument->setDateLastModified(dateLastModified());
newDocument->setTimeEdited(timeEdited());
newDocument->setComments(comments());
newDocument->setFileName(fileName());
for (int i = 0; i < sheetList().size(); i++) {
CASheet* newSheet = sheetList()[i]->clone(newDocument);
newDocument->addSheet(newSheet);
}
for (int i = 0; i < resourceList().size(); i++) {
newDocument->addResource(resourceList()[i]);
}
return newDocument;
}
/*!
Clears and destroys the document.
\sa clear()
*/
CADocument::~CADocument()
{
clear();
if (archive())
delete archive();
}
/*!
Clears the document of any sheets and destroys them.
*/
void CADocument::clear()
{
_title.clear();
_subtitle.clear();
_composer.clear();
_arranger.clear();
_poet.clear();
_copyright.clear();
_dateCreated = QDateTime::currentDateTime();
_dateLastModified = QDateTime::currentDateTime();
_timeEdited = 0;
_comments.clear();
for (int i = 0; i < _sheetList.size(); i++) {
_sheetList[i]->clear();
delete _sheetList[i];
}
_sheetList.clear();
while (_resourceList.size()) {
CAResourceCtl::deleteResource(_resourceList[0]);
}
}
/*!
Creates a new sheet with the given \a name and
adds it to the sheets list.
\sa addSheet(CASheet *sheet), sheet(), sheetAt(), _sheetList
*/
CASheet* CADocument::addSheetByName(const QString name)
{
CASheet* s = new CASheet(name, this);
_sheetList << s;
return s;
}
/*!
Adds and empty sheet to the document.
*/
CASheet* CADocument::addSheet()
{
CASheet* s = new CASheet(QObject::tr("Sheet%1").arg(sheetList().size() + 1), this);
addSheet(s);
return s;
}
/*!
Returns the first sheet with the given \a name.
*/
CASheet* CADocument::findSheet(const QString name)
{
for (int i = 0; i < _sheetList.size(); i++) {
if (_sheetList[i]->name() == name)
return _sheetList[i];
}
return nullptr;
}
| 3,403
|
C++
|
.cpp
| 124
| 23.887097
| 87
| 0.687558
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,343
|
functionmarkcontext.cpp
|
canorusmusic_canorus/src/score/functionmarkcontext.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/functionmarkcontext.h"
#include "score/functionmark.h"
#include "score/playable.h"
#include "score/sheet.h"
/*!
\class CAFunctionMarkContext
\brief Context for function marks
This class represents a context which holds various function marks.
As CAStaff is a parent context for CANote, CARest and other staff elements,
CAFunctionMarkContext is a parent context for CAFunctionMark.
\sa CAContext
*/
CAFunctionMarkContext::CAFunctionMarkContext(const QString name, CASheet* sheet)
: CAContext(name, sheet)
{
_contextType = CAContext::FunctionMarkContext;
repositionElements();
}
CAFunctionMarkContext::~CAFunctionMarkContext()
{
clear();
}
CAFunctionMarkContext* CAFunctionMarkContext::clone(CASheet* s)
{
CAFunctionMarkContext* newFmc = new CAFunctionMarkContext(name(), s);
for (int i = 0; i < _functionMarkList.size(); i++) {
CAFunctionMark* newFm = _functionMarkList[i]->clone(newFmc);
newFmc->addFunctionMark(newFm);
}
return newFmc;
}
void CAFunctionMarkContext::clear()
{
for (int i = 0; i < _functionMarkList.size(); i++)
delete _functionMarkList[i];
_functionMarkList.clear();
}
/*!
Adds an already created function mark to this context.
*/
void CAFunctionMarkContext::addFunctionMark(CAFunctionMark* function, bool replace)
{
int i;
for (i = _functionMarkList.size() - 1; i > 0 && _functionMarkList[i]->timeStart() > function->timeStart(); i--)
;
_functionMarkList.insert(i + 1, function);
if (replace && i < _functionMarkList.size() && i >= 0 && _functionMarkList[i]->isEmpty()) {
_functionMarkList.removeAt(i);
} else if (!replace) {
i++;
while (++i < _functionMarkList.size())
_functionMarkList[i]->setTimeStart(_functionMarkList[i]->timeStart() + function->timeLength());
}
}
CAMusElement* CAFunctionMarkContext::next(CAMusElement* elt)
{
int idx = _functionMarkList.indexOf(static_cast<CAFunctionMark*>(elt));
if (idx == -1)
return nullptr;
if (++idx >= _functionMarkList.size())
return nullptr;
else
return _functionMarkList[idx];
}
CAMusElement* CAFunctionMarkContext::previous(CAMusElement* elt)
{
int idx = _functionMarkList.indexOf(static_cast<CAFunctionMark*>(elt));
if (idx == -1)
return nullptr;
if (--idx < 0)
return nullptr;
else
return _functionMarkList[idx];
}
bool CAFunctionMarkContext::remove(CAMusElement* elt)
{
return _functionMarkList.removeAll(static_cast<CAFunctionMark*>(elt));
}
CAMusElement *CAFunctionMarkContext::insertEmptyElement(int timeStart) {
CAFunctionMark *newElt = new CAFunctionMark(CAFunctionMark::Undefined, false, CADiatonicKey("C"), this, timeStart, 1);
addFunctionMark(newElt, false);
return newElt;
}
/*!
It repositions the functions (sets timeStart and timeLength) one by one according to the chords
above the context.
If two functions contain the same timeStart, they are treated as modulation and will contain
the same timeStart after reposition is done as well!
*/
void CAFunctionMarkContext::repositionElements()
{
int ts, tl;
int curIdx; // contains current position in _functionMarkList
QList<CAPlayable*> chord;
for (ts = 0, curIdx = 0;
(sheet() && (chord = sheet()->getChord(ts)).size()) || curIdx < _functionMarkList.size(); ts += tl) {
tl = (chord.size() ? chord[0]->timeLength() : 256);
for (int i = 0; i < chord.size(); i++)
if (chord[i]->timeLength() < tl)
tl = chord[i]->timeLength();
if (curIdx == _functionMarkList.size()) { // add new empty functions, if chords still exist
insertEmptyElement(ts);
curIdx++;
}
// apply timeStart and timeLength to existing function marks
for (int startIdx = curIdx; curIdx == 0 || (curIdx < _functionMarkList.size() && _functionMarkList[curIdx]->timeStart() == _functionMarkList[startIdx]->timeStart()); curIdx++) {
_functionMarkList[curIdx]->setTimeLength(tl);
_functionMarkList[curIdx]->setTimeStart(ts);
}
}
}
/*!
Returns the function marks at the exact given \a timeStart.
This function is usually called to determine the number of possible modulations of the
same chord at the given time.
*/
QList<CAFunctionMark*> CAFunctionMarkContext::functionMarkAt(int timeStart)
{
int i;
QList<CAFunctionMark*> ret;
// seek to the given time
for (i = 0; i < _functionMarkList.size() && _functionMarkList[i]->timeStart() < timeStart; i++)
;
for (; i < _functionMarkList.size() && _functionMarkList[i]->timeStart() == timeStart; i++) {
ret << _functionMarkList[i];
}
return ret;
}
/*!
\var CAFunctionMarkContext::_functionMarkList
List of all the function marks sorted by timeStart
*/
| 5,108
|
C++
|
.cpp
| 137
| 32.678832
| 185
| 0.694191
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,344
|
chordnamecontext.cpp
|
canorusmusic_canorus/src/score/chordnamecontext.cpp
|
/*!
Copyright (c) 2019, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QDebug>
#include "score/chordname.h"
#include "score/chordnamecontext.h"
#include "score/playable.h"
#include "score/playablelength.h"
#include "score/sheet.h"
/*!
\class CAChordNameContext
\brief Context for chord names
This class represents a container for the chord names.
It is somehow similar to CALyricsContext in terms of use.
The class keeps all chord names in a single list. No specific times are stored.
This is because exactly one chord name is assigned to every chord in the score.
*/
CAChordNameContext::CAChordNameContext(QString name, CASheet* sheet)
: CAContext(name, sheet)
{
setContextType(ChordNameContext);
repositionElements();
}
CAChordNameContext::~CAChordNameContext()
{
clear();
}
/*!
Inserts the given chord name \a m according to its timeStart.
Replaces any existing chord name at that time, if \a replace is True (default).
*/
void CAChordNameContext::addChordName(CAChordName* m, bool replace)
{
int i;
for (i = 0; i < _chordNameList.size() && _chordNameList[i]->timeStart() < m->timeStart(); i++)
;
if (i < _chordNameList.size() && replace) {
delete _chordNameList.takeAt(i);
}
_chordNameList.insert(i, m);
for (i++; i < _chordNameList.size(); i++) {
_chordNameList[i]->setTimeStart(_chordNameList[i]->timeStart() + m->timeLength());
}
}
CAMusElement* CAChordNameContext::insertEmptyElement(int timeStart)
{
int i;
for (i = 0; i < _chordNameList.size() && _chordNameList[i]->timeStart() < timeStart; i++)
;
CAChordName *newChord = new CAChordName(CADiatonicPitch::Undefined, "", this, timeStart, 1);
_chordNameList.insert(i, newChord);
for (i++; i < _chordNameList.size(); i++)
_chordNameList[i]->setTimeStart(_chordNameList[i]->timeStart() + 1);
return newChord;
}
void CAChordNameContext::repositionElements()
{
int ts, tl;
int curIdx; // contains current position in _chordNameList
QList<CAPlayable*> chord;
for (ts = 0, curIdx = 0;
(sheet() && (chord = sheet()->getChord(ts)).size()) || curIdx < _chordNameList.size(); ts += tl, curIdx++) {
tl = (chord.size() ? chord[0]->timeLength() : 256);
for (int i = 0; i < chord.size(); i++)
if (chord[i]->timeLength() < tl)
tl = chord[i]->timeLength();
// add new empty chord names, if playables still exist above
if (curIdx == _chordNameList.size()) {
insertEmptyElement(ts);
}
// apply timeStart and timeLength to existing chord names
if (curIdx < _chordNameList.size()) {
_chordNameList[curIdx]->setTimeLength(tl);
_chordNameList[curIdx]->setTimeStart(ts);
}
}
}
/*!
Returns chord name at the given \a time.
*/
CAChordName* CAChordNameContext::chordNameAtTimeStart(int time)
{
int i;
for (i = 0; i < _chordNameList.size() && _chordNameList[i]->timeStart() <= time; i++)
;
if (i > 0 && _chordNameList[--i]->timeEnd() > time) {
return _chordNameList[i];
} else {
return nullptr;
}
}
CAContext* CAChordNameContext::clone(CASheet* s)
{
CAChordNameContext* newCnc = new CAChordNameContext(name(), s);
for (int i = 0; i < _chordNameList.size(); i++) {
CAChordName* newCn = static_cast<CAChordName*>(_chordNameList[i]->clone(newCnc));
newCnc->addChordName(newCn);
}
return newCnc;
}
void CAChordNameContext::clear()
{
while (!_chordNameList.isEmpty())
delete _chordNameList.takeFirst();
}
CAMusElement* CAChordNameContext::next(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::ChordName)
return nullptr;
int i = _chordNameList.indexOf(static_cast<CAChordName*>(elt));
if ((i != -1) && (++i < _chordNameList.size()))
return _chordNameList[i];
else
return nullptr;
}
CAMusElement* CAChordNameContext::previous(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::ChordName)
return nullptr;
int i = _chordNameList.indexOf(static_cast<CAChordName*>(elt));
if (i != -1 && --i > -1)
return _chordNameList[i];
else
return nullptr;
}
bool CAChordNameContext::remove(CAMusElement* elt)
{
if (!elt || elt->musElementType() != CAMusElement::ChordName)
return false;
bool success = false;
success = _chordNameList.removeAll(static_cast<CAChordName*>(elt));
if (success)
delete elt;
return success;
}
| 4,713
|
C++
|
.cpp
| 137
| 29.693431
| 117
| 0.665422
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,345
|
voice.cpp
|
canorusmusic_canorus/src/score/voice.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/voice.h"
#include "interface/mididevice.h"
#include "score/clef.h"
#include "score/keysignature.h"
#include "score/lyricscontext.h"
#include "score/mark.h"
#include "score/muselement.h"
#include "score/note.h"
#include "score/playable.h"
#include "score/rest.h"
#include "score/slur.h"
#include "score/staff.h"
#include "score/tempo.h"
#include "score/timesignature.h"
/*!
\class CAVoice
\brief Class which represents a voice in the staff.
CAVoice is a class which holds music elements in the staff. In hieararchy, staff
includes multiple voices and every voice includes multiple music elements.
\sa CAStaff, CAMusElement
*/
/*!
Creates a new voice named \a name, in \a staff, \a voiceNumber and \a stemDirection of notes stems.
Voice number starts at 1.
*/
CAVoice::CAVoice(const QString name, CAStaff* staff, CANote::CAStemDirection stemDirection)
{
_staff = staff;
_name = name;
_stemDirection = stemDirection;
_midiChannel = ((staff && staff->sheet()) ? CAMidiDevice::freeMidiChannel(staff->sheet()) : 0);
_midiProgram = 0;
_midiPitchOffset = 0;
}
/*!
Clears and destroys the current voice.
This also destroys all non-shared music elements held by the voice.
\sa clear()
*/
CAVoice::~CAVoice()
{
clear();
QList<CALyricsContext*> lc = lyricsContextList();
for (int i = 0; i < lc.size(); i++) {
lc[i]->setAssociatedVoice(nullptr);
}
if (staff()) {
staff()->removeVoice(this);
}
}
/*!
Clones the current voice including all the music elements.
Sets the voice staff to \a newStaff. If none given, use the original staff.
*/
CAVoice* CAVoice::clone(CAStaff* newStaff)
{
CAVoice* newVoice = new CAVoice(name(), newStaff);
newVoice->cloneVoiceProperties(this);
newVoice->setStaff(newStaff);
return newVoice;
}
/*!
Sets the properties of the given voice to this voice.
*/
void CAVoice::cloneVoiceProperties(CAVoice* voice)
{
setName(voice->name());
setStaff(voice->staff());
setStemDirection(voice->stemDirection());
setMidiChannel(voice->midiChannel());
setMidiProgram(voice->midiProgram());
setMidiPitchOffset(voice->midiPitchOffset());
setLyricsContexts(voice->lyricsContextList());
}
/*!
Destroys all non-shared music elements held by the voice.
When clearing the whole staff, make sure the voice is *deleted*.
It is automatically removed from the staff - in voice's destructor.
*/
void CAVoice::clear()
{
while (_musElementList.size()) {
// deletes an element only if it's not present in other voices or we're deleting the last voice
if (_musElementList.front()->isPlayable() || (staff() && staff()->voiceList().size() < 2))
delete _musElementList.front(); // CAMusElement's destructor removes it from the list
else
_musElementList.removeFirst();
}
}
/*!
Appends a music element \a elt at the end of the voice.
If \a addToChord is True and the appended element is note, the note is added to the chord
instead of added after the chord. If appended element is rest, \a addToChord is ignored.
Appended element's timeStart is changed respectively.
\note Due to speed issues, voices are NOT synchronized for every inserted element. User
should manually call CAStaff::synchronizeVoices().
\sa insert()
*/
void CAVoice::append(CAMusElement* elt, bool addToChord)
{
CAMusElement* last = (musElementList().size() ? musElementList().last() : nullptr);
if (elt->musElementType() == CAMusElement::Note && last && last->musElementType() == CAMusElement::Note && addToChord) {
elt->setTimeStart(last->timeStart());
addNoteToChord(static_cast<CANote*>(elt), static_cast<CANote*>(last));
} else {
elt->setTimeStart(last ? last->timeEnd() : 0);
insertMusElement(nullptr, elt);
}
}
/*!
Adds the given element \a elt to the voice before the given \a eltAfter. If \a eltAfter is null,
the element is appended.
If \a elt is non-playable, it eventually does the same as insertMusElement().
If \a elt is a note and addToChord is True, the eltAfter should also be a note and the \a elt is
then added to the chord which eltAfter is part of.
If \a elt is other playable element, it is appropriately added before the \a eltAfter. \a addToChord is ignored.
Inserted element's timeStart is correctly changed.
Returns True, if the insertion action was successfully made, otherwise False.
\note Due to speed issues, voices are NOT synchronized for every inserted element. User
should manually call CAStaff::synchronizeVoices().
\sa insertMusElement()
*/
bool CAVoice::insert(CAMusElement* eltAfter, CAMusElement* elt, bool addToChord)
{
if (!elt)
return false;
if (eltAfter && eltAfter->musElementType() == CAMusElement::Note && static_cast<CANote*>(eltAfter)->getChord().size()) // if eltAfter is note, it should always be the FIRST note in the chord
eltAfter = static_cast<CANote*>(eltAfter)->getChord().front();
bool res;
if (!elt->isPlayable()) {
// insert a sign
elt->setTimeStart(eltAfter ? eltAfter->timeStart() : lastTimeEnd());
res = insertMusElement(eltAfter, elt);
// calculate note positions in staff when inserting a new clef
if (elt->musElementType() == CAMusElement::Clef) {
for (int i = musElementList().indexOf(elt) + 1; i < musElementList().size(); i++) {
if (musElementList()[i]->musElementType() == CAMusElement::Note)
static_cast<CANote*>(musElementList()[i])->setDiatonicPitch(static_cast<CANote*>(musElementList()[i])->diatonicPitch());
}
}
} else if (elt->musElementType() == CAMusElement::Note && eltAfter && eltAfter->musElementType() == CAMusElement::Note && addToChord) {
// add a note to chord
res = addNoteToChord(static_cast<CANote*>(elt), static_cast<CANote*>(eltAfter));
} else {
// insert a note somewhere in between, append or prepend
elt->setTimeStart(eltAfter ? (eltAfter->timeStart()) : lastTimeEnd());
res = insertMusElement(eltAfter, elt);
updateTimes(musElementList().indexOf(elt) + 1, elt->timeLength(), true);
}
return res;
}
/*!
Inserts a note/rest in a tuplet/voice. If the result should not be a chord the element
found will be deleted and replaced. This function probably should also work for non
tuplets.
Currently only adding notes, and with the basic tuplet timelength are implemented.
*/
CAPlayable* CAVoice::insertInTupletAndVoiceAt(CAPlayable* reference, CAPlayable* p)
{
int t = reference->timeStart();
int rtype = static_cast<CAMusElement*>(reference)->musElementType();
//int ptype = static_cast<CAMusElement*>(p)->musElementType();
CATuplet* tup = reference->tuplet();
CAVoice* voice = reference->voice();
CAMusElement* next = voice->next(static_cast<CAMusElement*>(reference));
p->setTimeStart(t);
if (rtype == CAMusElement::Rest) {
voice->insert(next, static_cast<CAMusElement*>(p), false);
if (tup) { // remove the rest from the tuplet and add the note
tup->removeNote(reference);
reference->setTuplet(nullptr);
tup->addNote(p);
reference->voice()->remove(reference, true);
tup->assignTimes();
}
} else {
// add the note to a chord
voice->insert(reference, static_cast<CAMusElement*>(p), true);
if (tup) {
tup->addNote(p);
tup->assignTimes();
}
}
return p;
}
/*!
Returns a pointer to the clef which the given \a elt belongs to.
Returns nullptr, if no clefs placed yet.
Warning! This operation is slow (linear time), but always returns the
correct clef depending on the order of the musElementList. If a timeBased
result suffices, use CAStaff::getClef(time).
*/
CAClef* CAVoice::getClef(CAMusElement* elt)
{
if (!elt || !musElementList().contains(elt))
elt = lastMusElement();
while (elt && (elt->musElementType() != CAMusElement::Clef) && (elt = previous(elt)))
;
return static_cast<CAClef*>(elt);
}
/*!
Returns a pointer to the time signature which the given \a elt belongs to.
Returns nullptr, if no time signatures placed yet.
Warning! This operation is slow (linear time), but always returns the
correct timeSig depending on the order of the musElementList. If a timeBased
result suffices, use CAStaff::getClef(time).
*/
CATimeSignature* CAVoice::getTimeSig(CAMusElement* elt)
{
if (!elt || !musElementList().contains(elt))
elt = lastMusElement();
while (elt && (elt->musElementType() != CAMusElement::TimeSignature) && (elt = previous(elt)))
;
return static_cast<CATimeSignature*>(elt);
}
/*!
Returns a pointer to the key signature which the given \a elt belongs to.
Returns nullptr, if no key signatures placed yet.
Warning! This operation is slow (linear time), but always returns the
correct keySig depending on the order of the musElementList. If a timeBased
result suffices, use CAStaff::getClef(time).
*/
CAKeySignature* CAVoice::getKeySig(CAMusElement* elt)
{
if (!elt || !musElementList().contains(elt))
elt = lastMusElement();
while (elt && (elt->musElementType() != CAMusElement::KeySignature) && (elt = previous(elt)))
;
return static_cast<CAKeySignature*>(elt);
}
/*!
Removes the given music element \a elt from this voice, if the element is playable or from
all the voices in the staff, if non-playable and part of the staff.
If \a updateSigns is True, startTimes of elements after the removed one are decreased
including the shared signs. Otherwise only timeStarts for playable elements are effected.
\warning This function doesn't destroy the object, but only removes its
reference in the voice.
\note Due to speed issues, voices are NOT synchronized for every inserted element. User
should manually call CAStaff::synchronizeVoices().
Returns true, if the element was found and removed; otherwise false.
*/
bool CAVoice::remove(CAMusElement* elt, bool updateSigns)
{
if (_musElementList.contains(elt)) { // if the search element is found
if (!elt->isPlayable() && staff()) { // element is shared - remove it from all the voices
for (int i = 0; i < staff()->voiceList().size(); i++) {
staff()->voiceList()[i]->_musElementList.removeAll(elt);
}
// remove it from the references list
if (elt->musElementType() == CAMusElement::KeySignature)
staff()->keySignatureRefs().removeAll(elt);
else if (elt->musElementType() == CAMusElement::TimeSignature)
staff()->timeSignatureRefs().removeAll(elt);
else if (elt->musElementType() == CAMusElement::Clef)
staff()->clefRefs().removeAll(elt);
else if (elt->musElementType() == CAMusElement::Barline)
staff()->barlineRefs().removeAll(elt);
} else {
// element is playable
if (elt->musElementType() == CAMusElement::Note) {
CANote* n = static_cast<CANote*>(elt);
if (n->isPartOfChord() && n->isFirstInChord()) {
// if the note is the first in the chord, the slurs and marks should be relinked to the 2nd in the chord
CANote* prevNote = n->getChord().at(1);
prevNote->setSlurStart(n->slurStart());
prevNote->setSlurEnd(n->slurEnd());
prevNote->setPhrasingSlurStart(n->phrasingSlurStart());
prevNote->setPhrasingSlurEnd(n->phrasingSlurEnd());
for (int i = 0; i < n->markList().size(); i++) {
if (n->markList()[i]->isCommon()) {
prevNote->addMark(n->markList()[i]);
n->markList()[i]->setAssociatedElement(prevNote);
n->removeMark(n->markList()[i--]);
}
}
} else if (!(n->isPartOfChord())) {
if (n->slurStart())
delete n->slurStart();
if (n->slurEnd())
delete n->slurEnd();
if (n->phrasingSlurStart())
delete n->phrasingSlurStart();
if (n->phrasingSlurEnd())
delete n->phrasingSlurEnd();
if (n->tuplet())
delete n->tuplet();
updateTimes(musElementList().indexOf(elt) + 1, elt->timeLength() * (-1), updateSigns); // shift back timeStarts of playable elements after it
}
} else {
if (elt->isPlayable() && static_cast<CAPlayable*>(elt)->tuplet())
delete static_cast<CAPlayable*>(elt)->tuplet();
updateTimes(musElementList().indexOf(elt) + 1, elt->timeLength() * (-1), updateSigns); // shift back timeStarts of playable elements after it
}
_musElementList.removeAll(elt); // removes the element from the voice music element list
}
return true;
} else {
return false;
}
}
/*!
Inserts the \a elt before the given \a eltAfter. If \a eltAfter is Null, it
appends the element.
Returns True, if \a eltAfter was found and the elt was inserted/appended; otherwise False.
*/
bool CAVoice::insertMusElement(CAMusElement* eltAfter, CAMusElement* elt)
{
if (!eltAfter || !_musElementList.size()) {
_musElementList.push_back(elt);
} else {
int i = musElementList().indexOf(eltAfter);
// if element wasn't found and the element before is slur
if (eltAfter->musElementType() == CAMusElement::Slur && i == -1)
i = musElementList().indexOf(static_cast<CASlur*>(eltAfter)->noteEnd());
if (i == -1) {
// eltBefore still wasn't found, return False
return false;
}
// eltBefore found, insert it
_musElementList.insert(i, elt);
}
CAMusElement* next = nextByType(elt->musElementType(), elt);
QList<CAMusElement*>* refs = nullptr;
// update staff references
if (elt->musElementType() == CAMusElement::KeySignature) {
refs = &staff()->keySignatureRefs();
} else if (elt->musElementType() == CAMusElement::TimeSignature) {
refs = &staff()->timeSignatureRefs();
} else if (elt->musElementType() == CAMusElement::Clef) {
refs = &staff()->clefRefs();
} else if (elt->musElementType() == CAMusElement::Barline) {
refs = &staff()->barlineRefs();
}
if (refs) {
int idxInRefs = refs->indexOf(next);
if (idxInRefs == -1) {
// we want to append the element
idxInRefs = refs->size();
}
if (!refs->contains(elt)) {
refs->insert(idxInRefs, elt);
}
}
return true;
}
/*!
Adds a \a note to an already existing \a referenceNote chord or a single note and
creates a chord out of it.
Notes in a chord always need to be sorted by pitch rising.
Chord in Canorus isn't its own structure but simply a list of notes sharing the
same start time.
The inserted \a note properteis timeStart, timeLength, dotted and playableLength
change according to other notes in the chord.
Returns True, if a referenceNote was found and a note was added; otherwise False.
\sa CANote::chord()
*/
bool CAVoice::addNoteToChord(CANote* note, CANote* referenceNote)
{
int idx = _musElementList.indexOf(referenceNote);
if (idx == -1)
return false;
QList<CANote*> chord = referenceNote->getChord();
idx = _musElementList.indexOf(chord.first());
int i;
for (i = 0; i < chord.size() && chord[i]->diatonicPitch().noteName() < note->diatonicPitch().noteName(); i++)
;
_musElementList.insert(idx + i, note);
note->setPlayableLength(referenceNote->playableLength());
note->setTimeLength(referenceNote->timeLength());
note->setTimeStart(referenceNote->timeStart());
note->setStemDirection(referenceNote->stemDirection());
return true;
}
/*!
Returns the pitch of the last note in the voice (default) or of the first note in
the last chord, if \a inChord is true.
This method is usually used by LilyPond parser when exporting the document, where
, or ' octave marks need to be determined.
\sa lastPlayableElt()
*/
CADiatonicPitch CAVoice::lastNotePitch(bool inChord)
{
for (int i = _musElementList.size() - 1; i >= 0; i--) {
if (_musElementList[i]->musElementType() == CAMusElement::Note) {
if (!static_cast<CANote*>(_musElementList[i])->isPartOfChord() || !inChord) // the note is not part of the chord
return (static_cast<CANote*>(_musElementList[i])->diatonicPitch());
else {
int chordTimeStart = _musElementList[i]->timeStart();
int j;
for (j = i;
(j >= 0 && _musElementList[j]->musElementType() == CAMusElement::Note && _musElementList[j]->timeStart() == chordTimeStart);
j--)
;
return (static_cast<CANote*>(_musElementList[j + 1])->diatonicPitch());
}
} else if (_musElementList[i]->musElementType() == CAMusElement::Clef)
return (static_cast<CAClef*>(_musElementList[i])->centerPitch());
}
return -1;
}
/*!
Returns the last playable element (eg. note or rest) in the voice.
\sa lastNotePitch()
*/
CAPlayable* CAVoice::lastPlayableElt()
{
for (int i = _musElementList.size() - 1; i >= 0; i--) {
if (_musElementList[i]->isPlayable())
return static_cast<CAPlayable*>(_musElementList[i]);
}
return nullptr;
}
/*!
Returns the note in the voice.
\sa lastNotePitch()
*/
CANote* CAVoice::lastNote()
{
for (int i = _musElementList.size() - 1; i >= 0; i--) {
if (_musElementList[i]->musElementType() == CAMusElement::Note)
return static_cast<CANote*>(_musElementList[i]);
}
return nullptr;
}
//! \A common binary search Algorithm with its pseudocode
bool CAVoice::binarySearch_startTime(int time, int& position)
{
int low = 0, high = _musElementList.size() - 1, midpoint = 0;
while (low <= high) {
midpoint = (low + high) / 2;
if (time == _musElementList[midpoint]->timeStart()) {
position = midpoint;
return true;
} else if (time < _musElementList[midpoint]->timeStart())
high = midpoint - 1;
else
low = midpoint + 1;
}
return false;
}
/*!
Returns a music element which has the given \a startTime and \a type.
This is useful for querying for eg. If a barline exists at the certain
point in time.
*/
CAMusElement* CAVoice::getOneEltByType(CAMusElement::CAMusElementType type, int startTime)
{
int i;
for (i = 0; i < _musElementList.size() && _musElementList[i]->timeStart() < startTime; i++)
; // seek to the start of the music elements with the given time
while (i < _musElementList.size() && _musElementList[i]->timeStart() == startTime) { // create a list of music elements with the given time
if (_musElementList[i]->musElementType() == type)
return _musElementList[i];
i++;
}
return nullptr;
}
/*!
Returns a list of pointers to actual music elements which have the given \a
startTime and are of given \a type.
This is useful for querying for eg. If a new key signature exists at the certain
point in time.
*/
QList<CAMusElement*> CAVoice::getEltByType(CAMusElement::CAMusElementType type, int startTime)
{
QList<CAMusElement*> eltList;
int i;
for (i = 0; i < _musElementList.size() && _musElementList[i]->timeStart() < startTime; i++)
; // seek to the start of the music elements with the given time
while (i < _musElementList.size() && _musElementList[i]->timeStart() == startTime) { // create a list of music elements with the given time
if (_musElementList[i]->musElementType() == type)
eltList << _musElementList[i];
i++;
}
return eltList;
}
/*!
Returns a music elements which is at or left (not past)
the given \a startTime and of given \a type.
This is useful for querying for eg. which is the barline before a certain
point in time.
*/
CAMusElement* CAVoice::getOnePreviousByType(CAMusElement::CAMusElementType type, int startTime)
{
int i;
for (i = _musElementList.size() - 1;
i >= 0 && _musElementList[i]->timeStart() > startTime; i--)
; // seek to the most right of the music elements with the given time
while (i >= 0 && _musElementList[i]->timeStart() <= startTime) { // create a list of music elements not past the given time
if (_musElementList[i]->musElementType() == type)
return _musElementList[i];
i--;
}
return nullptr;
}
/*!
Returns a list of pointers to actual music elements which are at or left (not past)
the given \a startTime and are of given \a type.
This is useful for querying for eg. which key pitch is in effect before a certain
point in time.
A list from time 0 until startTime is created which is
questionable regarding need and efficiency.
*/
QList<CAMusElement*> CAVoice::getPreviousByType(CAMusElement::CAMusElementType type, int startTime)
{
QList<CAMusElement*> eltList;
int i;
for (i = _musElementList.size() - 1;
i >= 0 && _musElementList[i]->timeStart() > startTime; i--)
; // seek to the most right of the music elements with the given time
while (i >= 0 && _musElementList[i]->timeStart() <= startTime) { // create a list of music elements not past the given time
if (_musElementList[i]->musElementType() == type)
eltList.prepend(_musElementList[i]);
i--;
}
return eltList;
}
/*!
Returns a list of notes and rests (chord) in the given voice in the given
time slice \a time.
This is useful for determination of the harmony at certain point in time.
\sa CAStaff:getChord(), CASheet::getChord()
*/
QList<CAPlayable*> CAVoice::getChord(int time)
{
int i;
for (i = 0; i < _musElementList.size() && (_musElementList[i]->timeEnd() <= time || !_musElementList[i]->isPlayable()); i++)
;
if (i != _musElementList.size()) {
if (_musElementList[i]->musElementType() == CAMusElement::Note) { // music element is a note
//! \todo Casting QList<CANote*> to QList<CAPlayable*> doesn't work?! :( Do the conversation manually. This is slow. -Matevz
QList<CANote*> list = static_cast<CANote*>(_musElementList[i])->getChord();
QList<CAPlayable*> ret;
for (int i = 0; i < list.size(); i++)
ret << list[i];
return ret;
} else { // music element is a rest
QList<CAPlayable*> ret;
ret << static_cast<CARest*>(_musElementList[i]);
return ret;
}
}
return QList<CAPlayable*>();
}
/*!
Returns a list of music elements inside the given bar.
The return list consists of all music elements between two barlines excluding the first barline.
Expression marks and other non-standalone elements are excluded as well.
The parameter \a time is any time of music elements inside the bar.
This function is usually called when double clicking on the score.
*/
QList<CAMusElement*> CAVoice::getBar(int time)
{
QList<CAPlayable*> chord = getChord(time);
QList<CAMusElement*> ret;
if (!chord.size()) {
return ret;
}
// search left
CAMusElement* curElt = previous(chord[0]);
while (curElt && curElt->musElementType() != CAMusElement::Barline) {
ret.append(curElt);
curElt = previous(curElt);
}
ret.append(chord[0]);
curElt = next(chord[0]);
while (curElt && curElt->musElementType() != CAMusElement::Barline) {
ret.append(curElt);
curElt = next(curElt);
}
if (curElt) { // last elt is barline
ret.append(curElt);
}
return ret;
}
/*!
Generates a list of all the notes and chords in the voice.
This is useful for harmony analysis.
*/
QList<CANote*> CAVoice::getNoteList()
{
QList<CANote*> list;
for (int i = 0; i < _musElementList.size(); i++)
if (_musElementList[i]->musElementType() == CAMusElement::Note)
list << static_cast<CANote*>(_musElementList[i]);
return list;
}
/*!
Generates a list of all the notes and chords in the voice.
This is useful when importing a specific voice and all the shared elements should be
completely repositioned.
*/
QList<CAMusElement*> CAVoice::getSignList()
{
QList<CAMusElement*> list;
for (int i = 0; i < _musElementList.size(); i++)
if (!_musElementList[i]->isPlayable())
list << _musElementList[i];
return list;
}
/*!
Returns pointer to the music element after the given \a elt or 0, if the next music
element doesn't exist.
If \elt is null, it returns the first element in the voice.
*/
CAMusElement* CAVoice::next(CAMusElement* elt)
{
if (musElementList().isEmpty())
return nullptr;
if (elt) {
int idx = _musElementList.indexOf(elt);
if (idx == -1) //the element wasn't found
return nullptr;
if (++idx == _musElementList.size()) //last element in the list
return nullptr;
return _musElementList[idx];
} else {
return _musElementList.first();
}
}
/*!
Returns the first element of type \a type after the given \a elt or Null if
such an element doesn't exist.
If \a elt is Null, it returns the first element with such a type in the voice.
\sa previousByType()
*/
CAMusElement* CAVoice::nextByType(CAMusElement::CAMusElementType type, CAMusElement* elt)
{
while ((elt = next(elt)) && (elt->musElementType() != type))
;
return elt;
}
/*!
Returns the first element of type \a type before the given \a elt or Null if
such an element doesn't exist.
If \a elt is Null, it returns the last element with such a type in the voice.
\sa previousByType()
*/
CAMusElement* CAVoice::previousByType(CAMusElement::CAMusElementType type, CAMusElement* elt)
{
while ((elt = previous(elt)) && (elt->musElementType() != type))
;
return elt;
}
/*!
Returns pointer to the music element before the given \a elt or 0, if the previous
music element doesn't exist.
If \elt is null, it returns the last element in the voice.
*/
CAMusElement* CAVoice::previous(CAMusElement* elt)
{
if (musElementList().isEmpty())
return nullptr;
if (elt) {
int idx = _musElementList.indexOf(elt);
if (--idx < 0) //if the element wasn't found or was the first element
return nullptr;
return _musElementList[idx];
} else {
return _musElementList.last();
}
}
/*!
Returns a pointer to the next note with the strictly higher timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CANote* CAVoice::nextNote(int timeStart)
{
int i;
for (i = 0;
i < _musElementList.size() && (_musElementList[i]->musElementType() != CAMusElement::Note || _musElementList[i]->timeStart() <= timeStart);
i++)
;
if (i < _musElementList.size())
return static_cast<CANote*>(_musElementList[i]);
else
return nullptr;
}
/*!
Returns a pointer to the previous note with the strictly lower timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CANote* CAVoice::previousNote(int timeStart)
{
int i;
for (i = _musElementList.size() - 1;
i > -1 && (_musElementList[i]->musElementType() != CAMusElement::Note || _musElementList[i]->timeStart() >= timeStart);
i--)
;
if (i > -1)
return static_cast<CANote*>(_musElementList[i]);
else
return nullptr;
}
/*!
Returns a pointer to the next rest with the strictly higher timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CARest* CAVoice::nextRest(int timeStart)
{
int i;
for (i = 0;
i < _musElementList.size() && (_musElementList[i]->musElementType() != CAMusElement::Rest || _musElementList[i]->timeStart() <= timeStart);
i++)
;
if (i < _musElementList.size())
return static_cast<CARest*>(_musElementList[i]);
else
return nullptr;
}
/*!
Returns a pointer to the previous rest with the strictly lower timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CARest* CAVoice::previousRest(int timeStart)
{
int i;
for (i = _musElementList.size() - 1;
i > -1 && (_musElementList[i]->musElementType() != CAMusElement::Rest || _musElementList[i]->timeStart() >= timeStart);
i--)
;
if (i > -1)
return static_cast<CARest*>(_musElementList[i]);
else
return nullptr;
}
/*!
Returns a pointer to the next playable element with the strictly higher timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CAPlayable* CAVoice::nextPlayable(int timeStart)
{
int i;
for (i = 0;
i < _musElementList.size() && (!_musElementList[i]->isPlayable() || _musElementList[i]->timeStart() <= timeStart);
i++)
;
if (i < _musElementList.size())
return static_cast<CAPlayable*>(_musElementList[i]);
else
return nullptr;
}
/*!
Returns a pointer to the previous playable with the strictly lower timeStart than the given one.
Returns nullptr, if the such a note doesn't exist.
*/
CAPlayable* CAVoice::previousPlayable(int timeStart)
{
int i;
for (i = _musElementList.size() - 1;
i > -1 && (!_musElementList[i]->isPlayable() || _musElementList[i]->timeStart() >= timeStart);
i--)
;
if (i > -1)
return static_cast<CAPlayable*>(_musElementList[i]);
else
return nullptr;
}
/*!
Updates times of playable elements and optionally \a signsToo after and including the given index
\a idx for a delta \a length. The order of the elements stays intact.
This method is usually called when inserting, removing or changing the music elements so they affect
others.
*/
bool CAVoice::updateTimes(int idx, int length, bool signsToo)
{
for (int i = idx; i < musElementList().size(); i++)
if (signsToo || musElementList()[i]->isPlayable()) {
musElementList()[i]->setTimeStart(musElementList()[i]->timeStart() + length);
for (int j = 0; j < musElementList()[i]->markList().size(); j++) {
CAMark* m = musElementList()[i]->markList()[j];
if (!m->isCommon() || musElementList()[i]->musElementType() != CAMusElement::Note || static_cast<CANote*>(musElementList()[i])->isFirstInChord())
m->setTimeStart(musElementList()[i]->timeStart());
}
}
return true; // What to return ? Maybe if some music element times were actually set
}
/*!
Fixes any inconsistencies between music elements:
1) If a common (shared) mark is present only in non-first note of the chord, it's moved and assigned
to first note in the chord.
The exception are non-common marks (eg. fingering), which are assigned to each note separately.
Returns True, if fixes were made or False otherwise.
*/
bool CAVoice::synchronizeMusElements()
{
bool fixesMade = false;
for (int i = 0; i < musElementList().size(); i++) {
if (musElementList()[i]->musElementType() == CAMusElement::Note && musElementList()[i]->markList().size() && static_cast<CANote*>(musElementList()[i])->isPartOfChord()) {
QList<CAMark*> marks; // list of shared marks
QList<CANote*> chord = static_cast<CANote*>(musElementList()[i])->getChord();
// gather a list of marks and remove them from the chord
for (int j = 0; j < chord.size(); j++) {
for (int k = 0; k < chord[j]->markList().size(); k++) {
if (chord[j]->markList()[k]->isCommon()) {
chord[j]->markList()[k]->setAssociatedElement(chord.first());
if (!marks.contains(chord[j]->markList()[k]))
marks << chord[j]->markList()[k];
chord[j]->removeMark(chord[j]->markList()[k]);
}
}
}
// add marks back to the chord
for (int k = 0; k < marks.size(); k++) {
chord.first()->addMark(marks[k]);
}
// move at the end of the chord
i += (chord.size() - chord.indexOf(static_cast<CANote*>(musElementList()[i])));
fixesMade = true;
}
}
return fixesMade;
}
/*!
Returns true, if this voice contains a note with the given \a pitch notename at the
given \a timeStart.
This is useful when inserting a note and there needs to be determined if a user is
adding a note to a chord and the note is maybe already there. Note's accidentals
are ignored.
*/
bool CAVoice::containsPitch(int noteName, int timeStart)
{
for (int i = 0; i < _musElementList.size(); i++) {
if (_musElementList[i]->timeStart() == timeStart && _musElementList[i]->musElementType() == CAMusElement::Note && static_cast<CANote*>(_musElementList[i])->diatonicPitch().noteName() == noteName)
return true;
}
return false;
}
/*!
Returns true, if this voice contains a note with the given diatonic \a pitch at the
given \a timeStart.
This is useful when inserting a note and there needs to be determined if a user is
adding a note to a chord and the note is maybe already there.
*/
bool CAVoice::containsPitch(CADiatonicPitch p, int timeStart)
{
for (int i = 0; i < _musElementList.size(); i++) {
if (_musElementList[i]->timeStart() == timeStart && _musElementList[i]->musElementType() == CAMusElement::Note && static_cast<CANote*>(_musElementList[i])->diatonicPitch() == p)
return true;
}
return false;
}
/*!
Returns the Tempo element active at the given time.
*/
CATempo* CAVoice::getTempo(int time)
{
QList<CAPlayable*> chord = getChord(time);
int curElt = -1;
if (chord.isEmpty()) {
curElt = musElementList().size() - 1;
} else {
curElt = musElementList().indexOf(chord.last());
}
CATempo* tempo = nullptr;
while (!tempo && curElt >= 0) {
for (int i = 0; i < musElementList()[curElt]->markList().size(); i++) {
if (musElementList()[curElt]->markList()[i]->markType() == CAMark::Tempo) {
tempo = static_cast<CATempo*>(musElementList()[curElt]->markList()[i]);
}
}
curElt--;
}
return tempo;
}
/*!
Returns a list of pointers to key signatures which have the given \a startTime.
This is useful for querying for eg. If a new key signature exists at the certain
point in time.
*/
QList<CAMusElement*> CAVoice::getKeySignature(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the start of the music elements with the given time
for (i = 0; i < staff()->keySignatureRefs().size() && staff()->keySignatureRefs()[i]->timeStart() < startTime; i++)
;
// create a list of music elements with the given time
while (i < staff()->keySignatureRefs().size() && staff()->keySignatureRefs()[i]->timeStart() == startTime) {
eltList << staff()->keySignatureRefs()[i];
i++;
}
return eltList;
}
/*!
Returns a list of pointers to key signatures which have the given \a startTime.
This is useful for querying for eg. If a new key signature exists at the certain
point in time.
*/
QList<CAMusElement*> CAVoice::getTimeSignature(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the start of the music elements with the given time
for (i = 0; i < staff()->timeSignatureRefs().size() && staff()->timeSignatureRefs()[i]->timeStart() < startTime; i++)
;
// create a list of music elements with the given time
while (i < staff()->timeSignatureRefs().size() && staff()->timeSignatureRefs()[i]->timeStart() == startTime) {
eltList << staff()->timeSignatureRefs()[i];
i++;
}
return eltList;
}
/*!
Returns a list of pointers to key signatures which have the given \a startTime.
This is useful for querying for eg. If a new key signature exists at the certain
point in time.
*/
QList<CAMusElement*> CAVoice::getClef(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the start of the music elements with the given time
for (i = 0; i < staff()->clefRefs().size() && staff()->clefRefs()[i]->timeStart() < startTime; i++)
;
// create a list of music elements with the given time
while (i < staff()->clefRefs().size() && staff()->clefRefs()[i]->timeStart() == startTime) {
eltList << staff()->clefRefs()[i];
i++;
}
return eltList;
}
/*!
Returns a list of pointers to key signatures which are at or left (not past)
the given \a startTime.
This is useful for querying for eg. which key signature is in effect before a certain
point in time.
*/
QList<CAMusElement*> CAVoice::getPreviousKeySignature(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the most right of the music elements with the given time
for (i = staff()->keySignatureRefs().size() - 1;
i >= 0 && staff()->keySignatureRefs()[i]->timeStart() > startTime; i--)
;
// create a list of music elements not past the given time
while (i >= 0 && staff()->keySignatureRefs()[i]->timeStart() <= startTime) {
eltList.prepend(staff()->keySignatureRefs()[i]);
i--;
}
return eltList;
}
/*!
Returns a list of pointers to key signatures which are at or left (not past)
the given \a startTime.
This is useful for querying for eg. which key signature is in effect before a certain
point in time.
*/
QList<CAMusElement*> CAVoice::getPreviousTimeSignature(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the most right of the music elements with the given time
for (i = staff()->timeSignatureRefs().size() - 1;
i >= 0 && staff()->timeSignatureRefs()[i]->timeStart() > startTime; i--)
;
// create a list of music elements not past the given time
while (i >= 0 && staff()->timeSignatureRefs()[i]->timeStart() <= startTime) {
eltList.prepend(staff()->timeSignatureRefs()[i]);
i--;
}
return eltList;
}
/*!
Returns a list of pointers to clefs which are at or left (not past)
the given \a startTime.
This is useful for querying for eg. which clef is in effect before a certain
point in time.
*/
QList<CAMusElement*> CAVoice::getPreviousClef(int startTime)
{
QList<CAMusElement*> eltList;
int i;
// seek to the most right of the music elements with the given time
for (i = staff()->clefRefs().size() - 1;
i >= 0 && staff()->clefRefs()[i]->timeStart() > startTime; i--)
;
// create a list of music elements not past the given time
while (i >= 0 && staff()->clefRefs()[i]->timeStart() <= startTime) {
eltList.prepend(staff()->clefRefs()[i]);
i--;
}
return eltList;
}
/*!
\fn void CAVoice::setStemDirection(CANote::CAStemDirection direction)
Sets the stem direction and update slur directions in all the notes in the voice.
*/
/*!
\fn CAVoice::musElementList()
Returns the list of music elements in the voice.
\sa _musElementList
*/
/*!
\var CAVoice::_staff
Staff which this voice belongs to.
\sa staff()
*/
/*!
\fn CAVoice::voiceNumber()
Voice number in the staff starting at 1.
Voice number is 1, if no staff defined.
*/
| 40,196
|
C++
|
.cpp
| 1,009
| 34.021804
| 203
| 0.652598
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,346
|
playable.cpp
|
canorusmusic_canorus/src/score/playable.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/playable.h"
#include "score/staff.h"
#include "score/voice.h"
/*!
\class CAPlayable
\brief Playable instances of music elements.
CAPlayable class represents a base class for all the music elements which are
playable (timeLength property is greater than 0). It also adds other properties
like the music length (whole, half, quarter etc.), number of dots and instead
of contexts, playable elements voices for their parent objects.
Notes and rests inherit this class.
\sa CAMusElement, CAPlayableLength
*/
/*!
Creates a new playable element with playable length \a length, \a voice, \a timeStart
and number of dots \a dotted.
\sa CAPlayableLength, CAVoice, CAMusElement
*/
CAPlayable::CAPlayable(CAPlayableLength length, CAVoice* voice, int timeStart, int timeLength)
: CAMusElement(voice ? (voice->staff()) : nullptr, timeStart, timeLength)
{
setVoice(voice);
setPlayableLength(length);
if (timeLength == -1) {
calculateTimeLength();
}
setTuplet(nullptr);
}
/*!
Destroys the playable element.
The element is removed from any voice, if part of.
\note Non-playable signs are not shifted back when removing the element from the voice.
*/
CAPlayable::~CAPlayable()
{
if (tuplet())
tuplet()->removeNote(this);
if (voice())
voice()->remove(this, false);
}
void CAPlayable::setVoice(CAVoice* voice)
{
_voice = voice;
_context = voice ? voice->staff() : nullptr;
}
/*!
Calculates the new timeLength depending on the playableLength.
Tuplets and other time transformations are not recognized.
\sa playableLength(), resetTime()
*/
void CAPlayable::calculateTimeLength()
{
setTimeLength(CAPlayableLength::playableLengthToTimeLength(playableLength()));
}
/*!
Calculates both the new timeLength and timeStart according to the playableLength
and the previous playable element timeEnd.
Element should be part of the voice.
Tuplets and other time transformations are not recognized.
\sa calculateTimeLength()
*/
void CAPlayable::resetTime()
{
CAPlayable* p;
if (voice() && (p = voice()->previousPlayable(timeStart()))) {
setTimeStart(p->timeEnd());
} else {
setTimeStart(0);
}
calculateTimeLength();
}
| 2,466
|
C++
|
.cpp
| 76
| 29.447368
| 94
| 0.747044
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,347
|
tempo.cpp
|
canorusmusic_canorus/src/score/tempo.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/tempo.h"
/*!
\class CATempo
\brief Tempo mark
Sets and shows the tempo mark.
It consists of the note (beat) and beats per minute number.
*/
CATempo::CATempo(CAPlayableLength p, unsigned char bpm, CAMusElement* t)
: CAMark(CAMark::Tempo, t)
{
setBeat(p);
setBpm(bpm);
}
CATempo::~CATempo()
{
}
CATempo* CATempo::clone(CAMusElement* elt)
{
return new CATempo(beat(), bpm(), elt);
}
int CATempo::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
else if (static_cast<CAMark*>(elt)->markType() != CAMark::Tempo)
return -1;
else if (static_cast<CATempo*>(elt)->bpm() != bpm())
return 1;
else if (static_cast<CATempo*>(elt)->beat() != beat())
return 2;
else
return 0;
}
| 1,025
|
C++
|
.cpp
| 38
| 23.578947
| 76
| 0.680286
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,348
|
bookmark.cpp
|
canorusmusic_canorus/src/score/bookmark.cpp
|
/*!
Copyright (c) 2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/bookmark.h"
/*!
\class CABookMark
\brief A bookmark shortcut
Arbitrary text above or below *any* element with a shortcut key.
*/
CABookMark::CABookMark(const QString s, CAMusElement* elt)
: CAMark(CAMark::BookMark, elt)
{
setText(s);
}
CABookMark::~CABookMark()
{
}
CABookMark* CABookMark::clone(CAMusElement* elt)
{
return new CABookMark(text(), elt);
}
int CABookMark::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::BookMark)
return -1;
if (static_cast<CABookMark*>(elt)->text() != text())
return 1;
return 0;
}
| 904
|
C++
|
.cpp
| 33
| 24.30303
| 76
| 0.711628
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,349
|
crescendo.cpp
|
canorusmusic_canorus/src/score/crescendo.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/crescendo.h"
#include "score/note.h"
/*!
\class CACrescendo
\brief Crescendo and Decrescendo marks
Relative dynamic marks.
Crescendo starts with the current volume and linearily increases the volume
to the final volume. Decrescendo decreases volume to the final volume.
*/
CACrescendo::CACrescendo(int volume, CANote* note, CACrescendoType t, int timeStart, int timeLength)
: CAMark(CAMark::Crescendo, note, timeStart, timeLength)
{
setFinalVolume(volume);
setCrescendoType(t);
}
CACrescendo::~CACrescendo()
{
}
CACrescendo* CACrescendo::clone(CAMusElement* elt)
{
return new CACrescendo(finalVolume(), (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr, crescendoType(), timeStart(), timeLength());
}
int CACrescendo::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::Crescendo)
return -1;
if (static_cast<CACrescendo*>(elt)->finalVolume() != finalVolume())
return 1;
if (static_cast<CACrescendo*>(elt)->crescendoType() != crescendoType())
return 1;
return 0;
}
const QString CACrescendo::crescendoTypeToString(CACrescendoType t)
{
switch (t) {
case Crescendo:
return "Crescendo";
case Decrescendo:
return "Decrescendo";
}
return "Crescendo";
}
CACrescendo::CACrescendoType CACrescendo::crescendoTypeFromString(const QString c)
{
if (c == "Crescendo") {
return Crescendo;
} else if (c == "Decrescendo") {
return Decrescendo;
}
return Crescendo;
}
| 1,863
|
C++
|
.cpp
| 58
| 28.37931
| 171
| 0.72067
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,350
|
resource.cpp
|
canorusmusic_canorus/src/score/resource.cpp
|
/*!
Copyright (c) 2008-2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QFile>
#include <iostream>
#include "score/document.h"
#include "score/resource.h"
/*!
\class CAResource
\brief Different resources included in the file
CAResource is a wrapper for any file attached to the document.
Resource files are usually the recorded midi files, transcripts of
the score or a scanned music, audio and video files, score in other
formats, images in the score etc.
CAResource contains a valid absolute path (_fileName) to the actual file:
- If the resource is external (not included in file, but linked), _linked is
True and a _fileName is the absolute path of the linked file (or URL).
- If the resource is internal (saved along the file), _linked is False and a
_fileName is an absolute path to the extracted file in the system temporary
directory.
When the resources are saved, internal resources are saved as
\sa CAResourceContainer
*/
/*!
Default constructor.
*/
CAResource::CAResource(QUrl url, QString name, bool linked, CAResourceType t, CADocument* parent)
{
setName(name);
setUrl(url);
setLinked(linked);
setResourceType(t);
setDocument(parent);
}
CAResource::~CAResource()
{
if (document()) {
document()->removeResource(shared_from_this());
}
if (!isLinked()) {
QFile::remove(url().toLocalFile());
}
}
/*!
Copies the resource to the specified \a fileName.
Overwrites the specified \a fileName, if the file already exists.
*/
bool CAResource::copy(QString fileName)
{
if (QFile::exists(fileName)) {
QFile::remove(fileName);
}
return QFile::copy(url().toLocalFile(), fileName);
}
/*!
Converts the given \a type to string. Usually called when saving the resource.
*/
QString CAResource::resourceTypeToString(CAResourceType type)
{
switch (type) {
case Image:
return "image";
case Sound:
return "sound";
case Movie:
return "movie";
case Document:
return "document";
case Other:
return "other";
default:
return "";
}
}
/*!
Converts the given string \a type to CAResourceType. Usually called when opening the resource.
*/
CAResource::CAResourceType CAResource::resourceTypeFromString(QString type)
{
if (type == "image") {
return Image;
} else if (type == "sound") {
return Sound;
} else if (type == "movie") {
return Movie;
} else if (type == "document") {
return Document;
} else if (type == "other") {
return Other;
} else {
return Undefined;
}
}
| 2,773
|
C++
|
.cpp
| 95
| 25.315789
| 97
| 0.697447
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,351
|
ritardando.cpp
|
canorusmusic_canorus/src/score/ritardando.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/ritardando.h"
#include "score/playable.h"
/*!
\class CARitardando
\brief Ritardando and Accellerando marks
Relative tempo marks.
Ritardando starts with the current tempo and linearily decreases the tempo
to the final tempo. The original tempo is restored after the ritardando is finished.
Accellerando does the opposite.
*/
CARitardando::CARitardando(int finalTempo, CAPlayable* p, int timeLength, CARitardandoType t)
: CAMark(CAMark::Ritardando, p, p->timeStart(), timeLength)
{
setFinalTempo(finalTempo);
setRitardandoType(t);
}
CARitardando::~CARitardando()
{
}
CARitardando* CARitardando::clone(CAMusElement* elt)
{
return new CARitardando(finalTempo(), (elt->isPlayable()) ? static_cast<CAPlayable*>(elt) : nullptr, timeLength(), ritardandoType());
}
int CARitardando::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::Ritardando)
return -1;
if (static_cast<CARitardando*>(elt)->finalTempo() != finalTempo())
return 1;
if (static_cast<CARitardando*>(elt)->ritardandoType() != ritardandoType())
return 1;
return 0;
}
const QString CARitardando::ritardandoTypeToString(CARitardandoType t)
{
switch (t) {
case Ritardando:
return "Ritardando";
case Accellerando:
return "Accellerando";
}
return "Ritardando";
}
CARitardando::CARitardandoType CARitardando::ritardandoTypeFromString(const QString r)
{
if (r == "Ritardando") {
return Ritardando;
} else if (r == "Accellerando") {
return Accellerando;
}
return Ritardando;
}
| 1,907
|
C++
|
.cpp
| 59
| 28.59322
| 137
| 0.72762
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,352
|
instrumentchange.cpp
|
canorusmusic_canorus/src/score/instrumentchange.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/instrumentchange.h"
#include "score/note.h"
/*!
\class CAInstrumentChange
\brief Instrument change during the score
This class is used to allow the playback to change the default voice instrument.
\todo Instrument is now int. This should probably be moved out someday to enum
(eg. into CAInstrument?).
*/
CAInstrumentChange::CAInstrumentChange(int instrument, CANote* note)
: CAMark(CAMark::InstrumentChange, note)
{
setInstrument(instrument);
}
CAInstrumentChange::~CAInstrumentChange()
{
}
CAInstrumentChange* CAInstrumentChange::clone(CAMusElement* elt)
{
return new CAInstrumentChange(instrument(), (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr);
}
int CAInstrumentChange::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::InstrumentChange)
return -1;
if (static_cast<CAInstrumentChange*>(elt)->instrument() != instrument())
return 1;
return 0;
}
| 1,290
|
C++
|
.cpp
| 36
| 32.666667
| 133
| 0.749597
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,353
|
diatonickey.cpp
|
canorusmusic_canorus/src/score/diatonickey.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/diatonickey.h"
/*!
\class CADiatonicKey
\brief Musical key
This is a typical music presentation of the key.
For example, C-major, d-minor, e-flat-minor etc.
It consists of two properties:
- diatonic pitch (cis, des etc.)
- gender (major, minor etc.)
Valid range of diatonic pitch for the diatonic key is a positive
number ranging from 0 (C) to 6 (B).
\sa CADiatonicPitch
*/
CADiatonicKey::CADiatonicKey()
{
setDiatonicPitch(CADiatonicPitch(0));
setGender(Major);
setShape(Natural);
}
CADiatonicKey::CADiatonicKey(const QString& key)
{
operator=(key);
}
CADiatonicKey::CADiatonicKey(const int& nAccs, const CAGender& gender)
{
setGender(gender);
setShape(Natural);
int pitch = ((4 * nAccs) % 7) + ((nAccs < 0) ? 7 : 0);
if (gender == CADiatonicKey::Minor) // find the parallel minor key
pitch = (pitch + 5) % 7;
signed char accs = 0;
if (nAccs > 5 && gender == CADiatonicKey::Major)
accs = (nAccs - 5) / 7 + 1;
else if (nAccs > 2 && gender == CADiatonicKey::Minor)
accs = (nAccs - 2) / 7 + 1;
else if (nAccs < -1 && gender == CADiatonicKey::Major)
accs = (nAccs + 1) / 7 - 1;
else if (nAccs < -4 && gender == CADiatonicKey::Minor)
accs = (nAccs + 4) / 7 - 1;
setDiatonicPitch(CADiatonicPitch(pitch, accs));
}
CADiatonicKey::CADiatonicKey(const CADiatonicPitch& pitch, const CAGender& gender)
{
setDiatonicPitch(pitch);
setGender(gender);
if (gender == Major)
setShape(Natural);
else
setShape(Harmonic);
}
CADiatonicKey::CADiatonicKey(const CADiatonicPitch& pitch, const CAGender& gender, const CAShape& shape)
{
setDiatonicPitch(pitch);
setGender(gender);
setShape(shape);
}
int CADiatonicKey::numberOfAccs()
{
// calculate accs for minor keys
int accs = (((diatonicPitch().noteName() + 2) * 2 + 4) % 7 - 4);
accs += 7 * diatonicPitch().accs();
if (gender() == CADiatonicKey::Major)
accs += 3;
return accs;
}
bool CADiatonicKey::operator==(CADiatonicKey k)
{
if (diatonicPitch() == k.diatonicPitch() && gender() == k.gender())
return true;
else
return false;
}
void CADiatonicKey::operator=(const QString& key)
{
setDiatonicPitch(CADiatonicPitch(key));
setGender(key[0].isUpper() ? Major : Minor);
if (gender() == Major)
setShape(Natural);
else
setShape(Harmonic);
}
/*!
Transposes the key for the given \a interval.
The new pitch is correctly bounded.
*/
CADiatonicKey CADiatonicKey::operator+(CAInterval interval)
{
CADiatonicPitch p = diatonicPitch() + interval;
p.setNoteName(p.noteName() % 7);
if (p.noteName() < 0) {
p.setNoteName(p.noteName() + 7);
}
return CADiatonicKey(p, gender(), shape());
}
const QString CADiatonicKey::genderToString(CAGender gender)
{
switch (gender) {
case Major:
return "major";
case Minor:
return "minor";
}
return "";
}
CADiatonicKey::CAGender CADiatonicKey::genderFromString(const QString gender)
{
if (gender == "major")
return Major;
else if (gender == "minor")
return Minor;
else
return Major;
}
const QString CADiatonicKey::shapeToString(CAShape shape)
{
switch (shape) {
case Natural:
return "natural";
case Harmonic:
return "harmonic";
case Melodic:
return "melodic";
}
return "";
}
CADiatonicKey::CAShape CADiatonicKey::shapeFromString(const QString shape)
{
if (shape == "natural")
return Natural;
else if (shape == "harmonic")
return Harmonic;
else if (shape == "melodic")
return Melodic;
else
return Natural;
}
/*!
Generates a readable name of the diatonic key.
eg. -3 accidentals & major => "Es"
+6 accidentals & minor => "dis"
*/
const QString CADiatonicKey::diatonicKeyToString(CADiatonicKey k)
{
// calculate key signature pitch from number of accidentals
int pitch = ((4 * k.numberOfAccs()) % 7) + ((k.numberOfAccs() < 0) ? 7 : 0);
if (k.gender() == CADiatonicKey::Minor) // find the parallel minor key
pitch = (pitch + 5) % 7;
signed char accs = 0;
if (k.numberOfAccs() > 5 && k.gender() == CADiatonicKey::Major)
accs = (k.numberOfAccs() - 5) / 7 + 1;
else if (k.numberOfAccs() > 2 && k.gender() == CADiatonicKey::Minor)
accs = (k.numberOfAccs() - 2) / 7 + 1;
else if (k.numberOfAccs() < -1 && k.gender() == CADiatonicKey::Major)
accs = (k.numberOfAccs() + 1) / 7 - 1;
else if (k.numberOfAccs() < -4 && k.gender() == CADiatonicKey::Minor)
accs = (k.numberOfAccs() + 4) / 7 - 1;
QString name;
name = static_cast<char>((pitch + 2) % 7 + 'a');
for (int i = 0; i < accs; i++)
name += "is"; // append as many -is-es as necessary
for (int i = 0; i > accs; i--) {
if ((name == "e") || (name == "a"))
name += "s"; // for pitches E and A, only append single -s the first time
else if (name[0] == 'a')
name += "as"; // for pitch A, append -as instead of -es
else
name += "es"; // otherwise, append normally as many es-es as necessary
}
if (k.gender() == CADiatonicKey::Major)
name[0] = name[0].toUpper();
return name;
}
/*!
Creates a new diatonic key from the given string.
*/
CADiatonicKey CADiatonicKey::diatonicKeyFromString(const QString s)
{
return CADiatonicKey(s);
}
/*!
Returns a list of accs from C to B for the key signature.
*/
QList<int> CADiatonicKey::accsMatrix()
{
QList<int> matrix;
for (int i = 0; i < 7; i++)
matrix << 0;
for (int i = 1; i <= numberOfAccs(); i++) {
matrix[(i * 4 - 1) % 7] = 1;
}
for (int i = -1; i >= numberOfAccs(); i--) {
matrix[(i * (-3) + 3) % 7] = -1;
}
return matrix;
}
/*!
Returns number of accidentals for the given note.
Eg. If we call noteAccs(17) in D-Major, it returns 1, because 17 is a note F and D-Major has Fis.
*/
int CADiatonicKey::noteAccs(int noteName)
{
return accsMatrix()[noteName < 0 ? 6 - (-noteName - 1) % 7 : noteName % 7];
}
/*!
Returns true, if the given pitch \a p is a natural note in the key
signature; False otherwise.
eg. F# is a natural note in G-major, but not in C-major (ie. F).
*/
bool CADiatonicKey::containsPitch(const CADiatonicPitch& p)
{
return (accsMatrix()[p.noteName() % 7] == p.accs());
}
/*!
\enum CADiatonicKey::CAGender
The lower tetrachord of the scale - gender:
- Major
- Minor
*/
/*!
\enum CADiatonicKey::CAShape
The upper tetrachord of the scale - shape:
- Natural
- Harmonic
- Melodic
*/
| 6,909
|
C++
|
.cpp
| 230
| 25.752174
| 104
| 0.636748
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,354
|
mark.cpp
|
canorusmusic_canorus/src/score/mark.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/mark.h"
#include "score/note.h"
/*!
\class CAMark
\brief Marks that depend on other music elements
This class covers all marks that depend on other music elements. This includes all
text signs, dynamic marks, articulation, fingering, etc.
*/
CAMark::CAMark(CAMarkType type, CAMusElement* associatedElt, int timeStart, int timeLength)
: CAMusElement(associatedElt->context(),
(timeStart == -1) ? associatedElt->timeStart() : timeStart,
(timeLength == -1) ? associatedElt->timeLength() : timeLength)
{
setMusElementType(Mark);
setMarkType(type);
setAssociatedElement(associatedElt);
setCommon(true);
}
CAMark::CAMark(CAMarkType type, CAContext* c, int timeStart, int timeLength)
: CAMusElement(c,
timeStart,
timeLength)
{
setMusElementType(Mark);
setMarkType(type);
setAssociatedElement(nullptr);
setCommon(true);
}
/*!
Converts mark type to string.
\sa markTypeFromString()
*/
const QString CAMark::markTypeToString(CAMark::CAMarkType t)
{
switch (t) {
case Text:
return "Text";
case Tempo:
return "Tempo";
case Ritardando:
return "Ritardando";
case Dynamic:
return "Dynamic";
case Crescendo:
return "Crescendo";
case Pedal:
return "Pedal";
case InstrumentChange:
return "InstrumentChange";
case BookMark:
return "BookMark";
case RehersalMark:
return "RehersalMark";
case Fermata:
return "Fermata";
case RepeatMark:
return "RepeatMark";
case Articulation:
return "Articulation";
case Fingering:
return "Fingering";
default:
return "Undefined";
}
}
/*!
Converts mark type from string.
\sa markTypeToString()
*/
CAMark::CAMarkType CAMark::markTypeFromString(const QString s)
{
if (s == "Text") {
return Text;
} else if (s == "Tempo") {
return Tempo;
} else if (s == "Ritardando") {
return Ritardando;
} else if (s == "Dynamic") {
return Dynamic;
} else if (s == "Crescendo") {
return Crescendo;
} else if (s == "Pedal") {
return Pedal;
} else if (s == "InstrumentChange") {
return InstrumentChange;
} else if (s == "BookMark") {
return BookMark;
} else if (s == "RehersalMark") {
return RehersalMark;
} else if (s == "Fermata") {
return Fermata;
} else if (s == "RepeatMark") {
return RepeatMark;
} else if (s == "Articulation") {
return Articulation;
} else if (s == "Fingering") {
return Fingering;
} else {
return Undefined;
}
}
CAMark::~CAMark()
{
if (associatedElement()) {
associatedElement()->removeMark(this);
}
}
CAMark* CAMark::clone(CAMusElement* elt)
{
return new CAMark(markType(), elt, timeStart(), timeLength());
}
int CAMark::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark) {
return -1;
} else if (static_cast<CAMark*>(elt)->markType() != markType()) {
return -1;
} else {
return 0;
}
}
/*!
\var bool CAMark::_common
Is mark present in all music elements in the chord. Default: True.
The exception is the fingering which is assigned explicitly to the specific note
inside the chord
*/
| 3,577
|
C++
|
.cpp
| 132
| 22.174242
| 91
| 0.648688
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,355
|
notecheckererror.cpp
|
canorusmusic_canorus/src/score/notecheckererror.cpp
|
/*!
Copyright (c) 2015, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/notecheckererror.h"
#include "context.h"
#include "score/muselement.h"
#include "sheet.h"
/*!
\class CANoteCheckerError
\brief Class representing the error produced by the note checker
CANoteCheckerError is a class corresponding to the error, warning, hint etc.
in the score, produced by the CANoteChecker.
\sa CANoteChecker, CADrawableNoteCheckerError
*/
CANoteCheckerError::CANoteCheckerError(CAMusElement* targetElement, QString message)
: _targetElement(targetElement)
, _message(message)
{
targetElement->addNoteCheckerError(this);
}
CANoteCheckerError::~CANoteCheckerError()
{
if (_targetElement) {
_targetElement->removeNoteCheckerError(this);
if (_targetElement->context() && _targetElement->context()->sheet()) {
_targetElement->context()->sheet()->noteCheckerErrorList().removeAll(this);
}
}
}
| 1,102
|
C++
|
.cpp
| 31
| 32.225806
| 87
| 0.759172
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,356
|
rest.cpp
|
canorusmusic_canorus/src/score/rest.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/rest.h"
#include "score/mark.h"
#include "score/staff.h"
/*!
\class CARest
\brief Represents a rest in the score.
This class represents every rest in the score. It inherits the base class CAPlayable.
*/
/*!
Creates a new rest with given \a type, playable length \a length in voice \a voice with starting time in the score \a timeStart and number of dots \a dotted.
timeLength is calculated automatically from the playable length.
\sa CARestType, CAPlayableLength, CAPlayable, CAVoice
*/
CARest::CARest(CARestType type, CAPlayableLength length, CAVoice* voice, int timeStart, int timeLength)
: CAPlayable(length, voice, timeStart, timeLength)
{
_musElementType = CAMusElement::Rest;
_restType = type;
}
/*!
Destroys the rest.
*/
CARest::~CARest()
{
}
CARest* CARest::clone(CAVoice* voice)
{
CARest* r = new CARest(restType(), playableLength(), voice, timeStart(), timeLength());
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(r));
r->addMark(m);
}
return r;
}
int CARest::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Rest)
return -1;
int diffs = 0;
if (playableLength() != static_cast<CAPlayable*>(elt)->playableLength())
diffs++;
return diffs;
}
/*!
Converts rest type CARestType to QString.
This is usually used when saving the score.
\sa CARestType, CACanorusML
*/
const QString CARest::restTypeToString(CARestType type)
{
switch (type) {
case Normal:
return "normal";
case Hidden:
return "hidden";
default:
return "";
}
}
/*!
Converts rest type from QString to CARestType.
This is usually used when loading the score.
\sa CARestType, CACanorusML
*/
CARest::CARestType CARest::restTypeFromString(const QString type)
{
if (type == "hidden") {
return Hidden;
} else
return Normal;
}
/*!
Generates a list of new rests in the total length of \a timeLength.
Rests are sorted from the shortes to the longest one.
The first rest has the given \a timeStart.
Passing voice and restType is optional.
This function is usually called when a gap between two voices with shared elements
appear in one voice and the gap with custom length needs to be filled with rests.
\note Only non-dotted rests are generated.
*/
QList<CARest*> CARest::composeRests(int timeLength, int timeStart, CAVoice* voice, CARestType type)
{
QList<CARest*> list;
// 2048 is the longest rest (breve)
for (; timeLength > 2048; timeLength -= 2048, timeStart += 2048)
list << new CARest(type, CAPlayableLength(CAPlayableLength::Breve), voice, timeStart);
for (int i = 0, TL = 2048; i < 256; (i ? i *= 2 : i++), TL /= 2) {
if (TL <= timeLength) {
list << new CARest(type, CAPlayableLength(static_cast<CAPlayableLength::CAMusicLength>(i)), voice, timeStart);
timeLength -= TL;
timeStart += TL;
}
}
return list;
}
/*!
\var CARest::_restType
Type of the rest.
\sa CARestType, restType()
*/
| 3,335
|
C++
|
.cpp
| 105
| 28.104762
| 158
| 0.697972
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,357
|
tuplet.cpp
|
canorusmusic_canorus/src/score/tuplet.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/tuplet.h"
#include "score/playable.h"
#include "score/voice.h"
#include <iostream> // debug
/*!
\class CATuplet
\brief Class used for tuplets (triplets, duols etc.)
Tuplets are a rhythmic specialty. They are used to shorten the set of
notes for a specified multiplier.
Most used tuplets are triplets (multiplier 2/3) and duols (multiplier 3/4).
*/
/*!
Constructs a tuplet.
\a number is the existing number of notes and \a actualNumber is the desired
length of the notes expressed in number of them. These parameters are used to
calculate the multiplier of the notes.
eg. number=3, actualNumber=2 multiplies all notes by a factor of 2/3.
\a noteList is a sorted list of rests and notes under the tuplet. Elements
should already be part of the voice.
*/
CATuplet::CATuplet(int number, int actualNumber, QList<CAPlayable*> noteList)
: CAMusElement(noteList.front()->context(), noteList.front()->timeStart(), 0)
, _number(number)
, _actualNumber(actualNumber)
, _noteList(noteList)
{
setMusElementType(Tuplet);
assignTimes();
}
/*!
Constructs an empty tuplet.
Add notes and rests under it manually by calling addNote().
Call assignTimes() to apply the actual times then.
*/
CATuplet::CATuplet(int number, int actualNumber)
: CAMusElement(nullptr, 0, 0)
, _number(number)
, _actualNumber(actualNumber)
{
setMusElementType(Tuplet);
}
CATuplet::~CATuplet()
{
resetTimes();
}
CATuplet* CATuplet::clone(CAContext*)
{ // context is ignored. this method should not be used. FIXME.
/// \todo replace raw pointer with shared or unique pointer
return new CATuplet(number(), actualNumber(), noteList());
}
CATuplet* CATuplet::clone(QList<CAPlayable*> newList)
{
/// \todo replace raw pointer with shared or unique pointer
return new CATuplet(number(), actualNumber(), newList);
}
int CATuplet::compare(CAMusElement* elt)
{
int diff = 0;
if (elt->musElementType() != CAMusElement::Tuplet) {
return -1;
}
if (number() != static_cast<CATuplet*>(elt)->number())
diff++;
if (actualNumber() != static_cast<CATuplet*>(elt)->actualNumber())
diff++;
return diff;
}
/*!
Generates a list of pointers to slurs (slur start, slur end, phrasing slur
start, phrasing slur end) per each note index.
If tuplet contains a rest, no slurs are present at that index.
\sa assignNoteSlurs()
*/
QList<QList<CASlur*>> CATuplet::getNoteSlurs()
{
QList<QList<CASlur*>> noteSlurs;
for (int i = 0; i < noteList().size(); i++) {
noteSlurs << QList<CASlur*>();
if (noteList()[i]->musElementType() == Note) {
noteSlurs.back() << static_cast<CANote*>(noteList()[i])->slurStart();
noteSlurs.back() << static_cast<CANote*>(noteList()[i])->slurEnd();
noteSlurs.back() << static_cast<CANote*>(noteList()[i])->phrasingSlurStart();
noteSlurs.back() << static_cast<CANote*>(noteList()[i])->phrasingSlurEnd();
static_cast<CANote*>(noteList()[i])->setSlurStart(nullptr);
static_cast<CANote*>(noteList()[i])->setSlurEnd(nullptr);
static_cast<CANote*>(noteList()[i])->setPhrasingSlurStart(nullptr);
static_cast<CANote*>(noteList()[i])->setPhrasingSlurEnd(nullptr);
}
}
return noteSlurs;
}
/*!
Assigns the given list of slurs per note index.
This function is usually called in combination with getNoteSlurs() when
managing note timeStarts and notes are removed/readded to voices.
\sa getNoteSlurs()
*/
void CATuplet::assignNoteSlurs(QList<QList<CASlur*>> noteSlurs)
{
// assign previously remembered slurs
for (int i = 0; i < noteSlurs.size(); i++) {
if (noteSlurs[i].size()) {
if (noteSlurs[i][0]) {
static_cast<CANote*>(noteList()[i])->setSlurStart(noteSlurs[i][0]);
noteSlurs[i][0]->setTimeStart(noteList()[i]->timeStart());
noteSlurs[i][0]->setTimeLength(noteSlurs[i][0]->timeEnd() - noteList()[i]->timeStart());
}
if (noteSlurs[i][1]) {
static_cast<CANote*>(noteList()[i])->setSlurEnd(noteSlurs[i][1]);
noteSlurs[i][1]->setTimeLength(noteList()[i]->timeStart() - noteSlurs[i][1]->noteStart()->timeStart());
}
if (noteSlurs[i][2]) {
static_cast<CANote*>(noteList()[i])->setPhrasingSlurStart(noteSlurs[i][2]);
noteSlurs[i][2]->setTimeStart(noteList()[i]->timeStart());
noteSlurs[i][2]->setTimeLength(noteSlurs[i][2]->timeEnd() - noteList()[i]->timeStart());
}
if (noteSlurs[i][3]) {
static_cast<CANote*>(noteList()[i])->setPhrasingSlurEnd(noteSlurs[i][3]);
noteSlurs[i][3]->setTimeLength(noteList()[i]->timeStart() - noteSlurs[i][3]->noteStart()->timeStart());
}
}
}
}
/*!
Transforms note times to tuplet-affected times.
The use case should be somewhat this:
1) Place ordinary notes and rests.
2) Create a tuplet containing them. This calls assignTimes() automatically
to transform music elements times.
This function requires elements to be part of the voice.
\sa resetTimes()
*/
void CATuplet::assignTimes()
{
resetTimes();
CAVoice* voice = noteList().front()->voice();
CAMusElement* next = nullptr;
if (noteList().back()->musElementType() == Note && static_cast<CANote*>(noteList().back())->getChord().size()) {
next = voice->next(static_cast<CANote*>(noteList().back())->getChord().back());
} else { // rest
next = voice->next(noteList().back());
}
// removes notes from the voice
// but first remember the slurs and phrasing slurs
QList<QList<CASlur*>> noteSlurs = getNoteSlurs();
for (int i = noteList().size() - 1; i >= 0; i--) {
noteList()[i]->setTuplet(nullptr);
voice->remove(noteList()[i]);
}
for (int i = 0; i < noteList().size(); i++) {
noteList()[i]->setTimeStart(qRound(firstNote()->timeStart() + (noteList()[i]->timeStart() - firstNote()->timeStart()) * (static_cast<float>(actualNumber()) / number())));
}
for (int i = 0; i < noteList().size(); i++) {
int j = i + 1;
while (j < noteList().size() && (noteList()[j]->timeStart() == noteList()[i]->timeStart())) {
j++;
}
if (j < noteList().size()) {
noteList()[i]->setTimeLength(noteList()[j]->timeStart() - noteList()[i]->timeStart());
} else {
noteList()[i]->setTimeLength(qRound(CAPlayableLength::playableLengthToTimeLength(noteList()[i]->playableLength()) * (static_cast<float>(actualNumber()) / number())));
}
}
// adds notes back to the voice
for (int i = 0; i < noteList().size(); i++) {
voice->insert(next, noteList()[i]);
int j = 1;
for (; i + j < noteList().size() && noteList()[i + j]->timeStart() == noteList()[i]->timeStart(); j++) {
voice->insert(noteList()[i], noteList()[i + j], true);
}
i += (j - 1);
}
// assign previously remembered slurs
assignNoteSlurs(noteSlurs);
setTimeLength(noteList().last()->timeEnd() - noteList().front()->timeStart());
for (int i = 0; i < noteList().size(); i++) {
noteList()[i]->setTuplet(this);
}
if (noteList().size()) {
setContext(noteList()[0]->context());
}
}
/*!
Resets the notes times back to their original values before
placing the tuplet.
This is usually called from the destructor of the tuplet.
*/
void CATuplet::resetTimes()
{
if (noteList().isEmpty())
return;
CAVoice* voice = noteList().front()->voice();
CAMusElement* next = nullptr;
if (noteList().back()->musElementType() == Note && static_cast<CANote*>(noteList().back())->getChord().size()) {
next = voice->next(static_cast<CANote*>(noteList().back())->getChord().back());
} else { // rest
next = voice->next(noteList().back());
}
// removes notes from the voice
// but first remember the slurs and phrasing slurs
QList<QList<CASlur*>> noteSlurs = getNoteSlurs();
for (int i = noteList().size() - 1; i >= 0; i--) {
noteList()[i]->setTuplet(nullptr);
voice->remove(noteList()[i]);
}
for (int i = 0; i < noteList().size();) {
int newTimeStart = (i == 0) ? (noteList()[0]->timeStart()) : (noteList()[i - 1]->timeEnd());
QList<CAPlayable*> chord;
int j = 0;
for (; i + j < noteList().size() && noteList()[i + j]->timeStart() == noteList()[i]->timeStart(); j++) { // chord..
chord << noteList()[i + j];
}
for (int k = 0; k < chord.size(); k++) {
chord[k]->calculateTimeLength();
chord[k]->setTimeStart(newTimeStart);
}
i += j;
}
// adds notes back to the voice
for (int i = 0; i < noteList().size(); i++) {
voice->insert(next, noteList()[i]);
int j = 1;
for (; i + j < noteList().size() && noteList()[i + j]->timeStart() == noteList()[i]->timeStart(); j++) { // chord..
voice->insert(noteList()[i], noteList()[i + j], true);
}
i += (j - 1);
}
// assign previously remembered slurs
assignNoteSlurs(noteSlurs);
}
/*!
Adds a note to the tuplet.
*/
void CATuplet::addNote(CAPlayable* p)
{
int i;
for (i = 0; i < noteList().size() && noteList()[i]->timeStart() <= p->timeStart() && (noteList()[i]->musElementType() != Note || noteList()[i]->timeStart() != p->timeStart() || static_cast<CANote*>(noteList()[i])->diatonicPitch().noteName() < static_cast<CANote*>(p)->diatonicPitch().noteName()); i++)
;
_noteList.insert(i, p);
}
/*!
Returns a pointer to the next member of tuplet with a greater timeStart.
If it doesn't exist it returns nullptr.
*/
CAPlayable* CATuplet::nextTimed(CAPlayable* p)
{
int t = p->timeStart();
for (int i = 0; i < noteList().size(); i++) {
if (noteList()[i]->timeStart() > t)
return noteList()[i];
}
return nullptr;
}
/*!
Returns the first note/rest in the first chord of the tuplet.
*/
CAPlayable* CATuplet::firstNote()
{
if (noteList().isEmpty())
return nullptr;
if (noteList().first()->musElementType() == CAMusElement::Note && !static_cast<CANote*>(noteList().first())->getChord().isEmpty()) {
return static_cast<CANote*>(noteList().first())->getChord().first();
} else {
return noteList().first();
}
}
/*!
Returns the last note/rest in the last chord of the tuplet.
*/
CAPlayable* CATuplet::lastNote()
{
if (noteList().isEmpty())
return nullptr;
if (noteList().last()->musElementType() == CAMusElement::Note && !static_cast<CANote*>(noteList().last())->getChord().isEmpty()) {
return static_cast<CANote*>(noteList().last())->getChord().last();
} else {
return noteList().last();
}
}
int CATuplet::timeLength() const
{
if (noteList().size()) {
return (noteList().back()->timeEnd() - timeStart());
} else {
return 0;
}
}
int CATuplet::timeStart() const
{
if (noteList().size()) {
return noteList()[0]->timeStart();
} else {
return 0;
}
}
| 11,503
|
C++
|
.cpp
| 300
| 32.703333
| 305
| 0.618064
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,358
|
midinote.cpp
|
canorusmusic_canorus/src/score/midinote.cpp
|
/*!
Copyright (c) 2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/midinote.h"
/*!
\class CAMidiNote
\brief Represents a note with custom length and Midi-defined pitch
This class is usually used when a composer wants to import his improvisations
and the input Midi files are naturally recorded and are too difficult to quantize.
However, composer wants to see his recorded notes in the staff so he can transcribe
the prototype improvisation into actual notes.
The CAMidiNote class represents a Midi Note-On/Note-Off pair of events with defined
timeStart, timeLength and Midi pitch. The class is usually used to graphically
display the recorded Midi events in the staff and nothing more.
*/
CAMidiNote::CAMidiNote(int midiPitch, int timeStart, int timeLength, CAVoice* voice)
: CAPlayable(CAPlayableLength::Undefined, voice, timeStart, timeLength)
, _midiPitch(midiPitch)
{
setMusElementType(MidiNote);
}
CAMidiNote::~CAMidiNote()
{
}
CAMidiNote* CAMidiNote::clone(CAVoice* v)
{
return new CAMidiNote(midiPitch(), timeStart(), timeLength(), v);
}
int CAMidiNote::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::MidiNote) {
return -1;
} else if (static_cast<CAMidiNote*>(elt)->midiPitch() != midiPitch()) {
return 1;
} else {
return 0;
}
}
| 1,497
|
C++
|
.cpp
| 40
| 34.525
| 84
| 0.759144
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,359
|
clef.cpp
|
canorusmusic_canorus/src/score/clef.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/clef.h"
#include "score/mark.h"
#include "score/staff.h"
/*!
\class CAClef
Represents a clef in the score
This class represents every clef in the score. It directly inherits the base class
CAMusElement. Element is not playable (_timeLength=0).
*/
/*!
Creates a new predefined clef with type \a type, parent \a staff and start time \a time.
_timeLength is set to 0.
\a offsetInterval can be custom -1,0,1 no offset, +8 or -8 etc. mean the 8 written above or below the clef which raises or
lowers the clef for one octave or whichever interval. Offset is the musical interval, not the internal offset.
\sa CAPredefinedClefType, CAMusElement
*/
CAClef::CAClef(CAPredefinedClefType type, CAStaff* staff, int time, int offsetInterval)
: CAMusElement(staff, time)
{
_musElementType = CAMusElement::Clef;
_offset = CAClef::offsetFromReadable(offsetInterval);
setPredefinedType(type);
}
/*!
Creates a new clef with type \a type, location of middle C \a c1, time start \a time and parent \a staff.
\a offset is the internal clef offset 0, +7, -7 etc. It does not affect c1.
\sa CAPredefinedClefType, CAMusElement
*/
CAClef::CAClef(CAClefType type, int c1, CAStaff* staff, int time, int offset)
: CAMusElement(staff, time)
{
_musElementType = CAMusElement::Clef;
_c1 = c1;
_offset = offset;
setClefType(type);
}
void CAClef::setPredefinedType(CAPredefinedClefType type)
{
switch (type) {
case Treble:
setClefType(G);
_c1 = -2 - offset();
break;
case Bass:
setClefType(F);
_c1 = 10 - offset();
break;
case French:
setClefType(G);
_c1 = -4 - offset();
break;
case Soprano:
setClefType(C);
_c1 = 0 - offset();
break;
case Mezzosoprano:
setClefType(C);
_c1 = 2 - offset();
break;
case Alto:
setClefType(C);
_c1 = 4 - offset();
break;
case Tenor:
setClefType(C);
_c1 = 6 - offset();
break;
case Baritone:
setClefType(C);
_c1 = 8 - offset();
break;
case Varbaritone:
setClefType(F);
_c1 = 8 - offset();
break;
case Subbass:
setClefType(F);
_c1 = 12 - offset();
break;
case Undefined:
case Percussion:
case Tablature:
break;
}
}
/*!
Sets the clef type to \a type and update _c1 and _centerPitch.
\sa CAClefType, _clefType
*/
void CAClef::setClefType(CAClefType type)
{
_clefType = type;
switch (type) {
case G:
_centerPitch = 32;
break;
case F:
_centerPitch = 24;
break;
case C:
_centerPitch = 28;
break;
case PercussionHigh:
case PercussionLow:
case Tab:
break;
}
_centerPitch += offset();
}
CAClef* CAClef::clone(CAContext* context)
{
CAClef* c = new CAClef(_clefType, _c1, static_cast<CAStaff*>(context), _timeStart, _offset);
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(c));
c->addMark(m);
}
return c;
}
int CAClef::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Clef)
return -1;
int diffs = 0;
if (_clefType != static_cast<CAClef*>(elt)->clefType())
diffs++;
if (_offset != static_cast<CAClef*>(elt)->offset())
diffs++;
if (_c1 != static_cast<CAClef*>(elt)->c1())
diffs++;
return diffs;
}
/*!
Converts clef \a type to QString.
\sa CAClefType, clefTypeFromString()
*/
const QString CAClef::clefTypeToString(CAClefType type)
{
switch (type) {
case G:
return "G";
case F:
return "F";
case C:
return "C";
case PercussionHigh:
return "percussion-high";
case PercussionLow:
return "percussion-low";
case Tab:
return "tab";
}
return "";
}
/*!
Converts QString \a type to clef type.
\sa CAClefType, clefTypeToString()
*/
CAClef::CAClefType CAClef::clefTypeFromString(const QString type)
{
if (type == "G")
return G;
else if (type == "F")
return F;
else if (type == "C")
return C;
else if (type == "percussion-high")
return PercussionHigh;
else if (type == "percussion-low")
return PercussionLow;
else if (type == "tab")
return Tab;
else
return G;
}
/*!
Converts the internal clef offset to the musical interval.
eg. offset +1 means +2 (supper second),
+7 means +8 (supper octave),
-7 means -8 (sub octave),
0 is an exception and stays 0 (instead of prime)
This method is usually called when displaying the offset of the key (eg. when rendering it).
\sa offsetFromReadable()
*/
int CAClef::offsetToReadable(const int offsetInterval)
{
if (!offsetInterval)
return 0;
return offsetInterval + offsetInterval / qAbs(offsetInterval);
}
/*!
Converts the musical interval offset to Canorus internal offset.
This method is usually called where user inputs the offset interval and it needs to be stored.
\sa offsetToReadable()
*/
int CAClef::offsetFromReadable(const int offset)
{
if (qAbs(offset) == 1 || !offset)
return 0;
return offset - offset / qAbs(offset);
}
/*!
\var CAClef::_c1
Location of the middle C:
- 0 - 1st line
- 1 - 1st space
- -2 - 1st ledger line below staff (ie. C1 in treble clef) etc.
\sa c1(), _centerPitch
*/
/*!
\var CAClef::_centerPitch
Location of the clefs physical center:
- 24 - f for bass clef
- 32 - g for treble clef
- 28 - middle C for c-clefs etc.
This is needed for Y position in the staff calculation.
\sa centerPitch(), _c1
*/
| 5,994
|
C++
|
.cpp
| 222
| 22.184685
| 123
| 0.641039
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,360
|
slur.cpp
|
canorusmusic_canorus/src/score/slur.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/slur.h"
#include "score/note.h"
/*!
\class CASlur
\brief Slur, Tie, Phrasing slur and Laissez vibrer tie
This class represents any type of slur.
Holds pointers to the first and last notes.
\sa CANote::_slurStart, \sa CANote::_tieStart, \sa CANote::_phrasingSlurStart
*/
/*!
\enum CASlur::CASlurDirection
\brief Direction of the slur
This type represents the direction of the note's slur.
Possible values:
- SlurUp
Slur high point above the left and right points.
- SlurDown
Slur high point below the left and right points.
- SlurNeutral
Slur on the oposite side of the stem.
- SlurPreferred
Slur direction determined by CANote::determineSlurDirection() (default)
*/
/*!
Default constructor.
*/
CASlur::CASlur(CASlurType type, CASlurDirection dir, CAContext* c, CANote* noteStart, CANote* noteEnd, CASlurStyle style)
: CAMusElement(c, noteStart->timeStart(), 0)
{
setMusElementType(CAMusElement::Slur);
setSlurDirection(dir);
setSlurType(type);
setSlurStyle(style);
setNoteStart(noteStart);
setNoteEnd(noteEnd);
if (noteEnd)
setTimeLength(noteEnd->timeStart() - noteStart->timeStart());
else
setTimeLength(noteStart->timeLength());
}
CASlur::~CASlur()
{
switch (slurType()) {
case TieType:
if (noteStart())
noteStart()->setTieStart(nullptr);
if (noteEnd())
noteEnd()->setTieEnd(nullptr);
break;
case SlurType:
if (noteStart())
noteStart()->setSlurStart(nullptr);
if (noteEnd())
noteEnd()->setSlurEnd(nullptr);
break;
case PhrasingSlurType:
if (noteStart())
noteStart()->setPhrasingSlurStart(nullptr);
if (noteEnd())
noteEnd()->setPhrasingSlurEnd(nullptr);
break;
}
}
// FIXME copying noteStart/End pointers.
CASlur* CASlur::clone(CAContext* context)
{
return new CASlur(slurType(), slurDirection(), context, noteStart(), noteEnd(), slurStyle());
}
CASlur* CASlur::clone(CAContext* context, CANote* noteStart, CANote* noteEnd)
{
return new CASlur(slurType(), slurDirection(), context, noteStart, noteEnd, slurStyle());
}
int CASlur::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Slur)
return -1;
int diffs = 0;
if (slurDirection() != static_cast<CASlur*>(elt)->slurDirection())
diffs++;
return diffs;
}
const QString CASlur::slurStyleToString(CASlur::CASlurStyle style)
{
switch (style) {
case SlurSolid:
return "slur-solid";
case SlurDotted:
return "slur-dotted";
case Undefined:
break;
}
return "";
}
CASlur::CASlurStyle CASlur::slurStyleFromString(const QString style)
{
if (style == "slur-solid")
return SlurSolid;
else if (style == "slur-dotted")
return SlurDotted;
return Undefined;
}
const QString CASlur::slurDirectionToString(CASlur::CASlurDirection dir)
{
switch (dir) {
case SlurUp:
return "slur-up";
case SlurDown:
return "slur-down";
case SlurNeutral:
return "slur-neutral";
case SlurPreferred:
return "slur-preferred";
}
return "";
}
CASlur::CASlurDirection CASlur::slurDirectionFromString(const QString dir)
{
if (dir == "slur-up")
return SlurUp;
else if (dir == "slur-down")
return SlurDown;
else if (dir == "slur-neutral")
return SlurNeutral;
else if (dir == "slur-pereferred")
return SlurPreferred;
return SlurPreferred;
}
| 3,797
|
C++
|
.cpp
| 132
| 23.969697
| 121
| 0.680582
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,361
|
context.cpp
|
canorusmusic_canorus/src/score/context.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/context.h"
/*!
\class CAContext
\brief Line of music elements in the sheet
CAContext represents usually an infinite graphical space on the sheet where music elements are
placed in. This idea was introduced by LilyPond and it turned out to be quite useful.
Contexts can be staffs, lyrics, figured bass context, function mark context, dynamics etc.
CAContext is an abstract class and different solutions should be done based on it.
\sa CAStaff, CAFunctionMarkContext
*/
/*!
Creates a context named \a name and with parent sheet \a s.
*/
CAContext::CAContext(const QString name, CASheet* s)
{
_sheet = s;
_name = name;
}
CAContext::~CAContext()
{
}
/*!
\enum CAContext::CAContextType
This enum holds different CAContext types:
- Staff
Every context with lines which includes various music elements.
- Tablature
Context similar to Staff, but specialized for guitar.
- Lyrics
Holds words (syllables) for choir music. Every syllable is assigned to certain CANote.
- Dynamics
Sometimes we want to have a separate context for the crescendo, rit., mf and other marks
*/
/*!
\fn CAContext::name()
Returns context's name.
\sa setName(), _name
*/
/*!
\fn CAContext::setName(const QString name)
Sets the Context's name to \a name.
\sa name(), _name
*/
/*!
\fn CAContext::findNextMusElement(CAMusElement *elt)
Finds the next music element to the given \a elt and returns its pointer.
This method is usually used when walking through notes using cursor keys.
Returns pointer to the elements \a elt right neighbour or 0, if the right neighbour doesn't
exist.
\sa findPrevMusElement()
*/
/*!
\fn CAContext::findPrevMusElement(CAMusElement *elt)
Finds the previous music element to the given \a elt and returns its pointer.
This method is usually used when walking through notes using cursor keys.
Returns pointer to the elements \a elt left neighbour or 0, if the left neighbour doesn't exist.
\sa findNextMusElement()
*/
/*!
\fn CAContext::removeMusElement(CAMusElement *elt, bool cleanup)
Removes the music element \a elt from the context.
Destroys the object as well, if \a cleanup is true (default).
Returns true, if the element was found and removed; otherwise false.
*/
/*!
\fn CAContext::sheet()
Returns the pointer to CASheet which this context belongs to.
\sa setSheet(), _sheet
*/
/*!
\fn CAContext::setSheet(CASheet *sheet)
Sets the context's parent sheet to \a sheet.
\sa sheet(), _sheet
*/
/*!
\fn CAContext::clone( CASheet *s )
Clones the current context with the given parent sheet \a s.
\sa CAMusElement::clone(), CADocument::clone()
*/
/*!
\fn CAContext::insertEmptyElement(int timeStart)
Inserts an empty dependent element (syllable, chord name, figured bass mark, function mark) to the context.
After the call the elements need to be repositioned manually (subsequent timeStarts and timeLengths will be out of place).
This function is usually called when initializing the dependent context or inserting a new note.
\sa CAContext::repositionElements()
*/
/*!
\fn CAContext::repositionElements()
Repositions the existing dependent elements (syllables, chord names, figured bass marks, function marks) by setting timeStart and timeLength
one by one according to the playable music it depends on. The order is preserved.
\sa CAContext::insertEmptyElement(int)
*/
| 3,631
|
C++
|
.cpp
| 97
| 35
| 144
| 0.766419
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,362
|
figuredbasscontext.cpp
|
canorusmusic_canorus/src/score/figuredbasscontext.cpp
|
/*!
Copyright (c) 2009-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/figuredbasscontext.h"
#include "score/figuredbassmark.h"
#include "score/playable.h"
#include "score/playablelength.h"
#include "score/sheet.h"
/*!
\class CAFiguredBassContext
\brief Context for keeping the figured bass marks
This class represents a container for the figured bass (or general bass) marks.
It is somehow similar to CALyricsContext in terms of use.
The class keeps all figured bass marks in a single list. No specific times are stored.
This is because exactly one figured bass mark is assigned to every chord.
*/
CAFiguredBassContext::CAFiguredBassContext(QString name, CASheet* sheet)
: CAContext(name, sheet)
{
setContextType(FiguredBassContext);
repositionElements();
}
CAFiguredBassContext::~CAFiguredBassContext()
{
clear();
}
/*!
Inserts the given figured bass mark \a m according to its timeStart.
Replaces any existing figured bass marks at that time, if \a replace is True (default).
*/
void CAFiguredBassContext::addFiguredBassMark(CAFiguredBassMark* m, bool replace)
{
int i;
for (i = 0; i < _figuredBassMarkList.size() && _figuredBassMarkList[i]->timeStart() < m->timeStart(); i++)
;
//int s = _figuredBassMarkList.size();
if (i < _figuredBassMarkList.size() && replace) {
delete _figuredBassMarkList.takeAt(i);
}
_figuredBassMarkList.insert(i, m);
for (i++; i < _figuredBassMarkList.size(); i++)
_figuredBassMarkList[i]->setTimeStart(_figuredBassMarkList[i]->timeStart() + m->timeLength());
}
/*!
Returns figured bass mark at the given \a time.
*/
CAFiguredBassMark* CAFiguredBassContext::figuredBassMarkAtTimeStart(int time)
{
int i;
for (i = 0; i < _figuredBassMarkList.size() && _figuredBassMarkList[i]->timeStart() <= time; i++)
;
if (i > 0 && _figuredBassMarkList[--i]->timeEnd() > time) {
return _figuredBassMarkList[i];
} else {
return nullptr;
}
}
CAContext* CAFiguredBassContext::clone(CASheet* s)
{
CAFiguredBassContext* newFbc = new CAFiguredBassContext(name(), s);
for (int i = 0; i < _figuredBassMarkList.size(); i++) {
CAFiguredBassMark* newFbm = static_cast<CAFiguredBassMark*>(_figuredBassMarkList[i]->clone(newFbc));
newFbc->addFiguredBassMark(newFbm);
}
return newFbc;
}
void CAFiguredBassContext::clear()
{
while (!_figuredBassMarkList.isEmpty())
delete _figuredBassMarkList.takeFirst();
}
CAMusElement* CAFiguredBassContext::next(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::FiguredBassMark)
return nullptr;
int i = _figuredBassMarkList.indexOf(static_cast<CAFiguredBassMark*>(elt));
if (i != -1 && ++i < _figuredBassMarkList.size())
return _figuredBassMarkList[i];
else
return nullptr;
}
CAMusElement* CAFiguredBassContext::previous(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::FiguredBassMark)
return nullptr;
int i = _figuredBassMarkList.indexOf(static_cast<CAFiguredBassMark*>(elt));
if (i != -1 && --i > -1)
return _figuredBassMarkList[i];
else
return nullptr;
}
bool CAFiguredBassContext::remove(CAMusElement* elt)
{
if (!elt || elt->musElementType() != CAMusElement::FiguredBassMark)
return false;
bool success = false;
success = _figuredBassMarkList.removeAll(static_cast<CAFiguredBassMark*>(elt));
if (success)
delete elt;
return success;
}
CAMusElement *CAFiguredBassContext::insertEmptyElement(int timeStart)
{
CAFiguredBassMark *newElt = new CAFiguredBassMark(this, timeStart, 1);
int i;
for (i = 0; i < _figuredBassMarkList.size() && _figuredBassMarkList[i]->timeStart() < timeStart; i++)
;
_figuredBassMarkList.insert(i, newElt);
for (i++; i < _figuredBassMarkList.size(); i++)
_figuredBassMarkList[i]->setTimeStart(_figuredBassMarkList[i]->timeStart() + 1);
return newElt;
}
void CAFiguredBassContext::repositionElements()
{
if (!sheet()) {
return;
}
QList<CAPlayable*> chord = sheet()->getChord(0);
int fbmIdx = 0;
while (chord.size()) {
int maxTimeStart = chord[0]->timeStart();
int minTimeEnd = chord[0]->timeEnd();
bool notes = false; // are notes present in the chord or only rests?
for (int i = 1; i < chord.size(); i++) {
if (chord[i]->musElementType() == CAMusElement::Note) {
notes = true;
}
if (chord[i]->timeStart() > maxTimeStart) {
maxTimeStart = chord[i]->timeStart();
}
if (chord[i]->timeEnd() < minTimeEnd) {
minTimeEnd = chord[i]->timeEnd();
}
}
// only assign figured bass marks under the notes
if (notes) {
// add new empty figured bass, if none exist
if (fbmIdx == _figuredBassMarkList.size()) {
insertEmptyElement(maxTimeStart);
}
CAFiguredBassMark* mark = _figuredBassMarkList[fbmIdx];
mark->setTimeStart(maxTimeStart);
mark->setTimeLength(minTimeEnd - maxTimeStart);
fbmIdx++;
}
chord = sheet()->getChord(minTimeEnd);
}
// updated times for the figured bass marks at the end (after the score)
for (; fbmIdx < _figuredBassMarkList.size(); fbmIdx++) {
_figuredBassMarkList[fbmIdx]->setTimeStart(((fbmIdx > 0) ? _figuredBassMarkList[fbmIdx - 1] : _figuredBassMarkList[0])->timeEnd());
_figuredBassMarkList[fbmIdx]->setTimeLength(CAPlayableLength::Quarter);
}
}
| 5,820
|
C++
|
.cpp
| 155
| 31.987097
| 139
| 0.672876
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,363
|
functionmark.cpp
|
canorusmusic_canorus/src/score/functionmark.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/functionmark.h"
#include "score/functionmarkcontext.h"
#include "score/mark.h"
/*!
\class CAFunctionMark
\brief Represents a function mark in the score
Function marks are used to describe a harmony flow of the score.
Current implementation uses a standard European-German nomenclature of harmony.
\todo Current translations of terms are mostly done "by heart". An English/Amercian
composer or musicologist should translate attributes the best. -Matevz
\sa CADrawableFunctionMark, CAFunctionMarkContext
*/
CAFunctionMark::CAFunctionMark(CAFunctionType function, bool minor, const CADiatonicKey key, CAFunctionMarkContext* context, int timeStart, int timeLength, CAFunctionType chordArea, bool chordAreaMinor, CAFunctionType tonicDegree, bool tonicDegreeMinor, const QString alterations, bool ellipseSequence)
: CAMusElement(context, timeStart, timeLength)
{
_musElementType = CAMusElement::FunctionMark;
_function = function;
_tonicDegree = tonicDegree;
_tonicDegreeMinor = tonicDegreeMinor;
_key = key;
_chordArea = chordArea;
_chordAreaMinor = chordAreaMinor;
_minor = minor;
_ellipseSequence = ellipseSequence;
setAlterations(alterations);
}
CAFunctionMark::~CAFunctionMark()
{
}
bool CAFunctionMark::isSideDegree()
{
if (_function == I || _function == II || _function == III || _function == IV || _function == V || _function == VI || _function == VII)
return true;
else
return false;
}
CAFunctionMark* CAFunctionMark::clone(CAContext* context)
{
CAFunctionMark* newElt;
newElt = new CAFunctionMark(function(), isMinor(), key(), static_cast<CAFunctionMarkContext*>(context), timeStart(), timeLength(), chordArea(), isChordAreaMinor(), tonicDegree(), isTonicDegreeMinor(), "", isPartOfEllipse());
newElt->setAlteredDegrees(_alteredDegrees);
newElt->setAddedDegrees(_addedDegrees);
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(newElt));
newElt->addMark(m);
}
return newElt;
}
void CAFunctionMark::clear()
{
setFunction(Undefined);
setChordArea(Undefined);
setTonicDegree(T);
setKey(CADiatonicKey("C"));
}
int CAFunctionMark::compare(CAMusElement* func)
{
int diffs = 0;
if (func->musElementType() != CAMusElement::FunctionMark)
return -1;
CAFunctionMark* fm = static_cast<CAFunctionMark*>(func);
if (fm->function() != function())
diffs++;
if (fm->chordArea() != chordArea())
diffs++;
if (fm->tonicDegree() != tonicDegree())
diffs++;
if (fm->key() != key())
diffs++;
if (fm->addedDegrees() != addedDegrees())
diffs++;
if (fm->alteredDegrees() != alteredDegrees())
diffs++;
return diffs;
}
/*!
Reads \a alterations and sets alteredDegrees and addedDegrees.
Sixte ajoutee and other added degrees have +/- sign after the number.
Stable alterations have +/- sign before the number.
\a alterations consists first of added degrees and then altered degrees.
*/
void CAFunctionMark::setAlterations(const QString alterations)
{
if (alterations.isEmpty())
return;
int i = 0; //index of the first character that belongs to the degree
int rightIdx;
//added degrees:
_addedDegrees.clear();
while (i < alterations.size() && alterations[i] != '+' && alterations[i] != '-') {
if (alterations.indexOf('+', i + 1) == -1)
rightIdx = alterations.indexOf('-', i + 1);
else if (alterations.indexOf('-', i + 1) == -1)
rightIdx = alterations.indexOf('+', i + 1);
else
rightIdx = alterations.indexOf('+', i + 1) < alterations.indexOf('-', i + 1) ? alterations.indexOf('+', i + 1) : alterations.indexOf('-', i + 1);
QString curDegree = alterations.mid(i, rightIdx - i + 1);
curDegree.insert(0, curDegree[curDegree.size() - 1]); // move the last + or - before the string
curDegree.chop(1);
_addedDegrees << curDegree.toInt();
i = rightIdx + 1;
}
// altered degrees:
_alteredDegrees.clear();
while (i < alterations.size()) {
if (alterations.indexOf('+', i + 1) == -1 && alterations.indexOf('-', i + 1) != -1)
rightIdx = alterations.indexOf('-', i + 1);
else if (alterations.indexOf('-', i + 1) == -1 && alterations.indexOf('+', i + 1) != -1)
rightIdx = alterations.indexOf('+', i + 1);
else if (alterations.indexOf('-', i + 1) != -1 && alterations.indexOf('+', i + 1) != -1)
rightIdx = alterations.indexOf('+', i + 1) < alterations.indexOf('-', i + 1) ? alterations.indexOf('+', i + 1) : alterations.indexOf('-', i + 1);
else
rightIdx = alterations.size();
_alteredDegrees << alterations.mid(i, rightIdx - i).toInt();
i = rightIdx;
}
}
const QString CAFunctionMark::functionTypeToString(CAFunctionMark::CAFunctionType type)
{
switch (type) {
case T:
return "T";
case S:
return "S";
case D:
return "D";
case I:
return "I";
case II:
return "II";
case III:
return "III";
case IV:
return "IV";
case V:
return "V";
case VI:
return "VI";
case VII:
return "VII";
case N:
return "N";
case F:
return "F";
case L:
return "L";
case K:
return "K";
case Undefined:
return "undefined";
}
return "undefined";
}
CAFunctionMark::CAFunctionType CAFunctionMark::functionTypeFromString(const QString type)
{
if (type == "T")
return T;
else if (type == "S")
return S;
else if (type == "D")
return D;
else if (type == "I")
return I;
else if (type == "II")
return II;
else if (type == "III")
return III;
else if (type == "IV")
return IV;
else if (type == "V")
return V;
else if (type == "VI")
return VI;
else if (type == "VII")
return VII;
else if (type == "N")
return N;
else if (type == "L")
return L;
else if (type == "F")
return F;
else if (type == "K")
return K;
else if (type == "undefined")
return Undefined;
return Undefined;
}
/*!
\enum CAFunctionMark::CAFunctionType
Name of the function (tonic, subdominant, etc.), its chord area or the tonic degree.
Possible names are:
- Undefined
no degree - extend the previous one
- I
1st (usually never used)
- II
2nd
- III
3rd
- IV
4th (no subdominant leading tone in minor key)
- V
5th (no dominant leading tone in minor key)
- VI
6th
- VII
7th
- T
Tonic
- S
Subdominant
- D
Dominant
- F
Phrygian (F for Frigio in Italian)
- N
Napolitan
- L
Lidian
- K
Cadenze chord (see http://en.wikipedia.org/wiki/Cadence_%28music%29). K stands for "kadenze" in German. This is standard nomenclature.
*/
| 7,215
|
C++
|
.cpp
| 227
| 26.647577
| 302
| 0.636873
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,364
|
text.cpp
|
canorusmusic_canorus/src/score/text.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/text.h"
#include "score/playable.h"
/*!
\class CAText
\brief Text sign
Arbitrary text above or below playable elements.
Playable elements are required since Lilypond is not able to easily assign
arbitrary text on non-playable ones.
*/
CAText::CAText(const QString s, CAPlayable* t)
: CAMark(CAMark::Text, t)
{
setText(s);
}
CAText::~CAText()
{
}
CAText* CAText::clone(CAMusElement* elt)
{
return new CAText(text(), (elt->isPlayable()) ? static_cast<CAPlayable*>(elt) : nullptr);
}
int CAText::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
if (static_cast<CAMark*>(elt)->markType() != CAMark::Text)
return -1;
if (static_cast<CAText*>(elt)->text() != text())
return 1;
return 0;
}
| 1,025
|
C++
|
.cpp
| 36
| 25.5
| 93
| 0.708589
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,365
|
figuredbassmark.cpp
|
canorusmusic_canorus/src/score/figuredbassmark.cpp
|
/*!
Copyright (c) 2009-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/figuredbassmark.h"
#include "score/figuredbasscontext.h"
CAFiguredBassMark::CAFiguredBassMark(CAFiguredBassContext* c, int timeStart, int timeLength)
: CAMusElement(c, timeStart, timeLength)
{
setMusElementType(FiguredBassMark);
}
CAFiguredBassMark::~CAFiguredBassMark()
{
if (_context) {
_context->remove(this);
}
}
/*!
Adds or replaces the given figured bass \a number.
The new number will not contain any accidentals.
Allowed values are from 1 to 15.
*/
void CAFiguredBassMark::addNumber(int number)
{
insertNumber(number);
if (_accs.contains(number)) {
_accs.remove(number);
}
}
/*!
Adds or replaces the given figured bass \a number.
Allowed values are from 0 (no number) to 15.
Show the accidental \a accs:
- +1 for one sharp
- +2 for two sharps
- 0 for neutral
- -1 for one flat
- -2 for two flats
*/
void CAFiguredBassMark::addNumber(int number, int accs)
{
insertNumber(number);
_accs[number] = accs;
}
/*!
Removes the given figured bass \a number and its accidental.
*/
void CAFiguredBassMark::removeNumber(int number)
{
_numbers.removeAll(number);
_accs.remove(number);
}
/*!
Inserts or replaces the given \a number into a sorted list of numbers.
*/
void CAFiguredBassMark::insertNumber(int number)
{
if (!_numbers.contains(number)) {
// numbers must be sorted
int i;
for (i = 0; i < _numbers.size() && _numbers[i] < number; i++)
;
_numbers.insert(i, number);
}
}
CAMusElement* CAFiguredBassMark::clone(CAContext* context)
{
if (context && context->contextType() != CAContext::FiguredBassContext) {
return nullptr;
}
CAFiguredBassMark* fbm = new CAFiguredBassMark(static_cast<CAFiguredBassContext*>(context), timeStart(), timeLength());
for (int i = 0; i < _numbers.size(); i++) {
if (_accs.contains(_numbers[i])) {
fbm->addNumber(_numbers[i], _accs[_numbers[i]]);
} else {
fbm->addNumber(_numbers[i]);
}
}
return fbm;
}
int CAFiguredBassMark::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::FiguredBassMark) {
return -1;
}
int diff = 0;
CAFiguredBassMark* other = static_cast<CAFiguredBassMark*>(elt);
diff += qAbs(other->numbers().size() - numbers().size());
if (diff) {
return diff;
}
for (int i = 0; i < numbers().size(); i++) {
if (numbers()[i] != other->numbers()[i]) {
diff++;
}
if (accs()[numbers()[i]] != other->accs()[other->numbers()[i]]) {
diff++;
}
}
return diff;
}
| 2,885
|
C++
|
.cpp
| 102
| 23.95098
| 123
| 0.65521
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,366
|
staff.cpp
|
canorusmusic_canorus/src/score/staff.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QtDebug>
#include <QPainter>
#include <iostream>
#include "score/note.h"
#include "score/rest.h" // used for voice synchronization
#include "score/staff.h"
#include "score/tempo.h"
#include "score/tuplet.h"
#include "score/voice.h"
#include "score/barline.h"
#include "score/timesignature.h"
/*!
\class CAStaff
\brief Represents a staff in the sheet
This class represents usually an infinite long n-line staff where notes, rests, barlines, clefs and
other music elements are placed.
CAStaff is by hierarchy part of CASheet and can include various number of CAVoice objects.
\sa CADrawableStaff, CASheet, CAVoice
*/
/*!
Creates a new empty staff with parent sheet \a s, named \a name and \a numberOfLines.
\warning By default, no voices are created where music elements can be put. Use addVoice() to
append a new voice.
*/
CAStaff::CAStaff(const QString name, CASheet* s, int numberOfLines)
: CAContext(name, s)
{
_contextType = CAContext::Staff;
_numberOfLines = numberOfLines;
_name = name;
}
CAStaff::~CAStaff()
{
clear();
}
CAStaff* CAStaff::clone(CASheet* s)
{
CAStaff* newStaff = new CAStaff(name(), s, numberOfLines());
// create empty voices
for (int i = 0; i < voiceList().size(); i++) {
newStaff->addVoice(voiceList()[i]->clone(newStaff));
}
int* peltIdx = new int[voiceList().size()];
for (int i = 0; i < voiceList().size(); i++)
peltIdx[i] = 0;
QList<CANote*> tiedOrigNotes; // original notes having opened tie
QList<CANote*> sluredOrigNotes; // original notes having opened slur
QList<CANote*> phrasingSluredOrigNotes; // original notes having opened phrasing slur
QList<CANote*> tiedClonedNotes; // cloned notes having opened tie
QList<CANote*> sluredClonedNotes; // cloned notes having opened slur
QList<CANote*> phrasingSluredClonedNotes; // cloned notes having opened phrasing slur
bool done = false;
while (!done) {
// append playable elements
for (int i = 0; i < voiceList().size(); i++) {
QList<CAPlayable*> elementsUnderTuplet;
// clone elements in the current voice until the non-playable element is reached
while (peltIdx[i] < voiceList()[i]->musElementList().size() && voiceList()[i]->musElementList()[peltIdx[i]]->isPlayable()) {
CAPlayable* origElt = static_cast<CAPlayable*>(voiceList()[i]->musElementList()[peltIdx[i]]);
CAPlayable* clonedElt = origElt->clone(newStaff->voiceList()[i]);
newStaff->voiceList()[i]->append(clonedElt,
voiceList()[i]->musElementList()[peltIdx[i]]->musElementType() == CAMusElement::Note && static_cast<CANote*>(origElt)->isPartOfChord() && !static_cast<CANote*>(origElt)->isFirstInChord());
if (origElt->musElementType() == CAMusElement::Note) {
CANote* origNote = static_cast<CANote*>(origElt);
CANote* clonedNote = static_cast<CANote*>(clonedElt);
// check starting ties, slurs, prasing slurs
for (int i = 0; i < tiedOrigNotes.size(); i++) {
if (tiedOrigNotes[i]->tieStart()->noteEnd() == origNote) {
CASlur* newTie = tiedOrigNotes[i]->tieStart()->clone(newStaff);
tiedClonedNotes[i]->setTieStart(newTie);
newTie->setNoteStart(tiedClonedNotes[i]);
newTie->setNoteEnd(clonedNote);
clonedNote->setTieEnd(newTie);
tiedOrigNotes.removeAt(i);
tiedClonedNotes.removeAt(i);
}
}
for (int i = 0; i < sluredOrigNotes.size(); i++) {
if (sluredOrigNotes[i]->slurStart()->noteEnd() == origNote) {
CASlur* newSlur = sluredOrigNotes[i]->slurStart()->clone(newStaff);
sluredClonedNotes[i]->setSlurStart(newSlur);
newSlur->setNoteStart(sluredClonedNotes[i]);
newSlur->setNoteEnd(clonedNote);
clonedNote->setSlurEnd(newSlur);
sluredOrigNotes.removeAt(i);
sluredClonedNotes.removeAt(i);
}
}
for (int i = 0; i < phrasingSluredOrigNotes.size(); i++) {
if (phrasingSluredOrigNotes[i]->phrasingSlurStart()->noteEnd() == origNote) {
CASlur* newPhrasingSlur = phrasingSluredOrigNotes[i]->phrasingSlurStart()->clone(newStaff);
phrasingSluredClonedNotes[i]->setPhrasingSlurStart(newPhrasingSlur);
newPhrasingSlur->setNoteStart(phrasingSluredClonedNotes[i]);
newPhrasingSlur->setNoteEnd(clonedNote);
clonedNote->setPhrasingSlurEnd(newPhrasingSlur);
phrasingSluredOrigNotes.removeAt(i);
phrasingSluredClonedNotes.removeAt(i);
}
}
// check ending ties, slurs, phrasing slurs
if (origNote->tieStart()) {
tiedOrigNotes << origNote;
tiedClonedNotes << static_cast<CANote*>(clonedElt);
}
if (origNote->slurStart()) {
sluredOrigNotes << origNote;
sluredClonedNotes << static_cast<CANote*>(clonedElt);
}
if (origNote->phrasingSlurStart()) {
phrasingSluredOrigNotes << origNote;
phrasingSluredClonedNotes << static_cast<CANote*>(clonedElt);
}
}
// check tuplets
if (origElt->tuplet()) {
elementsUnderTuplet << clonedElt;
}
if (origElt->isLastInTuplet()) {
new CATuplet(origElt->tuplet()->number(), origElt->tuplet()->actualNumber(), elementsUnderTuplet);
elementsUnderTuplet.clear();
}
peltIdx[i]++;
}
newStaff->voiceList()[i]->synchronizeMusElements();
}
// append non-playable elements (shared by all voices - only create clone of the first voice element and append it to all)
if (peltIdx[0] < voiceList()[0]->musElementList().size()) {
CAMusElement* newElt = voiceList()[0]->musElementList()[peltIdx[0]]->clone(newStaff);
for (int i = 0; i < voiceList().size(); i++) {
newStaff->voiceList()[i]->append(newElt);
peltIdx[i]++;
}
}
// check if we're at the end
done = true;
for (int i = 0; i < voiceList().size(); i++) {
if (peltIdx[i] < voiceList()[i]->musElementList().size()) {
done = false;
break;
}
}
}
delete[] peltIdx;
return newStaff;
}
/*!
Returns the end of the last music element in the staff.
\sa CAVoice::lastTimeEnd()
*/
int CAStaff::lastTimeEnd()
{
int maxTime = 0;
for (int i = 0; i < _voiceList.size(); i++)
if (_voiceList[i]->lastTimeEnd() > maxTime)
maxTime = _voiceList[i]->lastTimeEnd();
return maxTime;
}
void CAStaff::clear()
{
while (_voiceList.size()) {
delete _voiceList.front(); // CAVoice's destructor removes the voice from the list.
}
}
/*!
Adds an empty voice to the staff.
Call synchronizeVoices() manually to synchronize a new voice with other voices.
*/
CAVoice* CAStaff::addVoice()
{
CAVoice* voice = new CAVoice(name() + QObject::tr("Voice%1").arg(voiceList().size() + 1), this);
addVoice(voice);
return voice;
}
/*!
Returns the pointer to the element right next to the given \a elt in any of the voice.
\sa next()
*/
CAMusElement* CAStaff::next(CAMusElement* elt)
{
for (int i = 0; i < voiceList().size(); i++) { // go through all the voices and check, if any of them includes the given element
if (voiceList()[i]->musElementList().contains(elt)) {
return voiceList()[i]->next(elt);
}
}
return nullptr; // the element doesn't exist in any of the voices, return nullptr
}
/*!
Returns the pointer to the element right before the given \a elt in any of the voice.
\sa previous()
*/
CAMusElement* CAStaff::previous(CAMusElement* elt)
{
for (int i = 0; i < voiceList().size(); i++) { // go through all the voices and check, if any of them includes the given element
if (voiceList()[i]->musElementList().contains(elt)) {
return voiceList()[i]->previous(elt);
}
}
return nullptr; // the element doesn't exist in any of the voices, return nullptr
}
/*!
Removes the element \a elt. Updates timeStarts for elements after the given element.
Also updates non-playable shared signs after the element, if \a updateSignTimes is True.
Eventually does the same as CAVoice::remove(), but checks for any voices present in the staff.
*/
bool CAStaff::remove(CAMusElement* elt, bool updateSignTimes)
{
if (!elt || !voiceList().size())
return false;
return voiceList()[0]->remove(elt, updateSignTimes);
}
CAMusElement *CAStaff::insertEmptyElement(int timeStart)
{
return nullptr; // N/A
}
/*!
Returns the first voice with the given \a name or Null, if such a voice doesn't exist.
*/
CAVoice* CAStaff::findVoice(const QString name)
{
for (int i = 0; i < _voiceList.size(); i++)
if (_voiceList[i]->name() == name)
return _voiceList[i];
return nullptr;
}
/*!
Returns a list of pointers to actual music elements which have the given \a startTime and are of
given \a type.
This searches the entire staff through all the voices.
\sa CASheet::getChord()
*/
QList<CAMusElement*> CAStaff::getEltByType(CAMusElement::CAMusElementType type, int startTime)
{
QList<CAMusElement*> eltList;
for (int i = 0; i < _voiceList.size(); i++) {
QList<CAMusElement*> curList;
curList = _voiceList[i]->getEltByType(type, startTime);
eltList += curList;
}
return eltList;
}
/*!
Returns one music element which has the given \a startTime and \a type.
This searches through all the voices of the staff.
\sa CASheet::getChord()
*/
CAMusElement* CAStaff::getOneEltByType(CAMusElement::CAMusElementType type, int startTime)
{
for (int i = 0; i < _voiceList.size(); i++) {
CAMusElement* elt;
elt = _voiceList[i]->getOneEltByType(type, startTime);
if (elt)
return elt;
}
return nullptr;
}
/*!
Returns a list of notes and rests (chord) for all the voices in the staff in
the given time slice \a time.
This is useful for determination of the harmony at certain point in time.
\sa CASheet:getChord(), CAVoice::getChord()
*/
QList<CAPlayable*> CAStaff::getChord(int time)
{
QList<CAPlayable*> chord;
for (int i = voiceList().size() - 1; i >= 0; i--)
chord << voiceList()[i]->getChord(time);
return chord;
}
/*!
Returns the Tempo element active at the given time.
*/
CATempo* CAStaff::getTempo(int time)
{
CATempo* tempo = nullptr;
for (int i = 0; i < voiceList().size(); i++) {
CATempo* t = voiceList()[i]->getTempo(time);
if (t && (!tempo || t->timeStart() > tempo->timeStart())) {
tempo = t;
}
}
return tempo;
}
/*!
Fixes voices inconsistency:
1) If any of the voices include signs (key sigs, clefs etc.) which aren't present in all voices,
add that sign to all the voices.
2) If a voice includes a sign which overlaps a playable element in other voice, insert rests until
the sign is moved at the end of the overlapped chord in all voices.
3) If a voice elements are not linear (every N-th element's timeEnd should be N+1-th element's timeStart)
inserts rests to achieve linearity.
Synchronizing voices is relatively slow (O(n*m) where n is number of voices and m number of elements
in voice n). This was the main reason to not automate the synchronization: import filters use lots of
insertions and synchronization of the voices every time a new element is inserted would considerably
slow down the import filter.
\return True, if everything was ok. False, if fixes were needed.
*/
bool CAStaff::synchronizeVoices()
{
int* pidx = new int[voiceList().size()];
for (int i = 0; i < voiceList().size(); i++)
pidx[i] = -1; // array of current indices of voices at current timeStart
CAMusElement** plastPlayable = new CAMusElement*[voiceList().size()];
for (int i = 0; i < voiceList().size(); i++)
plastPlayable[i] = nullptr;
_clefList.clear();
_keySignatureList.clear();
_timeSignatureList.clear();
_barlineList.clear();
int timeStart = 0;
bool done = false;
bool changesMade = false;
// first fix any inconsistencies inside a voice
for (int i = 0; i < voiceList().size(); i++)
voiceList()[i]->synchronizeMusElements();
while (!done) {
QList<CAMusElement*> sharedList; // list of shared music elements having the same time-start sorted by voice number
// gather shared elements into sharedList and remove them from the voice at new timeStart
for (int i = 0; i < voiceList().size(); i++) {
// don't increase pidx[i], if the next element is not-playable
while (pidx[i] < voiceList()[i]->musElementList().size() - 1 && !voiceList()[i]->musElementList()[pidx[i] + 1]->isPlayable() && (voiceList()[i]->musElementList()[pidx[i] + 1]->timeStart() == timeStart)) {
if (!sharedList.contains(voiceList()[i]->musElementList()[pidx[i] + 1])) {
sharedList << voiceList()[i]->musElementList()[pidx[i] + 1];
}
voiceList()[i]->_musElementList.removeAt(pidx[i] + 1);
}
}
// insert all elements from sharedList into all voices
// OR increase pidx[i] for 1 in all voices, if their new element is playable and new timeStart is correct
if (sharedList.size()) {
for (int i = 0; i < voiceList().size(); i++) {
for (int j = 0; j < sharedList.size(); j++) {
voiceList()[i]->_musElementList.insert(pidx[i] + 1 + j, sharedList[j]);
}
pidx[i]++; // jump to the first one inserted from the sharedList, if inserting shared elts for the first time
// or the first one after the sharedList in second pass
}
// populate the references lists
for (int j = 0; j < sharedList.size(); j++) {
switch (sharedList[j]->musElementType()) {
case CAMusElement::KeySignature:
_keySignatureList << sharedList[j];
break;
case CAMusElement::TimeSignature:
_timeSignatureList << sharedList[j];
break;
case CAMusElement::Clef:
_clefList << sharedList[j];
break;
case CAMusElement::Barline:
_barlineList << sharedList[j];
break;
default:
break;
}
}
} else {
for (int i = 0; i < voiceList().size(); i++) {
if (pidx[i] < voiceList()[i]->musElementList().size() - 1 && (voiceList()[i]->musElementList()[pidx[i] + 1]->timeStart() == timeStart)) {
if (voiceList()[i]->musElementList()[pidx[i] + 1]->isPlayable()) {
pidx[i]++;
plastPlayable[i] = voiceList()[i]->musElementList()[pidx[i]];
}
}
}
}
// if the shared element overlaps any of the chords in other voices, insert rests (shift the shared sign forward) to that voice
for (int i = 0; i < voiceList().size(); i++) {
if (pidx[i] == -1 || voiceList()[i]->musElementList()[pidx[i]]->isPlayable()) // only legal pidx[i] and non-playable elements
continue;
for (int j = 0; j < voiceList().size(); j++) {
if (i == j)
continue;
// fix the overlapped chord, rests are inserted later in non-linearity check
if (pidx[j] != -1 && voiceList()[i]->musElementList()[pidx[i]]->timeStart() == timeStart && plastPlayable[j] && plastPlayable[j]->timeStart() < timeStart && plastPlayable[j]->timeEnd() > timeStart) {
int gapLength = plastPlayable[j]->timeEnd() - timeStart;
QList<CARest*> restList = CARest::composeRests(gapLength, voiceList()[i]->musElementList()[pidx[i]]->timeStart(), voiceList()[i]);
voiceList()[i]->musElementList()[pidx[i]]->setTimeStart(plastPlayable[j]->timeEnd());
for (int k = 0; k < restList.size(); k++)
voiceList()[i]->_musElementList.insert(pidx[i]++, restList[k]); // insert the missing rests, rests are added in back, pidx++
voiceList()[i]->updateTimes(pidx[i], gapLength, false); // increase playable timeStarts
if (restList.size()) {
plastPlayable[i] = restList.last();
} else {
qDebug() << "Error in CAStaff::synchronizeVoices(): Cannot compose rests of length" << gapLength << endl;
}
changesMade = true;
}
}
}
// if the elements times are not linear (every N-th element's timeEnd should be N+1-th timeStart), insert rests to achieve it
for (int j = 0; j < voiceList().size(); j++) {
// fix the non-linearity
if (pidx[j] != -1 && !voiceList()[j]->musElementList()[pidx[j]]->isPlayable() && voiceList()[j]->musElementList()[pidx[j]]->timeStart() == timeStart
&& (plastPlayable[j] ? plastPlayable[j]->timeEnd() : 0) < timeStart) {
int gapLength = timeStart - ((pidx[j] == -1 || !plastPlayable[j]) ? 0 : plastPlayable[j]->timeEnd());
QList<CARest*> restList = CARest::composeRests(gapLength, (pidx[j] == -1 || !plastPlayable[j]) ? 0 : plastPlayable[j]->timeEnd(), voiceList()[j]);
for (int k = 0; k < restList.size(); k++)
voiceList()[j]->_musElementList.insert(pidx[j]++, restList[k]); // insert the missing rests, rests are added in back, pidx++
voiceList()[j]->updateTimes(pidx[j], gapLength, false); // increase playable timeStarts
if (restList.size()) {
plastPlayable[j] = restList.last();
} else {
qDebug() << "Error in CAStaff::synchronizeVoices(): Cannot compose rests of length" << gapLength << endl;
}
changesMade = true;
}
}
// jump to the last inserted from the sharedList
if (sharedList.size()) {
for (int i = 0; i < voiceList().size(); i++) {
pidx[i] += (sharedList.size() - 1);
}
}
// shortest time is delta between the current elements and the nearest one in the future
int shortestTime = -1;
for (int i = 0; i < voiceList().size(); i++) {
if (pidx[i] < (voiceList()[i]->musElementList().size() - 1) && (shortestTime == -1 || voiceList()[i]->musElementList()[pidx[i] + 1]->timeStart() - timeStart < shortestTime))
shortestTime = voiceList()[i]->musElementList()[pidx[i] + 1]->timeStart() - timeStart;
}
int deltaTime = ((shortestTime != -1) ? shortestTime : 0);
timeStart += deltaTime; // increase timeStart
// if all voices are at the end, finish
done = (deltaTime == 0); // last pass is only meant to linearize
for (int i = 0; i < voiceList().size(); i++)
if (pidx[i] < voiceList()[i]->musElementList().size() - 1)
done = false;
}
delete[] pidx;
return changesMade;
}
/*!
Places a barline in front of the element, if needed and the element is the
last element in the staff.
The function finds the last barline and places a new one, if the last bar is full.
It searches for the time signature in effect for the last bar, not to get fooled by
time signature(s) already present at a time signature change.
\return True, if a new barline was placed; otherwise False.
*/
bool CAStaff::placeAutoBar(CAPlayable* elt)
{
if (!elt)
return false;
CABarline* b = static_cast<CABarline*>(elt->voice()->previousByType(CAMusElement::Barline, elt));
CATimeSignature* t;
CAMusElement* prevTimeSig = elt;
// do not place autobar, if the element was inserted somewhere in the middle
for (int i = 0; i < elt->voice()->staff()->voiceList().size(); i++) {
if (elt->voice()->staff()->voiceList()[i]->lastTimeEnd() > elt->timeEnd()) {
return false;
}
}
do {
prevTimeSig = elt->voice()->previousByType(CAMusElement::TimeSignature, prevTimeSig);
t = static_cast<CATimeSignature*>(prevTimeSig);
} while (t && prevTimeSig->timeStart() == elt->timeStart()); // not the time signature for a bar in the future
if (t) {
if ((b ? (b->timeStart()) : 0) + t->barDuration() <= elt->timeStart()) {
elt->voice()->insert(elt, new CABarline(CABarline::Single, elt->staff(), elt->timeStart()));
elt->staff()->synchronizeVoices();
return true;
}
}
return false;
}
| 22,173
|
C++
|
.cpp
| 469
| 37.33049
| 216
| 0.590015
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,367
|
note.cpp
|
canorusmusic_canorus/src/score/note.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/note.h"
#include "score/clef.h"
#include "score/mark.h"
#include "score/staff.h"
#include "score/voice.h"
/*!
\class CANote
\brief Represents a note in the score.
This class represents every note in the score. It inherits the base class CAPlayable.
Chords in Canorus don't have its own class, but are represented as a list of notes.
The first note in the chord identifies it and contains chord-level marks.
*/
/*!
Creates a new note with playable length \a length in voice \a voice with pitch \a pitch
and accidentals \a accs, with starting time in the score \a timeStart and number of dots \a dotted.
timeLength is calculated automatically from the playable length.
\sa CAPlayableLength, CAPlayable, CAVoice, _pitch, _accs
*/
CANote::CANote(CADiatonicPitch pitch, CAPlayableLength length, CAVoice* voice, int timeStart, int timeLength)
: CAPlayable(length, voice, timeStart, timeLength)
{
_musElementType = CAMusElement::Note;
_forceAccidentals = false;
_stemDirection = StemPreferred;
setTieStart(nullptr);
setSlurStart(nullptr);
setPhrasingSlurStart(nullptr);
setTieEnd(nullptr);
setSlurEnd(nullptr);
setPhrasingSlurEnd(nullptr);
setDiatonicPitch(pitch);
}
CANote::~CANote()
{
if (tieStart())
delete tieStart(); // slurs destructor also disconnects itself from the notes
if (tieEnd())
tieEnd()->setNoteEnd(nullptr);
// other slurs are removed or moved in CAVoice::removeElement()
for (int i = 0; i < markList().size(); i++) {
delete markList()[i--];
}
}
/*!
\enum CANote::CAStemDirection
\brief Direction of the note's stem
This type represents the direction of the note's stem.
\todo Stem itself will probably be created as a separate class in the future. This will give us
possibility for a chord to have a common stem, apply additional stem properties etc. -Matevz
Possible values:
- StemNeutral
Up if under the middle line, down if above the middle line.
- StemUp
Always up.
- StemDown
Always down.
- StemPreferred
Use the voice's preferred direction.
*/
/*!
Clones the note with same pitch, voice, timeStart and other properties.
Does *not* create clones of ties, slurs and phrasing slurs!
*/
CANote* CANote::clone(CAVoice* voice)
{
CANote* d = new CANote(diatonicPitch(), playableLength(), voice, timeStart(), timeLength());
d->setStemDirection(stemDirection());
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(d));
d->addMark(m);
}
return d;
}
/*!
Dependent on the current clef calculates and returns the vertical
note position in the staff looking bottom-up:
- 0 - first line
- 1 - first space
- 2 - second line
- -1 - first space below the first line
- -2 - first ledger line below the staff (eg. C1 in treble clef)
*/
int CANote::notePosition()
{
CAClef* clef = nullptr;
if (voice() && voice()->staff()) {
// find the corresponding clef
int i = 0;
while (i < voice()->staff()->clefRefs().size() && staff()->clefRefs()[i]->timeStart() <= timeStart()) {
i++;
}
i--;
if (i >= 0) {
clef = static_cast<CAClef*>(voice()->staff()->clefRefs()[i]);
}
}
return (diatonicPitch().noteName() + (clef ? clef->c1() : -2) - 28);
}
/*!
Generates the note name on the given pitch \a pitch with accidentals \a accs.
Note name ranges are from C,, for sub-contra octave to c''''' for fifth octave.
This method is usually used for showing the note pitch in status bar.
\sa _pitch, _accs
*/
const QString CANote::generateNoteName(int pitch, int accs)
{
QString name;
name = static_cast<char>(((pitch < 0 ? pitch * (-1) : pitch) + 2) % 7 + 'a');
while (accs > 0) {
name += "is";
accs--;
}
while (accs < 0) {
if (name != "e" && name != "a")
name += "es";
else
name += "s";
accs++;
}
if (pitch < 21)
name = name.toUpper();
for (int i = 0; i < (pitch - 21) / 7; i++)
name.append('\'');
for (int i = 0; i < (pitch - 20) / (-7); i++)
name.append(',');
return name;
}
/*!
Returns true, if the note is part of a chord; otherwise false.
*/
bool CANote::isPartOfChord()
{
int idx = voice()->musElementList().indexOf(this);
// is there a note with the same start time after ours?
if (idx + 1 < voice()->musElementList().size() && voice()->musElementList()[idx + 1]->musElementType() == CAMusElement::Note && voice()->musElementList()[idx + 1]->timeStart() == _timeStart)
return true;
// is there a note with the same start time before ours?
if (idx > 0 && voice()->musElementList()[idx - 1]->musElementType() == CAMusElement::Note && voice()->musElementList()[idx - 1]->timeStart() == _timeStart)
return true;
return false;
}
/*!
Returns true, if the note is the first in the list of the chord; otherwise false.
*/
bool CANote::isFirstInChord()
{
int idx = voice()->musElementList().indexOf(this);
//is there a note with the same start time before ours?
if (idx > 0 && voice()->musElementList()[idx - 1]->musElementType() == CAMusElement::Note && voice()->musElementList()[idx - 1]->timeStart() == _timeStart)
return false;
return true;
}
/*!
Returns true, if the note is the last in the list of the chord; otherwise false.
*/
bool CANote::isLastInChord()
{
int idx = voice()->musElementList().indexOf(this);
//is there a note with the same start time after ours?
if (idx + 1 < voice()->musElementList().size() && voice()->musElementList()[idx + 1]->musElementType() == CAMusElement::Note && voice()->musElementList()[idx + 1]->timeStart() == _timeStart)
return false;
return true;
}
/*!
Generates a list of notes with the same start time - the whole chord - in the current voice.
Notes in chord keep the order present in the voice. This is usually bottom-up.
Returns a single element in the list - only the note itself, if the note isn't part of the chord.
\sa CAVoice::addNoteToChord()
*/
QList<CANote*> CANote::getChord()
{
QList<CANote*> list;
int idx = voice()->musElementList().indexOf(this) - 1;
while (idx >= 0 && voice()->musElementList()[idx]->musElementType() == CAMusElement::Note && voice()->musElementList()[idx]->timeStart() == timeStart())
idx--;
for (idx++;
(idx >= 0 && idx < voice()->musElementList().size()) && (voice()->musElementList()[idx]->musElementType() == CAMusElement::Note) && (voice()->musElementList()[idx]->timeStart() == timeStart());
idx++)
list << static_cast<CANote*>(voice()->musElementList()[idx]);
return list;
}
int CANote::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Note)
return -1;
int diffs = 0;
if (diatonicPitch() != static_cast<CANote*>(elt)->diatonicPitch())
diffs++;
if (playableLength() != static_cast<CAPlayable*>(elt)->playableLength())
diffs++;
return diffs;
}
/*!
Sets the stem direction and update tie, slur and phrasing slur direction.
*/
void CANote::setStemDirection(CAStemDirection dir)
{
_stemDirection = dir;
}
/*!
Looks at the tieStart() and tieEnd() ties and unties the note and tie if the
previous/next note pitch differs.
*/
void CANote::updateTies()
{
// break the tie, if needed
if (tieStart() && tieStart()->noteEnd() && diatonicPitch() != tieStart()->noteEnd()->diatonicPitch()) {
// break the tie, if the first note isn't the same pitch
tieStart()->noteEnd()->setTieEnd(nullptr);
tieStart()->setNoteEnd(nullptr);
}
if (tieEnd() && tieEnd()->noteStart() && diatonicPitch() != tieEnd()->noteStart()->diatonicPitch()) {
// break the tie, if the next note isn't the same pitch
tieEnd()->setNoteEnd(nullptr);
setTieEnd(nullptr);
}
// fix/create a tie, if needed
QList<CANote*> noteList;
if (voice())
noteList = voice()->getNoteList();
// checks a tie of the potential left note
CANote* leftNote = nullptr;
for (int i = 0; i < noteList.count() && noteList[i]->timeEnd() <= timeStart(); i++) { // get the left note
if (noteList[i]->timeEnd() == timeStart() && noteList[i]->diatonicPitch() == diatonicPitch()) {
leftNote = noteList[i];
break;
}
}
if (leftNote && leftNote->tieStart()) {
leftNote->tieStart()->setNoteEnd(this);
setTieEnd(leftNote->tieStart());
}
// checks a tie of the potential right note
CANote* rightNote = nullptr;
for (int i = 0; i < noteList.count() && noteList[i]->timeStart() <= timeEnd(); i++) { // get the right note
if (noteList[i]->timeStart() == timeEnd() && noteList[i]->diatonicPitch() == diatonicPitch()) {
rightNote = noteList[i];
break;
}
}
if (rightNote && tieStart()) {
rightNote->setTieEnd(tieStart());
tieStart()->setNoteEnd(rightNote);
}
}
/*!
Converts stem direction CAStemDirection to QString.
This is usually used when saving the score.
\sa CAStemDirection, CACanorusML
*/
const QString CANote::stemDirectionToString(CANote::CAStemDirection dir)
{
switch (dir) {
case CANote::StemUp:
return "stem-up";
case CANote::StemDown:
return "stem-down";
case CANote::StemNeutral:
return "stem-neutral";
case CANote::StemPreferred:
return "stem-preferred";
case CANote::StemUndefined:
return "stem-preferred";
}
return "stem-preferred";
}
/*!
Converts stem direction in QString format to CAStemDirection.
This is usually used when loading a score.
\sa CAStemDirection, CACanorusML
*/
CANote::CAStemDirection CANote::stemDirectionFromString(const QString dir)
{
if (dir == "stem-up") {
return CANote::StemUp;
} else if (dir == "stem-down") {
return CANote::StemDown;
} else if (dir == "stem-neutral") {
return CANote::StemNeutral;
} else if (dir == "stem-preferred") {
return CANote::StemPreferred;
} else
return CANote::StemPreferred;
}
/*!
Returns the actual stem direction (the one which is drawn). Always returns stem up or stem down.
*/
CANote::CAStemDirection CANote::actualStemDirection()
{
switch (stemDirection()) {
case StemUp:
case StemDown:
return stemDirection();
case StemNeutral:
if (staff() && notePosition() < staff()->numberOfLines() - 1) // position from 0 to half of the number of lines - where position has step of 2 per line
return StemUp;
else
return StemDown;
case StemPreferred:
if (!voice()) {
return StemUp;
}
switch (voice()->stemDirection()) {
case StemUp:
case StemDown:
return voice()->stemDirection();
case StemNeutral:
if (staff() && notePosition() < staff()->numberOfLines() - 1) // position from 0 to half of the number of lines - where position has step of 2 per line
return StemUp;
else
return StemDown;
default: // We should always have a defined stem here
return StemUndefined;
}
default:
return StemUndefined;
}
}
/*!
Determines the right slur direction of the note.
Slur should be on the other side of the stem, if the stem direction is neutral
or on the same side if the stem direction is set strictly to up and down (or preferred).
*/
CASlur::CASlurDirection CANote::actualSlurDirection()
{
CAStemDirection dir = actualStemDirection();
if (stemDirection() == StemNeutral || (stemDirection() == StemPreferred && voice() && voice()->stemDirection() == StemNeutral)) {
if (dir == StemUp)
return CASlur::SlurDown;
else
return CASlur::SlurUp;
} else {
if (dir == StemUp)
return CASlur::SlurUp;
else
return CASlur::SlurDown;
}
}
/*!
\fn CANote::accidentals()
Returns number and type of accidentals of the note.
\sa _accs, setAccidentals()
*/
/*!
\fn CANote::setAccidentals(int accs)
Sets a number and type of accidentals to \a accs of the note.
\sa _accs, accidentals()
*/
/*!
\var CANote::_accs
Number of note accidentals:
- 0 - neutral
- 1 - sharp
- -1 - flat etc.
\sa accidentals(), setAccidentals()
*/
/*!
\fn CANote::pitch()
Returns the note pitch in internal Canorus units.
\sa _pitch, setPitch()
*/
/*!
\fn CANote::setPitch(int pitch)
Sets the note pitch to \a pitch.
\sa _pitch, pitch()
*/
/*!
\var CANote::_pitch
Pitch in internal Canorus format.
- 0 - sub-contra C
- 1 - sub-contra D
- 28 - middle C
- 56 - c5 etc.
\sa pitch(), setPitch(), midiPitchToPitch(), pitchToMidiPitch(), pitchToString(), generateNoteName()
*/
/*!
\var CANote::_stemDirection
Direction of the note's stem, if any.
\sa CAStemDirection
*/
/*!
\var CANote::_forceAccidentals
Always draw notes accidentals.
\sa _accs
*/
| 13,367
|
C++
|
.cpp
| 390
| 29.576923
| 202
| 0.650954
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,368
|
fermata.cpp
|
canorusmusic_canorus/src/score/fermata.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/fermata.h"
#include "score/barline.h"
#include "score/playable.h"
/*!
\class CAFermata
\brief Fermata mark
Extended mark for fermata.
Fermata is assigned to playable elements or to the barlines.
*/
CAFermata::CAFermata(CAPlayable* p, CAFermataType t)
: CAMark(CAMark::Fermata, p)
{
setFermataType(t);
}
CAFermata::CAFermata(CABarline* b, CAFermataType t)
: CAMark(CAMark::Fermata, b)
{
setFermataType(t);
}
CAFermata::~CAFermata()
{
}
CAFermata* CAFermata::clone(CAMusElement* elt)
{
if (elt->isPlayable()) {
return new CAFermata(static_cast<CAPlayable*>(elt), fermataType());
} else {
return new CAFermata((elt->musElementType() == Barline) ? static_cast<CABarline*>(elt) : nullptr, fermataType());
}
}
int CAFermata::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
else if (static_cast<CAMark*>(elt)->markType() != CAMark::Fermata)
return -1;
else if (static_cast<CAFermata*>(elt)->fermataType() != fermataType())
return 1;
return 0;
}
const QString CAFermata::fermataTypeToString(CAFermataType t)
{
switch (t) {
case NormalFermata:
return "NormalFermata";
case ShortFermata:
return "ShortFermata";
case LongFermata:
return "LongFermata";
case VeryLongFermata:
return "VeryLongFermata";
}
return "NormalFermata";
}
CAFermata::CAFermataType CAFermata::fermataTypeFromString(const QString r)
{
if (r == "NormalFermata") {
return NormalFermata;
} else if (r == "ShortFermata") {
return ShortFermata;
} else if (r == "LongFermata") {
return LongFermata;
} else if (r == "VeryLongFermata") {
return VeryLongFermata;
}
return NormalFermata;
}
| 2,030
|
C++
|
.cpp
| 72
| 24.152778
| 121
| 0.690647
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,369
|
fingering.cpp
|
canorusmusic_canorus/src/score/fingering.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/fingering.h"
#include "score/note.h"
/*!
\class CAFingering
\brief Finger marks
This class represents fingering beside or above/below the note.
Fingering can include a single finger number or multiple fingers (change fingering
on one note).
The finger numbers can be written with italic style (original author's fingering when
making an arrangment) or regular. This property is stored in original().
*/
CAFingering::CAFingering(CAFingerNumber finger, CANote* n, bool original)
: CAMark(CAMark::Fingering, n)
{
addFinger(finger);
setOriginal(original);
setCommon(false);
}
CAFingering::CAFingering(QList<CAFingerNumber> fingers, CANote* n, bool original)
: CAMark(CAMark::Fingering, n)
{
_fingerList = fingers;
setOriginal(original);
setCommon(false);
}
CAFingering::~CAFingering()
{
}
CAFingering* CAFingering::clone(CAMusElement* elt)
{
return new CAFingering(fingerList(), (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr, isOriginal());
}
int CAFingering::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
else if (static_cast<CAMark*>(elt)->markType() != CAMark::Fingering)
return -1;
int differ = 0;
CAFingering* f = static_cast<CAFingering*>(elt);
for (int i = 0; i < f->fingerList().size() || i < fingerList().size(); i++) {
if (i >= f->fingerList().size() || i >= fingerList().size() || f->fingerList().at(i) != fingerList().at(i))
differ++;
}
if (static_cast<CAFingering*>(elt)->isOriginal() != isOriginal())
differ++;
return differ;
}
const QString CAFingering::fingerNumberToString(CAFingerNumber n)
{
switch (n) {
case First:
return "First";
case Second:
return "Second";
case Third:
return "Third";
case Fourth:
return "Fourth";
case Fifth:
return "Fifth";
case Thumb:
return "Thumb";
case LHeel:
return "LHeel";
case RHeel:
return "RHeel";
case LToe:
return "LToe";
case RToe:
return "RToe";
case Undefined:
return "Undefined";
}
return "Undefined";
}
CAFingering::CAFingerNumber CAFingering::fingerNumberFromString(const QString f)
{
if (f == "First") {
return First;
} else if (f == "Second") {
return Second;
} else if (f == "Third") {
return Third;
} else if (f == "Fourth") {
return Fourth;
} else if (f == "Fifth") {
return Fifth;
} else if (f == "Thumb") {
return Thumb;
} else if (f == "LHeel") {
return LHeel;
} else if (f == "RHeel") {
return RHeel;
} else if (f == "LToe") {
return LToe;
} else if (f == "RToe") {
return RToe;
} else
return Undefined;
}
| 3,096
|
C++
|
.cpp
| 106
| 24.320755
| 140
| 0.639785
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,370
|
barline.cpp
|
canorusmusic_canorus/src/score/barline.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/barline.h"
#include "score/mark.h"
#include "score/staff.h"
/*!
\class CABarline
\brief Music element which represents a barline in the score.
This class represents any type of barlines in the score.
Barline type is defined in _barlineType.
\sa CAMusElement
*/
/*!
Creates a barline of type \a type, its parent \a staff and \a startTime.
\a timeLength of a barline is always 0.
*/
CABarline::CABarline(CABarlineType type, CAStaff* staff, int startTime)
: CAMusElement(staff, startTime)
{
setMusElementType(CAMusElement::Barline);
setBarlineType(type);
}
/*!
Destroys the barline.
*/
CABarline::~CABarline()
{
}
CABarline* CABarline::clone(CAContext* context)
{
CABarline* b = new CABarline(barlineType(), static_cast<CAStaff*>(context), timeStart());
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(b));
b->addMark(m);
}
return b;
}
int CABarline::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Barline)
return -1;
int diffs = 0;
if (barlineType() != static_cast<CABarline*>(elt)->barlineType())
diffs++;
return diffs;
}
/*!
Converts the given barline's \a type to QString.
\sa CABarlineType, barlineTypeFromString()
*/
const QString CABarline::barlineTypeToString(CABarlineType type)
{
switch (type) {
case Single:
return "single";
case Double:
return "double";
case End:
return "end";
case RepeatOpen:
return "repeat-open";
case RepeatClose:
return "repeat-close";
case RepeatCloseOpen:
return "repeat-close-open";
case Dotted:
return "dotted";
default:
return "";
}
}
/*!
Converts the barline's \a type in QString to CABarlineType.
\sa CABarlineType, barlineTypeToString()
*/
CABarline::CABarlineType CABarline::barlineTypeFromString(const QString type)
{
if (type == "single")
return Single;
else if (type == "double")
return Double;
else if (type == "end")
return End;
else if (type == "repeat-open")
return RepeatOpen;
else if (type == "repeat-close")
return RepeatClose;
else if (type == "repeat-close-open")
return RepeatCloseOpen;
else if (type == "dotted")
return Dotted;
else
return Single;
}
| 2,621
|
C++
|
.cpp
| 97
| 22.835052
| 93
| 0.676377
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,371
|
repeatmark.cpp
|
canorusmusic_canorus/src/score/repeatmark.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/repeatmark.h"
#include "score/barline.h"
/*!
\class CARepeatMark
\brief Repeat marks like segno, volta, coda etc.
This class represents non-ordinary repeat signs like coda, segno and volta.
\sa CABarline
*/
CARepeatMark::CARepeatMark(CABarline* b, CARepeatMarkType t, int voltaNumber)
: CAMark(CAMark::RepeatMark, b)
{
setRepeatMarkType(t);
setVoltaNumber(voltaNumber);
}
CARepeatMark::~CARepeatMark()
{
}
CARepeatMark* CARepeatMark::clone(CAMusElement* elt)
{
return new CARepeatMark((elt->musElementType() == CAMusElement::Barline) ? static_cast<CABarline*>(elt) : nullptr, repeatMarkType(), voltaNumber());
}
int CARepeatMark::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::Mark)
return -2;
else if (static_cast<CAMark*>(elt)->markType() != CAMark::RepeatMark)
return -1;
else if (static_cast<CARepeatMark*>(elt)->repeatMarkType() != repeatMarkType())
return 1;
else if (static_cast<CARepeatMark*>(elt)->voltaNumber() != voltaNumber())
return 2;
else
return 0;
}
const QString CARepeatMark::repeatMarkTypeToString(CARepeatMarkType t)
{
switch (t) {
case (Undefined):
return "Undefined";
case (Volta):
return "Volta";
case (Segno):
return "Segno";
case (Coda):
return "Coda";
case (VarCoda):
return "VarCoda";
case (DalSegno):
return "DalSegno";
case (DalCoda):
return "DalCoda";
case (DalVarCoda):
return "DalVarCoda";
}
return "Undefined";
}
CARepeatMark::CARepeatMarkType CARepeatMark::repeatMarkTypeFromString(const QString r)
{
if (r == "Undefined")
return Undefined;
else if (r == "Volta")
return Volta;
else if (r == "Segno")
return Segno;
else if (r == "Coda")
return Coda;
else if (r == "VarCoda")
return VarCoda;
else if (r == "DalSegno")
return DalSegno;
else if (r == "DalCoda")
return DalCoda;
else if (r == "DalVarCoda")
return DalVarCoda;
return Undefined;
}
| 2,334
|
C++
|
.cpp
| 81
| 24.08642
| 152
| 0.667707
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,372
|
playablelength.cpp
|
canorusmusic_canorus/src/score/playablelength.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/playablelength.h"
#include "score/barline.h"
#include "score/timesignature.h"
#include <iostream>
/*!
\class CAPlayableLength
\brief Musical length of notes and rests
This class represents a musical length (quarter, half, whole etc.) of notes
and rests with number of dots.
It consists of two properties:
- music length (quarter, half, whole etc.)
- number of dots
Playable length can be easily converted to timeLength. Vice-versa is a bit more
difficult.
\sa playableLengthToTimeLength(), CARest::composeRests()
*/
CAPlayableLength::CAPlayableLength()
{
setMusicLength(Undefined);
setDotted(0);
}
CAPlayableLength::CAPlayableLength(CAMusicLength l, int dotted)
{
setMusicLength(l);
setDotted(dotted);
}
CAPlayableLength::CAMusicLength CAPlayableLength::musicLengthFromString(const QString length)
{
if (length == "undefined") {
return Undefined;
} else if (length == "breve") {
return Breve;
} else if (length == "whole") {
return Whole;
} else if (length == "half") {
return Half;
} else if (length == "quarter") {
return Quarter;
} else if (length == "eighth") {
return Eighth;
} else if (length == "sixteenth") {
return Sixteenth;
} else if (length == "thirty-second") {
return ThirtySecond;
} else if (length == "sixty-fourth") {
return SixtyFourth;
} else if (length == "hundred-twenty-eighth") {
return HundredTwentyEighth;
} else
return Undefined;
}
const QString CAPlayableLength::musicLengthToString(CAPlayableLength::CAMusicLength length)
{
switch (length) {
case Undefined:
return "undefined";
case Breve:
return "breve";
case Whole:
return "whole";
case Half:
return "half";
case Quarter:
return "quarter";
case Eighth:
return "eighth";
case Sixteenth:
return "sixteenth";
case ThirtySecond:
return "thirty-second";
case SixtyFourth:
return "sixty-fourth";
case HundredTwentyEighth:
return "hundred-twenty-eighth";
}
return "";
}
/*!
Converts internal enum playableLength to actual timeLength.
\sa CARest::composeRests()
*/
int CAPlayableLength::playableLengthToTimeLength(CAPlayableLength length)
{
int timeLength;
switch (length.musicLength()) {
case HundredTwentyEighth:
timeLength = 8;
break;
case SixtyFourth:
timeLength = 16;
break;
case ThirtySecond:
timeLength = 32;
break;
case Sixteenth:
timeLength = 64;
break;
case Eighth:
timeLength = 128;
break;
case Quarter:
timeLength = 256;
break;
case Half:
timeLength = 512;
break;
case Whole:
timeLength = 1024;
break;
case Breve:
timeLength = 2048;
break;
default: // This should never occur!
timeLength = 0;
break;
}
float factor = 1.0, delta = 0.5;
for (int i = 0; i < length.dotted(); i++, factor += delta, delta /= 2)
; // calculate the length factor out of number of dots
timeLength = qRound(timeLength * factor); // increase the time length for the factor
return timeLength;
}
/*!
Compute for a given time length the CAPlayableLengths. In the general case
this could result in several notes. In the canorus GUI we can have max. 4 dots.
By default longer notes appear first in the list, but with negating longNotesFirst
the short ones appear first. This is useful for end of bar notes.
To make this computation fast we take in account that note durations are
a binary presentation of the time duration. The breve value is not exactly
a log2 value, so we do this singular nonlinear operation through the method of
computation (see **).
Limitations: Maximum four dots per note, and the smallest resulting time duration
is SixtyFourth;
Todo: Allow change of limitations as function parameters, which are longest note
and number of dots.
*/
QList<CAPlayableLength> CAPlayableLength::timeLengthToPlayableLengthList(int t, bool longNotesFirst, int dotsLimit)
{
QList<CAPlayableLength> pl;
int workTime = t; // this is the register that decreases for every item processed
const int breveTime = playableLengthToTimeLength(Breve);
int leadingBreves = workTime & ~(2 * breveTime - 1);
while (leadingBreves >= breveTime) {
pl << CAPlayableLength(Breve);
leadingBreves -= breveTime;
}
// Now only maximum one breve with possibly many dots is left
workTime &= 2 * breveTime - 1;
// and as a safety measure we suppress time elements smaller than 128ths.
workTime &= ~(playableLengthToTimeLength(HundredTwentyEighth) - 1);
if (dotsLimit > 4)
dotsLimit = 4;
int currentTime = breveTime;
int logCurrentMusLenPlusOne = 0;
int dots = 0;
bool findNote = true;
while (workTime && (currentTime >= musicLengthToTimeLength(HundredTwentyEighth))) {
if (findNote) {
if (workTime & currentTime) {
// Now we reverse log2 and exponentiate and do the nonlinear mapping of breve (**)
// when the value 1 is erased by division with 2::
pl << CAPlayableLength(CAMusicLength((1 << logCurrentMusLenPlusOne) / 2));
dots = dotsLimit;
findNote = dotsLimit > 0 ? false : true;
} else {
findNote = true;
}
} else {
// try to find a dot for the current note
if (workTime & currentTime) {
pl.back().setDotted(pl.back().dotted() + 1);
dots--;
findNote = dots > 0 ? false : true;
} else
findNote = true;
}
workTime &= ~currentTime;
currentTime /= 2;
logCurrentMusLenPlusOne++;
}
// If not short notes first, for example at the end of bar, we reverse the list.
int i, j;
if (!longNotesFirst)
for (i = 0, j = pl.size() - 1; i < j; i++, j--)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
pl.swapItemsAt(i, j);
#else
pl.swap(i, j);
#endif
return pl;
}
/*!
Compares two playable lengths.
*/
bool CAPlayableLength::operator==(CAPlayableLength l)
{
if (musicLength() == l.musicLength() && dotted() == l.dotted())
return true;
else
return false;
}
/*!
Compares two playable lengths.
*/
bool CAPlayableLength::operator!=(CAPlayableLength l)
{
return (!operator==(l));
}
/*!
Split a playable to match a given bar border and bar length.
This function is used at music input with a midi keyboard.
*/
QList<CAPlayableLength> CAPlayableLength::matchToBars(CAPlayableLength len, int timeStart, CABarline* lastBarline, CATimeSignature* ts, int dotsLimit)
{
// If something is strange or undoable we prepare for returning the length unchanged.
QList<CAPlayableLength> unchanged;
unchanged << len;
if (!ts)
return unchanged;
int beat = ts->beat();
switch (beat) {
case 2:
case 4:
case 8:
break;
default:
return unchanged;
}
int barLength = CAPlayableLength::playableLengthToTimeLength(
CAPlayableLength(static_cast<CAPlayableLength::CAMusicLength>(ts->beat())))
* ts->beats();
int barRest = (lastBarline ? lastBarline->timeStart() : 0) + barLength - timeStart;
if (!lastBarline || lastBarline->timeStart() < ts->timeStart() || timeStart == ts->timeStart())
barRest = 0;
// no change when bar lengths are bogus
if (barRest < 0 || barRest > barLength)
return unchanged;
int noteLen = len.playableLengthToTimeLength(len);
// now we really do a split
QList<CAPlayableLength> list;
int tSplit = barRest ? barRest : barLength;
bool longNotesFirst = barRest ? false : true;
while (noteLen) {
tSplit = tSplit > noteLen ? noteLen : tSplit;
list << timeLengthToPlayableLengthList(tSplit, longNotesFirst, dotsLimit);
noteLen -= tSplit;
tSplit = noteLen > barLength ? barLength : noteLen;
longNotesFirst = true;
}
return list;
}
/*!
Split a playable length to match a virtual or real next barline by recognising a given previous barline
and bar length by a given time signature.
In lack of barline or timesignature asumptions are made, maybe resulting in returning an empty split list.
separationTime is an additional splitting point, meant to do there key signature changes.
This function is used in midi import, could be used at mouse note input too, probably. See also \a matchToBars
with CAPlayableLength as parameter, which is used at midi keyboard input. This functions probably could be
merged.
*/
QList<CAPlayableLength> CAPlayableLength::matchToBars(int timeLength, int timeStart, CABarline* lastBarline, CATimeSignature* ts, int dotsLimit, int separationTime)
{
QList<CAPlayableLength> list;
// default time signature is 4/4
int barLength = CAPlayableLength::playableLengthToTimeLength(CAPlayableLength::Quarter) * 4;
if (ts) {
int beat = ts->beat();
switch (beat) {
case 4:
case 2:
case 8:
case 16:
case 1:
case 32:
break;
default:
return list; // If something is strange or undoable we prepare for returning an empty list!
}
barLength = CAPlayableLength::playableLengthToTimeLength(
CAPlayableLength(static_cast<CAPlayableLength::CAMusicLength>(ts->beat())))
* ts->beats();
}
int barRest = (lastBarline ? lastBarline->timeStart() : 0) + barLength - timeStart;
// no change when bar lengths are bogus
if (lastBarline && ts && (lastBarline->timeStart() < ts->timeStart()))
barRest = 0;
if (ts && (timeStart == ts->timeStart()))
barRest = 0;
if (barRest < 0 || barRest > barLength)
barRest = 0;
int noteLen = timeLength;
int sepRest = separationTime - timeStart;
if (sepRest < 0 || sepRest >= noteLen)
sepRest = 0;
//if (sepRest > 0 && barRest
// now we really do a split
int tSplit = barRest ? barRest : barLength;
bool longNotesFirst = barRest ? false : true;
while (noteLen) {
tSplit = tSplit > noteLen ? noteLen : tSplit;
int decr = (tSplit < sepRest) || (sepRest <= 0) ? tSplit : sepRest;
list << timeLengthToPlayableLengthList(decr, longNotesFirst, dotsLimit);
noteLen -= decr;
sepRest -= decr;
tSplit = noteLen > barLength ? barLength : noteLen;
longNotesFirst = true;
}
return list;
}
| 11,004
|
C++
|
.cpp
| 314
| 29.041401
| 164
| 0.660028
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,373
|
interval.cpp
|
canorusmusic_canorus/src/score/interval.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/interval.h"
#include "score/diatonicpitch.h"
#include <QObject>
#include <QtGlobal>
/*!
\class CAInterval
\brief Music interval expressed with diatonical quality and quantity
This class represent an interval between two notes.
eg. major second, minor sixth, perfect prime, perfect fifth, augmented fifth etc.
It consists of two properties:
- quality (major, minor, perfect, augmented, diminished)
- quantity (prime, second, third, fourth etc.)
\note Quantity can also be negative for intervals down.
Intervals can be compared to each other, summed with other intervals or diatonic
pitches and inverted.
\sa CADiatonicPitch, operator~()
*/
/*!
Constructs an interval with quality \a qlt and quantity \a qnt.
*/
CAInterval::CAInterval(int qlt, int qnt)
{
setQuality(qlt);
setQuantity(qnt);
}
/*!
Constructs a new undefined interval.
Call setQuality() and setQuantity() to set its properties.
*/
CAInterval::CAInterval()
{
setQuality(0);
setQuantity(0);
}
/*!
Constructs an interval between the pitches \a pitch1 and \a pitch2.
Interval quantity is positive regardless of the order of pitches, if \a absolute is True (default).
Otherwise, quantity is negative, if second pitch is lower than the first one.
*/
CAInterval::CAInterval(CADiatonicPitch pitch1, CADiatonicPitch pitch2, bool absolute)
{
CADiatonicPitch pLow, pHigh;
if (pitch1.noteName() < pitch2.noteName() || (pitch1.noteName() == pitch2.noteName() && pitch1.accs() <= pitch2.accs())) {
pLow = pitch1;
pHigh = pitch2;
} else {
pLow = pitch2;
pHigh = pitch1;
}
setQuantity(pHigh.noteName() - pLow.noteName() + 1);
int relQnt = ((quantity() - 1) % 7) + 1;
int relPLow = pLow.noteName() % 7 /*, relPHigh = pHigh.noteName()%7*/;
int deltaQlt = 0;
switch (relQnt) {
case 1: // prime
deltaQlt = 0;
break;
case 2: // second
if (relPLow == 2 || relPLow == 6)
deltaQlt = -1;
else
deltaQlt = 1;
break;
case 3: // third
if (relPLow == 0 || relPLow == 3 || relPLow == 4)
deltaQlt = 1;
else
deltaQlt = -1;
break;
case 4: // fourth
if (relPLow == 3)
deltaQlt = 2;
else
deltaQlt = 0;
break;
case 5: // fifth
if (relPLow == 6)
deltaQlt = -2;
else
deltaQlt = 0;
break;
case 6: // sixth
if (relPLow == 2 || relPLow == 5 || relPLow == 6)
deltaQlt = -1;
else
deltaQlt = 1;
break;
case 7: // seventh
if (relPLow == 0 || relPLow == 3)
deltaQlt = 1;
else
deltaQlt = -1;
break;
}
// prime, fourth, fifth are perfect, diminished or augmented
if (relQnt == 1 || relQnt == 4 || relQnt == 5) {
if ((deltaQlt == 2 && pHigh.accs() - pLow.accs() == -1) || (deltaQlt == 0 && pHigh.accs() - pLow.accs() <= -1)) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() - 1);
} else if (deltaQlt == 2 && pHigh.accs() - pLow.accs() < -1) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() - 2);
} else if ((deltaQlt == -2 && pHigh.accs() - pLow.accs() == 1) || (deltaQlt == 0 && pHigh.accs() - pLow.accs() >= 1)) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() + 1);
} else if (deltaQlt == -2 && pHigh.accs() - pLow.accs() > 1) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() + 2);
} else {
setQuality(deltaQlt + pHigh.accs() - pLow.accs());
}
} else
// second, third, sixth and seventh cannot be perfect
if (deltaQlt == 1 && pHigh.accs() - pLow.accs() < 0) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() - 1);
} else if (deltaQlt == -1 && pHigh.accs() - pLow.accs() > 0) {
setQuality(deltaQlt + pHigh.accs() - pLow.accs() + 1);
} else {
setQuality(deltaQlt + pHigh.accs() - pLow.accs());
}
if (!absolute && (pitch1.noteName() > pitch2.noteName() || (pitch1.noteName() == pitch2.noteName() && pitch1.accs() > pitch2.accs()))) {
setQuantity(-quantity());
}
}
/*!
Returns the inverse of the interval. The reversed interval is always positive.
eg. seventh -> second, major -> minor and vice versa
*/
CAInterval CAInterval::operator~()
{
int qlt = quality() * (-1);
int qnt = 8 - ((qAbs(quantity()) - 2) % 7 + 1);
return CAInterval(qlt, qnt);
}
/*!
Returns the sum of two intervals.
eg. perfect fifth + major third = major seventh
*/
CAInterval CAInterval::operator+(CAInterval i)
{
CADiatonicPitch p1(0, 0);
CADiatonicPitch p2 = p1 + i + CAInterval(quality(), quantity());
return CAInterval(p1, p2);
}
/*!
Returns the number of semitones in the interval.
This is a surjective mapping.
*/
int CAInterval::semitones()
{
int semitones = 0;
int absQuantity = ((qAbs(quantity()) - 1) % 7) + 1;
// major and perfect intervals are default
switch (absQuantity) {
case Prime:
semitones = 0;
break;
case Second:
semitones = 2;
break;
case Third:
semitones = 4;
break;
case Fourth:
semitones = 5;
break;
case Fifth:
semitones = 7;
break;
case Sixth:
semitones = 9;
break;
case Seventh:
semitones = 11;
break;
}
// minor or diminished/augmented
switch (quality()) {
case Diminished: {
if (absQuantity == Second || absQuantity == Third || absQuantity == Sixth || absQuantity == Seventh) {
semitones -= 2;
} else {
semitones -= 1;
}
break;
}
case Minor:
semitones -= 1;
break;
case Augmented:
semitones += 1;
break;
}
// octaves
semitones += 12 * ((qAbs(quantity()) - 1) / 7);
// invert semitones for negative quantity
if (quantity() < 0)
semitones *= -1;
return semitones;
}
/*!
Creates an interval out of the given \a semitones.
Semitones can also be negative to produce intervals down.
The interval found in major/minor scales is returned.
Augmented fourth is used for the tritone.
This is an injective mapping.
*/
CAInterval CAInterval::fromSemitones(int semitones)
{
int absSemitones = qAbs(semitones) % 12;
CAInterval interval;
switch (absSemitones) {
case 0:
interval = CAInterval(Perfect, Prime);
break;
case 1:
interval = CAInterval(Minor, Second);
break;
case 2:
interval = CAInterval(Major, Second);
break;
case 3:
interval = CAInterval(Minor, Third);
break;
case 4:
interval = CAInterval(Major, Third);
break;
case 5:
interval = CAInterval(Perfect, Fourth);
break;
case 6:
interval = CAInterval(Augmented, Fourth);
break;
case 7:
interval = CAInterval(Perfect, Fifth);
break;
case 8:
interval = CAInterval(Minor, Sixth);
break;
case 9:
interval = CAInterval(Major, Sixth);
break;
case 10:
interval = CAInterval(Minor, Seventh);
break;
case 11:
interval = CAInterval(Major, Seventh);
break;
}
// rise the interval for the n-octaves
interval.setQuantity(interval.quantity() + (qAbs(semitones) / 12) * 7);
// set negative interval quantity for negative semitones
if (semitones < 0) {
interval.setQuantity(interval.quantity() * (-1));
}
return interval;
}
const QString CAInterval::qualityToReadable(int k)
{
switch (k) {
case 0:
return QObject::tr("Perfect", "interval");
case 1:
return QObject::tr("Major", "interval");
case -1:
return QObject::tr("Minor", "interval");
case 2:
return QObject::tr("Augmented", "interval");
case -2:
return QObject::tr("Diminished", "interval");
default:
return QString::number(k);
}
}
const QString CAInterval::quantityToReadable(int k)
{
switch (qAbs(k)) {
case 1:
return QObject::tr("Prime", "interval");
case 2:
return QObject::tr("Second", "interval");
case 3:
return QObject::tr("Third", "interval");
case 4:
return QObject::tr("Fourth", "interval");
case 5:
return QObject::tr("Fifth", "interval");
case 6:
return QObject::tr("Sixth", "interval");
case 7:
return QObject::tr("Seventh", "interval");
case 8:
return QObject::tr("Octave", "interval");
case 9:
return QObject::tr("Nineth", "interval");
case 10:
return QObject::tr("Tenth", "interval");
default:
return QString::number(k);
}
}
| 9,095
|
C++
|
.cpp
| 302
| 24.096026
| 140
| 0.598172
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,374
|
chordname.cpp
|
canorusmusic_canorus/src/score/chordname.cpp
|
/*!
Copyright (c) 2019-2022, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/chordname.h"
#include "score/chordnamecontext.h"
/*!
\class CAChordName
\brief Chord name
Chord name (e.g. C, F#m, Gsus4 etc.) inside the CAChordNameContext.
*/
CAChordName::CAChordName(CADiatonicPitch pitch, QString qualityModifier, CAChordNameContext* c, int timeStart, int timeLength)
: CAMusElement(c, timeStart, timeLength)
{
setMusElementType(ChordName);
setDiatonicPitch(pitch);
setQualityModifier(qualityModifier);
}
CAChordName::~CAChordName()
{
}
/*!
Clears the pitch and modifier.
This function is usually called when deleting the chord name from the UI, where it shouldn't actually
be removed, but only cleared.
*/
void CAChordName::clear()
{
setDiatonicPitch(CADiatonicPitch::Undefined);
setQualityModifier("");
}
CAChordName* CAChordName::clone(CAContext* context)
{
if (context && context->contextType() != CAContext::ChordNameContext) {
return nullptr;
}
return new CAChordName(
diatonicPitch(),
qualityModifier(),
static_cast<CAChordNameContext*>(context),
timeStart(),
timeLength());
}
int CAChordName::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::ChordName)
return -2;
if (static_cast<CAChordName*>(elt)->diatonicPitch() != diatonicPitch())
return 1;
if (static_cast<CAChordName*>(elt)->qualityModifier() != qualityModifier())
return 2;
return 0;
}
/*!
Transposes the chord for the given \a interval.
The new pitch is correctly bounded.
*/
CAChordName& CAChordName::operator+=(CAInterval interval)
{
if (diatonicPitch()!=CADiatonicPitch::Undefined) {
CADiatonicPitch p = diatonicPitch() + interval;
p.setNoteName(p.noteName() % 7);
if (p.noteName() < 0) {
p.setNoteName(p.noteName() + 7);
}
setDiatonicPitch(p);
}
return *this;
}
/*!
* \brief CAChordName::importFromLilyPond parses lilypondish syntax for chord name and applies it
* \param text chord name in lilypond syntax, for example "cis:m"
* \return True, if no errors encountered during parsing; False otherwise.
*/
bool CAChordName::importFromString(const QString& text)
{
int d = text.indexOf(':');
_diatonicPitch = CADiatonicPitch((d == -1) ? text : text.left(d));
if (_diatonicPitch.noteName() == CADiatonicPitch::Undefined) {
// syntax error
_qualityModifier = text;
return false;
}
if (d != -1) {
_qualityModifier = text.mid(d + 1);
} else {
_qualityModifier = "";
}
return true;
}
| 2,834
|
C++
|
.cpp
| 91
| 26.714286
| 126
| 0.691403
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,375
|
diatonicpitch.cpp
|
canorusmusic_canorus/src/score/diatonicpitch.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/diatonicpitch.h"
#include "score/diatonickey.h"
/*!
\class CADiatonicPitch
\brief Musical note pitch
This is a typical music presentation of the note pitch.
It consists of two properties:
- note name (C-0, D-1, E-2 etc.)
- accidentals (0-neutral, 1-one sharp, -1-one flat etc.)
Note name begins with sub-contra C.
Diatonic pitches can be compared with each other or only note names
and summed with intervals.
\sa CAInterval, operator+(), CAMidiDevice::diatonicPitchToMidi()
*/
CADiatonicPitch::CADiatonicPitch()
{
setNoteName(Undefined);
setAccs(0);
}
CADiatonicPitch::CADiatonicPitch(const QString& pitch)
{
setNoteName(Undefined);
setAccs(0);
QString noteName = pitch.toLower();
if (noteName[0].toLatin1() - 'a' > 6) {
// syntax error
return;
}
int curPitch = (noteName[0].toLatin1() - 'a' + 5) % 7;
if (!noteName.startsWith("as") && !noteName.startsWith("es"))
noteName.remove(0, 1); // remove one-letter note name
// determine accidentals
int curAccs = 0;
while (noteName.indexOf("is") != -1) {
curAccs++;
noteName.remove(0, noteName.indexOf("is") + 2);
}
while ((noteName.indexOf("es") != -1) || (noteName.indexOf("as") != -1)) {
curAccs--;
noteName.remove(0, ((noteName.indexOf("es") == -1) ? (noteName.indexOf("as") + 2) : (noteName.indexOf("es") + 2)));
}
if (noteName.size() > 0) {
// syntax error
return;
}
setNoteName(curPitch);
setAccs(curAccs);
}
CADiatonicPitch::CADiatonicPitch(const int& noteName, const int& accs)
{
setNoteName(noteName);
setAccs(accs);
}
bool CADiatonicPitch::operator==(CADiatonicPitch p)
{
if (noteName() == p.noteName() && accs() == p.accs())
return true;
else
return false;
}
bool CADiatonicPitch::operator==(int p)
{
if (noteName() == p)
return true;
else
return false;
}
/*!
Converts the music pitch to string.
*/
const QString CADiatonicPitch::diatonicPitchToString(CADiatonicPitch pitch)
{
if (pitch == Undefined) {
return "";
}
QString name;
name = static_cast<char>((pitch.noteName() + 2) % 7 + 'a');
for (int i = 0; i < pitch.accs(); i++)
name += "is"; // append as many -is-es as necessary
for (int i = 0; i > pitch.accs(); i--) {
if ((name == "e") || (name == "a"))
name += "s"; // for pitches E and A, only append single -s the first time
else if (name[0] == 'a')
name += "as"; // for pitch A, append -as instead of -es
else
name += "es"; // otherwise, append normally as many es-es as necessary
}
return name;
}
/*!
Calculates the new pitch using the old pitch + interval.
*/
CADiatonicPitch CADiatonicPitch::operator+(CAInterval i)
{
CADiatonicPitch dp(noteName(), accs());
// Leave diatonic pitch alone, if it is Undefined.
if (noteName() == Undefined) {
return dp;
}
// Only use positive intervals UP. If the interval is negative, inverse it:
if (i.quantity() < 0) {
if (i.quantity() != -1) {
// First lower the pitch for i octaves + 1,
dp.setNoteName(dp.noteName() + ((i.quantity() - 5) / 7) * 7);
} else {
// The exception is the negative prime (which actually doesn't exist, but we have to take care of it)
dp.setNoteName(dp.noteName() - 7);
}
// then inverse the interval. (negative prime becomes octave)
i = ~i;
// Below, the positive interval is now added to the lowered note.
}
dp.setNoteName(dp.noteName() + i.quantity() - 1);
int deltaAccs = 0;
int relP = noteName() % 7;
int relQnt = ((i.quantity() - 1) % 7) + 1;
switch (relQnt) { // major or perfect intervals up:
case CAInterval::Prime:
deltaAccs = 0;
break;
case CAInterval::Second:
if (relP == 2 || relP == 6)
deltaAccs = 1;
else
deltaAccs = 0;
break;
case CAInterval::Third:
if (relP == 0 || relP == 3 || relP == 4)
deltaAccs = 0;
else
deltaAccs = 1;
break;
case CAInterval::Fourth:
if (relP == 3)
deltaAccs = -1;
else
deltaAccs = 0;
break;
case CAInterval::Fifth:
if (relP == 6)
deltaAccs = 1;
else
deltaAccs = 0;
break;
case CAInterval::Sixth:
if (relP == 2 || relP == 5 || relP == 6)
deltaAccs = 1;
else
deltaAccs = 0;
break;
case CAInterval::Seventh:
if (relP == 0 || relP == 3)
deltaAccs = 0;
else
deltaAccs = 1;
break;
}
if (relQnt == 4 || relQnt == 5 || relQnt == 1) {
if (i.quality() < 0)
dp.setAccs(deltaAccs + dp.accs() + i.quality() + 1);
else if (i.quality() > 0)
dp.setAccs(deltaAccs + dp.accs() + i.quality() - 1);
else
dp.setAccs(deltaAccs + dp.accs());
} else {
if (i.quality() < 0)
dp.setAccs(deltaAccs + dp.accs() + i.quality());
else if (i.quality() > 0)
dp.setAccs(deltaAccs + dp.accs() + i.quality() - 1);
}
return dp;
}
/*!
Creates a new diatonic pitch from the given string.
*/
CADiatonicPitch CADiatonicPitch::diatonicPitchFromString(const QString s)
{
return CADiatonicPitch(s);
}
/*!
This function is provided for convenience.
\sa diatonicPitchFromMidiPitchKey()
*/
CADiatonicPitch CADiatonicPitch::diatonicPitchFromMidiPitch(int midiPitch, CAMidiPitchMode mode)
{
return diatonicPitchFromMidiPitchKey(midiPitch, CADiatonicKey("C"), mode);
}
/*!
Generates prefered diatonic pitch for the given \a midiPitch.
\a key tells generally which accidentals and note pitches to use.
\a mode tells which accidental is the preferred one, if the diatonic pitch
is unknown to the given key. If the auto mode is set, then C-major degrees
C#, D#, F#, G# and Bb are taken for the given key. These are the only
possible major thirds or minor sevenths of the Dominant chords of degrees.
\sa CAMidiPitchMode, diatonicPitchToMidiPitch
*/
CADiatonicPitch CADiatonicPitch::diatonicPitchFromMidiPitchKey(int midiPitch, CADiatonicKey key, CAMidiPitchMode mode)
{
int notePitch = 0, accs = 0;
double step = 7 / 12.0;
int octave = midiPitch / 12 - 1;
int rest = midiPitch % 12;
// calculate pitch to be a white key or a black key with sharp
CADiatonicPitch p;
p.setNoteName(qRound(step * static_cast<double>(rest) - 0.5 + 1.0 / 7 + octave * 7));
p.setAccs((diatonicPitchToMidiPitch(p) % 12) == rest ? 0 : 1);
// return the pitch, if it's natural to the key
if (key.containsPitch(p)) {
return p;
}
// try the degree lower / higher and adjust accidentals to have the same pitch
CADiatonicPitch pLower = p - CAInterval(CAInterval::Diminished, CAInterval::Second);
if (key.containsPitch(pLower)) {
return pLower;
}
CADiatonicPitch pHigher = p + CAInterval(CAInterval::Diminished, CAInterval::Second);
if (key.containsPitch(pHigher)) {
return pHigher;
}
// pitch not found naturally in the key, set the diatonic pitch according to the mode parameter
// first transpose the pitch to C-Major
CAInterval transposeInterval(CADiatonicPitch(0, 0), key.diatonicPitch());
if (key.gender() == CADiatonicKey::Minor) {
transposeInterval = transposeInterval + CAInterval(CAInterval::Major, CAInterval::Sixth); // interpret minor keys as major
}
transposeInterval.setQuantity(((transposeInterval.quantity() - 1) % 7) + 1);
octave = (midiPitch - transposeInterval.semitones()) / 12 - 1; // redefine octave with new key base
switch ((midiPitch + (12 - transposeInterval.semitones())) % 12) {
case 0:
notePitch = 0;
accs = 0;
break;
case 1:
switch (mode) {
case CADiatonicPitch::PreferAuto:
case CADiatonicPitch::PreferSharps:
notePitch = 0;
accs = 1;
break;
case CADiatonicPitch::PreferFlats:
notePitch = 1;
accs = -1;
break;
}
break;
case 2:
notePitch = 1;
accs = 0;
break;
case 3:
switch (mode) {
case CADiatonicPitch::PreferAuto:
case CADiatonicPitch::PreferSharps:
notePitch = 1;
accs = 1;
break;
case CADiatonicPitch::PreferFlats:
notePitch = 2;
accs = -1;
break;
}
break;
case 4:
notePitch = 2;
accs = 0;
break;
case 5:
notePitch = 3;
accs = 0;
break;
case 6:
switch (mode) {
case CADiatonicPitch::PreferAuto:
case CADiatonicPitch::PreferSharps:
notePitch = 3;
accs = 1;
break;
case CADiatonicPitch::PreferFlats:
notePitch = 4;
accs = -1;
break;
}
break;
case 7:
notePitch = 4;
accs = 0;
break;
case 8:
switch (mode) {
case CADiatonicPitch::PreferAuto:
case CADiatonicPitch::PreferSharps:
notePitch = 4;
accs = 1;
break;
case CADiatonicPitch::PreferFlats:
notePitch = 5;
accs = -1;
break;
}
break;
case 9:
notePitch = 5;
accs = 0;
break;
case 10:
switch (mode) {
case CADiatonicPitch::PreferSharps:
notePitch = 5;
accs = 1;
break;
case CADiatonicPitch::PreferAuto:
case CADiatonicPitch::PreferFlats:
notePitch = 6;
accs = -1;
break;
}
break;
case 11:
notePitch = 6;
accs = 0;
break;
}
notePitch += octave * 7;
return CADiatonicPitch(notePitch, accs) + transposeInterval;
}
/*!
Converts the given diatonic pitch (note name with octave and accidental) to
standard unsigned 7-bit MIDI pitch.
*/
int CADiatonicPitch::diatonicPitchToMidiPitch(const CADiatonicPitch& pitch)
{
// +0.3 - rounding factor for 7/12 that exactly underlays every tone in octave, if rounded
// +12 - our logical pitch starts at Sub-contra C, midi counting starts one octave lower
return qRound(pitch.noteName() * (12 / 7.0) + 0.3 + 12) + pitch.accs();
}
| 10,843
|
C++
|
.cpp
| 340
| 25.058824
| 130
| 0.599981
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,376
|
syllable.cpp
|
canorusmusic_canorus/src/score/syllable.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/syllable.h"
#include "score/mark.h"
/*!
\class CASyllable
\brief Lyrics under the note
This class represents one lyrics element above or below the note. It doesn't neccessarily consist of one
syllable or even a word, but can contain multiple syllables and words (using an underscore _ or a dash -).
Syllables are usually stored inside CALyricsContext.
Every lyrics element can finish with a hyphen (a horizontal middle line), with melisma (a horizontal
underscore line) or without line at the end of the word.
Each syllable can have a custom associated voice, if set. Usually parent's (lyrics context) voice is taken.
*/
/*!
Creates a new lyrics element with the given \a text, hyphenation \a hyphen and \a melisma properties, parent \a context,
\a timeStart and \a timeLength. \a voice is a special per-syllable associated voice (default 0 - takes parent's voice).
*/
CASyllable::CASyllable(QString text, bool hyphen, bool melisma, CALyricsContext* context, int timeStart, int timeLength, CAVoice* voice)
: CAMusElement(context, timeStart, timeLength)
{
setMusElementType(Syllable);
setText(text);
setHyphenStart(hyphen);
setMelismaStart(melisma);
setAssociatedVoice(voice);
}
CASyllable::~CASyllable()
{
}
/*!
Clears the text and sets the default hyphen and melisma settings.
This function is usually called when directly deleting the syllable - it shouldn't be actually removed, but only its
text set to empty.
*/
void CASyllable::clear()
{
setText("");
setHyphenStart(false);
setMelismaStart(false);
}
/*!
Clone the syllable using the given new context.
If the given context is not a lyrics context, 0 is used instead.
*/
CASyllable* CASyllable::clone(CAContext* context)
{
CALyricsContext* newContext = nullptr;
if (context->contextType() == CAContext::LyricsContext)
newContext = static_cast<CALyricsContext*>(context);
CASyllable* s = new CASyllable(text(), hyphenStart(), melismaStart(), newContext, timeStart(), timeLength(), associatedVoice());
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(s));
s->addMark(m);
}
return s;
}
int CASyllable::compare(CAMusElement* c)
{
if (c->musElementType() == CAMusElement::Syllable)
return 0;
else
return 1;
}
| 2,582
|
C++
|
.cpp
| 67
| 35.432836
| 136
| 0.741703
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,377
|
keysignature.cpp
|
canorusmusic_canorus/src/score/keysignature.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/keysignature.h"
#include "score/mark.h"
#include "score/staff.h"
/*!
\class CAKeySignature
\brief Represents a key signature sign in the staff
CAKeySignature represents a key signature sign (static accidentals) in the staff.
The actual key signature key is stored (depends on type though - currently only major/minor
diatonic keys are supported) in _diatonicKey.
\sa CADiatonicKey
*/
/*!
Creates a new key signature of type MajorMinor, diatonic key \a dKey, parent \a staff and \a timeStart.
Number of accidentals is a signed number, positive for sharps, negative for flats.
eg.
- 0 - C-Major
- -1 - F-Major
- +7 - Cis-Major etc.
*/
CAKeySignature::CAKeySignature(CADiatonicKey k, CAStaff* staff, int timeStart)
: CAMusElement(staff, timeStart)
{
setMusElementType(CAMusElement::KeySignature);
for (int i = 0; i < 7; i++)
_accidentals << 0;
setKeySignatureType(MajorMinor);
setDiatonicKey(k);
}
/*!
Creates a new key signature of type Modus, modus type \a m, parent \a staff and \a timeStart.
\todo Modus on different pitches
*/
CAKeySignature::CAKeySignature(CAModus m, CAStaff* staff, int timeStart)
: CAMusElement(staff, timeStart)
{
setMusElementType(CAMusElement::KeySignature);
for (int i = 0; i < 7; i++)
_accidentals << 0;
setKeySignatureType(Modus);
setModus(m);
}
/*!
\enum CAKeySignature::CAKeySignatureType
Type of the key signature:
- MajorMinor
Standard diatonic scale found by circle of fifths
- Modus
One of the moduses found in middle-age
- Custom
Custom scale. Modern scales, harmony of fourths, local scales
*/
/*!
\enum CAKeySignature::CAModus
Modus types:
- Ionian
- Dorian
- Phrygian
- Lydian
- Mixolydian
- Aeolian
- Locrian
- Hypodorian
- Hypolydian
- Hypomixolydian
- Hypophrygian
*/
/*!
\todo Implement non major-minor types
*/
void CAKeySignature::updateAccidentals()
{
if (keySignatureType() == MajorMinor) {
for (int i = 0; i < 7; i++) // clean up the _accidentals array
_accidentals[i] = 0;
// generate the _accidentals array according to the given number of the accidentals
// eg. _accidentals[3] = -1; means flat on the 3rd note (counting from 0), this means this key signature has Fes instead of F.
int idx = 3;
for (int i = 0; i < _diatonicKey.numberOfAccs(); i++) { // key signatures with sharps
_accidentals[idx] = 1;
idx = (idx + 4) % 7; // the circle of fifths in positive direction - add a Fifth
}
idx = 6;
for (int i = 0; i > _diatonicKey.numberOfAccs(); i--) { // key signatures with flats
_accidentals[idx] = -1;
idx = (idx + 3) % 7; // the circle of fifths in negative direction - add a Fourth
}
}
}
CAKeySignature::~CAKeySignature()
{
}
CAKeySignature* CAKeySignature::clone(CAContext* context)
{
CAKeySignature* k = nullptr;
switch (keySignatureType()) {
case MajorMinor:
k = new CAKeySignature(diatonicKey(), static_cast<CAStaff*>(context), timeStart());
break;
case Modus:
case Custom:
break;
}
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(k));
k->addMark(m);
}
return k;
}
int CAKeySignature::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::KeySignature)
return -1;
int diffs = 0;
if (keySignatureType() != static_cast<CAKeySignature*>(elt)->keySignatureType())
diffs++;
else {
if (keySignatureType() == MajorMinor)
if (diatonicKey() != static_cast<CAKeySignature*>(elt)->diatonicKey())
diffs++;
}
return diffs;
}
CAKeySignature::CAKeySignatureType CAKeySignature::keySignatureTypeFromString(const QString type)
{
if (type == "major-minor") {
return MajorMinor;
} else if (type == "modus") {
return Modus;
} else if (type == "custom") {
return Custom;
} else
return Custom;
}
const QString CAKeySignature::keySignatureTypeToString(const CAKeySignatureType type)
{
switch (type) {
case MajorMinor:
return "major-minor";
case Modus:
return "modus";
case Custom:
return "custom";
}
return "";
}
const QString CAKeySignature::modusToString(CAModus modus)
{
switch (modus) {
case Ionian:
return "ionian";
case Dorian:
return "dorian";
case Phrygian:
return "phrygian";
case Lydian:
return "lydian";
case Mixolydian:
return "mixolydian";
case Aeolian:
return "aeolian";
case Locrian:
return "locrian";
case Hypodorian:
return "hypodorian";
case Hypolydian:
return "hypolydian";
case Hypomixolydian:
return "hypomixolydian";
case Hypophrygian:
return "hypophrygian";
}
return "";
}
CAKeySignature::CAModus CAKeySignature::modusFromString(const QString modus)
{
if (modus == "ionian")
return Ionian;
else if (modus == "dorian")
return Dorian;
else if (modus == "phrygian")
return Phrygian;
else if (modus == "lydian")
return Lydian;
else if (modus == "mixolydian")
return Mixolydian;
else if (modus == "aeolian")
return Aeolian;
else if (modus == "locrian")
return Locrian;
else if (modus == "hypodorian")
return Hypodorian;
else if (modus == "hypolydian")
return Hypolydian;
else if (modus == "hypomixolydian")
return Hypomixolydian;
else if (modus == "hypophrygian")
return Hypophrygian;
else
return Ionian;
}
/*!
\fn CAKeySignature::accidentals()
Returns the array of accidentals for every level in the scale.
The levels can have the following values:
- 0 - natural
- 1 - sharp
- 2 - double sharp
- ...
- -1 - flat
- -2 - double flat
- ...
*/
/*!
\var CAKeySignature::_accidentals
Accidentals configuration for each level.
Indexes: [0..6] - C, D, E, F ... B
Values: 0 - none, -1 - flat, +1 - sharp
\sa accidentals(), numberOfAccidentals()
*/
| 6,444
|
C++
|
.cpp
| 224
| 23.977679
| 134
| 0.656861
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,378
|
timesignature.cpp
|
canorusmusic_canorus/src/score/timesignature.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "score/timesignature.h"
#include "score/mark.h"
#include "score/playablelength.h"
#include "score/staff.h"
/*!
\class CATimeSignature
\brief Represents a time signature in the staff
This class is used for different time signatures in the score.
Every staff has its own time signature object.
Time signatures are non-playable objects (timeLength=0) aka signs.
Time signature object is common to all the voices in one staff
Time signature consists of the upper number - number of beats and the lower number - beat.
Internal values _beats and _beat represent these values.
\sa CADrawableTimeSignature, CAKeySignature, CAClef, CAStaff
*/
/*!
\enum CATimeSignature::CATimeSignatureType
Type of time signature to be shown.
Possible options:
- Classical
C for 4/4, C| for 2/2, numbers otherwise. This is default behaviour.
- Number
Always show beats/beat, for 4/4 as well
- Mensural
Taken from LilyPond. Mensural layout.
- Neomensural
Taken from LilyPond. Neomensural layout.
- Baroque
Taken from LilyPond. Baroque layout.
\sa timeSignatureType()
*/
/*!
Creates a time signature with a beat \a beat, number of beats \a beats, parent \a staff, \a
startTime and of given \a type.
eg. 3/4 time signature should be called new CATimeSignature(3, 4, staff, startTime);
*/
CATimeSignature::CATimeSignature(int beats, int beat, CAStaff* staff, int startTime, CATimeSignatureType type)
: CAMusElement(staff, startTime)
{
_musElementType = CAMusElement::TimeSignature;
_beats = beats;
_beat = beat;
_timeSignatureType = type;
}
CATimeSignature::~CATimeSignature()
{
}
CATimeSignature* CATimeSignature::clone(CAContext* context)
{
CATimeSignature* t = new CATimeSignature(_beats, _beat, static_cast<CAStaff*>(context), _timeStart, _timeSignatureType);
for (int i = 0; i < markList().size(); i++) {
CAMark* m = static_cast<CAMark*>(markList()[i]->clone(t));
t->addMark(m);
}
return t;
}
/*! \deprecated Use timeSignatureTypeToString() instead. This should be moved to LilyPond parser. -Matevz
*/
const QString CATimeSignature::timeSignatureTypeML()
{
switch (_timeSignatureType) {
case Classical:
return QString("classical");
case Number:
return QString("number");
case Mensural:
return QString("mensural");
case Neomensural:
return QString("neomensural");
case Baroque:
return QString("baroque");
}
return "";
}
/*!
\deprecated New CanorusML parser uses beat and beats directly as integer. The following code
should be moved to LilyPond parser. -Matevz
*/
const QString CATimeSignature::timeSignatureML()
{
return (QString::number(_beats) + "/" + QString::number(_beat));
}
int CATimeSignature::compare(CAMusElement* elt)
{
if (elt->musElementType() != CAMusElement::TimeSignature)
return -1;
int diffs = 0;
if (_timeSignatureType != static_cast<CATimeSignature*>(elt)->timeSignatureType())
diffs++;
if (_beat != static_cast<CATimeSignature*>(elt)->beat())
diffs++;
if (_beats != static_cast<CATimeSignature*>(elt)->beats())
diffs++;
return diffs;
}
const QString CATimeSignature::timeSignatureTypeToString(CATimeSignatureType type)
{
switch (type) {
case Classical:
return "classical";
case Number:
return "number";
case Mensural:
return "mensural";
case Neomensural:
return "neomensural";
case Baroque:
return "baroque";
}
return "";
}
CATimeSignature::CATimeSignatureType CATimeSignature::timeSignatureTypeFromString(const QString type)
{
if (type == "classical")
return Classical;
else if (type == "number")
return Number;
else if (type == "mensural")
return Mensural;
else if (type == "neomensural")
return Neomensural;
else if (type == "baroque")
return Baroque;
else
return Classical;
}
/*!
* Returns the duration of a full measure in time units.
*/
int CATimeSignature::barDuration()
{
return CAPlayableLength::musicLengthToTimeLength(static_cast<CAPlayableLength::CAMusicLength>(_beat)) * _beats;
}
/*!
\fn CATimeSignature::beats()
Returns the number of beats of this time signature.
\sa setBeats(), _beats, _beat
*/
/*!
\fn CATimeSignature::setBeats(int beats)
Sets the number of beats to \a beats for this time signature.
\sa beats(), _beats, _beat
*/
/*!
\fn CATimeSignature::beat()
Returns the beat of this time signature.
\sa setBeat(), _beat, _beats
*/
/*!
\fn CATimeSignature::setBeat(int beat)
Sets the beat to \a beat for this time signature.
\sa beat(), _beat, _beats
*/
/*!
\fn CATimeSignature::timeSignatureType()
Returns type of the time signature.
\sa _timeSignatureType, CATimeSignatureType
*/
/*!
\fn CATimeSignature::_beats
Number of beats of this time signature.
That's the upper number in the time signature.
\sa beats(), setBeats(), _beat
*/
/*!
\fn CATimeSignature::_beat
Beat of this time signature.
That's the lower number in the time signature.
\sa beat(), setBeat(), _beats
*/
/*!
\fn CATimeSignature::_timeSignatureType
Stores the type of the time signature.
\sa timeSignatureType(), CATimeSignatureType
*/
| 5,495
|
C++
|
.cpp
| 180
| 27.05
| 124
| 0.718483
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,379
|
helpbrowser.cpp
|
canorusmusic_canorus/src/widgets/helpbrowser.cpp
|
/*!
Copyright (c) 2009, Itay Perl, Canorus development team
Copyright (c) 2016, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "widgets/helpbrowser.h"
#include <QFile>
#include <QTextStream>
CAHelpBrowser::CAHelpBrowser(QWidget* parent)
#if QT_VERSION >= 0x050600
: QWebEngineView(parent)
#else
: QWebView(parent)
#endif
{
}
| 491
|
C++
|
.cpp
| 17
| 26.823529
| 76
| 0.772824
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,380
|
tabwidget.cpp
|
canorusmusic_canorus/src/widgets/tabwidget.cpp
|
/*!
Copyright (c) 2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "widgets/tabwidget.h"
#include <QMouseEvent>
#include <QTabBar>
/*!
\class CATabWidget
\brief Tab widget for the score view inside the main window
This class is usually used to store multiple sheets inside the main window.
For now it offers double-click new sheet shortcut and movable tabs.
*/
CATabWidget::CATabWidget(QWidget* parent)
: QTabWidget(parent)
{
setMovable(false);
connect(tabBar(), SIGNAL(tabMoved(int, int)), this, SIGNAL(CAMoveTab(int, int)));
}
CATabWidget::~CATabWidget()
{
}
/*!
Processes the double click on empty space for the new tab action.
The event needs to be implemented in the TabBar and not TabWidget to effect
the double clicks inside the tab area only.
*/
void CATabWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->y() > tabBar()->y() && tabBar()->tabAt(event->pos()) == -1) {
emit CANewTab();
}
}
/*!
Disable moving sheets, if only one present.
*/
void CATabWidget::tabInserted(int)
{
setMovable(count() >= 2);
}
/*!
Disable moving sheets, if only one present.
*/
void CATabWidget::tabRemoved(int)
{
setMovable(count() >= 2);
}
| 1,346
|
C++
|
.cpp
| 48
| 25.854167
| 85
| 0.737781
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,381
|
progressstatusbar.cpp
|
canorusmusic_canorus/src/widgets/progressstatusbar.cpp
|
/*!
Copyright (c) 2009, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QLabel>
#include <QProgressBar>
#include <QPushButton>
#include "widgets/progressstatusbar.h"
CAProgressStatusBar::CAProgressStatusBar(QWidget* parent)
: QStatusBar(parent)
, _progressLabel(new QLabel("", this))
, _progressBar(new QProgressBar(this))
, _cancelButton(new QPushButton(tr("Cancel"), this))
{
addWidget(_progressLabel);
addWidget(_progressBar);
addWidget(_cancelButton);
connect(_cancelButton, SIGNAL(clicked(bool)), this, SLOT(on_cancelButton_clicked(bool)));
}
CAProgressStatusBar::~CAProgressStatusBar()
{
delete _progressLabel;
delete _progressBar;
delete _cancelButton;
}
void CAProgressStatusBar::on_cancelButton_clicked(bool c)
{
_cancelButton->setEnabled(false);
emit(cancelButtonClicked(c));
}
void CAProgressStatusBar::setProgress(QString label, int value)
{
_progressLabel->setText(label);
_progressBar->setValue(value);
}
void CAProgressStatusBar::setProgress(int value)
{
_progressBar->setValue(value);
}
void CAProgressStatusBar::setProgress(QString label)
{
_progressLabel->setText(label);
}
| 1,322
|
C++
|
.cpp
| 44
| 27.181818
| 93
| 0.765588
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,382
|
undotoolbutton.cpp
|
canorusmusic_canorus/src/widgets/undotoolbutton.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "widgets/undotoolbutton.h"
#include "canorus.h"
#include "core/undo.h"
#include "core/undocommand.h"
#include <QAction>
#include <QWheelEvent>
CAUndoToolButton::CAUndoToolButton(QIcon icon, CAUndoToolButtonType type, QWidget* parent)
: CAToolButton(parent)
{
setCheckable(false);
setIcon(icon);
_icon = icon;
setCurrentId(0);
setUndoType(type);
_listWidget = new QListWidget;
_listWidget->setMouseTracking(true);
_listWidget->setSelectionMode(QListWidget::MultiSelection);
setPopupWidget(_listWidget);
connect(_listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onListWidgetItemClicked(QListWidgetItem*)));
connect(_listWidget, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(onListWidgetItemEntered(QListWidgetItem*)));
}
CAUndoToolButton::~CAUndoToolButton()
{
delete _listWidget;
}
void CAUndoToolButton::wheelEvent(QWheelEvent*)
{
// do nothing!
}
void CAUndoToolButton::onListWidgetItemClicked(QListWidgetItem* item)
{
hideButtons();
emit toggled(false, _listWidget->row(item));
}
void CAUndoToolButton::onListWidgetItemEntered(QListWidgetItem* item)
{
for (int i = 0; i < _listWidget->count(); i++)
_listWidget->item(i)->setSelected(i <= _listWidget->row(item));
}
void CAUndoToolButton::showButtons()
{
_listWidget->clear();
if (mainWin()) {
QList<CAUndoCommand*>* stack = CACanorus::undo()->undoStack(mainWin()->document());
if (undoType() == Undo) {
for (int i = CACanorus::undo()->undoIndex(mainWin()->document()), delta = 0;
i >= 0 && delta < 20; /// \todo This should be set to maxUndo steps
i--, delta++)
_listWidget->addItem(stack->at(i)->text());
} else if (undoType() == Redo) {
for (int i = CACanorus::undo()->undoIndex(mainWin()->document()) + 1, delta = 0;
i < stack->size() && delta < 20; /// \todo This should be set to maxUndo steps
i++, delta++)
_listWidget->addItem(stack->at(i)->text());
}
}
CAToolButton::showButtons();
}
void CAUndoToolButton::setDefaultAction(QAction* action)
{
CAToolButton::setDefaultAction(action);
if (defaultAction()) {
defaultAction()->setCheckable(false);
defaultAction()->setIcon(_icon);
}
}
| 2,570
|
C++
|
.cpp
| 71
| 31.084507
| 119
| 0.67498
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,383
|
lcdnumber.cpp
|
canorusmusic_canorus/src/widgets/lcdnumber.cpp
|
/** @file widgets/numberdisplay.cpp
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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 "LICENSE.GPL"). If not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
*---------------------------------------------------------------------------
*
* Copyright (c) 2006, Reinhard Katzmann, Canorus development team
* All Rights Reserved. See AUTHORS for a complete list of authors.
*
*/
#include "lcdnumber.h"
#include <QAction>
#include <QMouseEvent>
#include <QToolTip>
#include <stdio.h>
CALCDNumber::CALCDNumber(int iMin, int iMax, QWidget* poParent /* = 0 */,
QString oText /* = "" */)
: QLCDNumber(poParent)
{
// Do not allow a larger minimum than maximum
if (iMin > iMax)
iMin = iMax;
min_ = iMin;
max_ = iMax;
setRealValue(0); // 0 = All!
//setMaximumSize (20, 60);
setToolTip(oText);
}
void CALCDNumber::setRealValue(int iVal)
{
if ((iVal <= max_) && (iVal >= 0))
realValue_ = iVal;
// 0 = All => Display letter "A" from Hex
if (realValue_ == 0) {
QLCDNumber::setMode(QLCDNumber::Hex);
display(10);
} else {
QLCDNumber::setMode(QLCDNumber::Dec);
display(realValue_);
}
emit valChanged(iVal);
}
int CALCDNumber::getRealValue()
{
return realValue_;
}
void CALCDNumber::setMin(int iMin)
{
// Do not allow a larger minimum than maximum
if (iMin > max_)
return;
min_ = iMin;
if (min_ > getRealValue()) {
setRealValue(min_);
}
}
void CALCDNumber::setMax(int iMax)
{
// Do not allow a larger minimum than maximum
if (iMax < min_)
return;
max_ = iMax;
if (max_ < getRealValue()) {
setRealValue(max_);
}
}
bool CALCDNumber::isZero()
{
return getRealValue() == 0;
}
void CALCDNumber::mousePressEvent(QMouseEvent* poEvt)
{
int iNewVal;
switch (poEvt->button()) {
case Qt::LeftButton:
iNewVal = getRealValue() + 1;
if (iNewVal > max_)
break;
setRealValue(iNewVal);
break;
default:
iNewVal = getRealValue() - 1;
if (iNewVal < min_)
break;
setRealValue(iNewVal);
break;
}
}
void CALCDNumber::wheelEvent(QWheelEvent* poEvt)
{
int iNewVal;
if (poEvt->delta() < 0) {
iNewVal = getRealValue() + 1;
if (iNewVal > max_)
return;
setRealValue(iNewVal);
} else if (poEvt->delta() > 0) {
iNewVal = getRealValue() - 1;
if (iNewVal < min_)
return;
setRealValue(iNewVal);
}
}
| 3,690
|
C++
|
.cpp
| 115
| 22.530435
| 77
| 0.521056
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,384
|
actionseditor.cpp
|
canorusmusic_canorus/src/widgets/actionseditor.cpp
|
/*!
Copyright (c) 2006-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
This code is based on
smplayer, GUI front-end for mplayer, v0.6.7.
Copyright (C) 2006-2009 Ricardo Villalba <rvm@escomposlinux.org>
which again based it on qq14-actioneditor-code.zip from Qt
and heavily adapted to our needs.
*/
#include "actionseditor.h"
#include <QHeaderView>
#include <QTableWidget>
#include <QAction>
#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QKeyEvent>
#include <QLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QObject>
#include <QPushButton>
#include <QRegExp>
#include <QSettings>
#include <QString>
#include <QTextStream>
//#include "images.h"
#include "canorus.h"
#include "core/settings.h"
// Number of columns used: Command, Context, Shortcut, Midi Command, Combined
#define COL_NUM 5
// Definition of column positions
enum actionCol {
COL_COMMAND = 0, // name of the command (not internal!)
COL_DESCRIPTION = 1, // Context of the command like mode
COL_SHORTCUT = 2, // Keyboard shortcut
COL_MIDI = 3, // Midi command
COL_MIDISCUT = 4 // Requires Midi and Shortcut at one time to be used
};
/*
#if USE_MULTIPLE_SHORTCUTS
QString ActionsEditor::shortcutsToString(QList <QKeySequence> shortcuts_list) {
QString accelText = "";
for (int n=0; n < shortcuts_list.count(); n++) {
accelText += shortcuts_list[n].toString(QKeySequence::PortableText);
if (n < (shortcuts_list.count()-1)) accelText += ", ";
}
return accelText;
}
QList <QKeySequence> ActionsEditor::stringToShortcuts(QString shortcuts) {
QList <QKeySequence> shortcuts_list;
QStringList l = shortcuts.split(',');
for (int n=0; n < l.count(); n++) {
//qDebug("%s", l[n].toUtf8().data());
// Qt (at least on linux) seems to have a problem when using Traditional Chinese
// QKeysequence deletes the arrow key names from the shortcut
// so this is a work-around.
QString s = l[n].simplified();
//Work-around for Simplified-Chinese
s.replace( QString::fromUtf8("左"), "Left");
s.replace( QString::fromUtf8("下"), "Down");
s.replace( QString::fromUtf8("右"), "Right");
s.replace( QString::fromUtf8("上"), "Up");
shortcuts_list.append( s );
//qDebug("ActionsEditor::stringToShortcuts: shortcut %d: '%s'", n, s.toUtf8().data());
}
return shortcuts_list;
}
#endif
*/
CAActionsEditor::CAActionsEditor(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
// Get directory used last time to adapt default directory to it.
latest_dir = CACanorus::settings()->latestShortcutsDirectory().dirName();
actionsTable = new QTableWidget(0, COL_NUM, this);
actionsTable->setSelectionMode(QAbstractItemView::SingleSelection);
actionsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
actionsTable->verticalHeader()->hide();
actionsTable->horizontalHeader()->setSectionResizeMode(COL_COMMAND, QHeaderView::Stretch);
actionsTable->horizontalHeader()->setSectionResizeMode(COL_DESCRIPTION, QHeaderView::Stretch);
actionsTable->setAlternatingRowColors(true);
//#if USE_SHORTCUTGETTER
// actionsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
actionsTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
//#endif
//actionsTable->setItemDelegateForColumn( COL_SHORTCUT, new MyDelegate(actionsTable) );
//#if !USE_SHORTCUTGETTER // In place editing of shortcut ??
connect(actionsTable, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
this, SLOT(recordAction(QTableWidgetItem*)));
connect(actionsTable, SIGNAL(itemChanged(QTableWidgetItem*)),
this, SLOT(validateAction(QTableWidgetItem*)));
//#else
connect(actionsTable, SIGNAL(itemActivated(QTableWidgetItem*)),
this, SLOT(editShortcut()));
//#endif
saveButton = new QPushButton(this);
loadButton = new QPushButton(this);
connect(saveButton, SIGNAL(clicked()), this, SLOT(saveActionsTable()));
connect(loadButton, SIGNAL(clicked()), this, SLOT(loadActionsTable()));
//#if USE_SHORTCUTGETTER
editButton = new QPushButton(this);
connect(editButton, SIGNAL(clicked()), this, SLOT(editShortcut()));
//#endif
QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->setSpacing(8);
//#if USE_SHORTCUTGETTER
buttonLayout->addWidget(editButton);
//#endif
buttonLayout->addStretch(1);
buttonLayout->addWidget(loadButton);
buttonLayout->addWidget(saveButton);
QVBoxLayout* mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(8);
mainLayout->setSpacing(8);
mainLayout->addWidget(actionsTable);
mainLayout->addLayout(buttonLayout);
retranslateStrings();
}
CAActionsEditor::~CAActionsEditor()
{
}
void CAActionsEditor::retranslateStrings()
{
actionsTable->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Description") << tr("Shortcut") << tr("Midi Command") << tr("Combined"));
//saveButton->setIcon(Images::icon("save"));
//loadButton->setIcon(Images::icon("open"));
saveButton->setText(tr("&Save shortcuts..."));
loadButton->setText(tr("&Load shortcuts..."));
//#if USE_SHORTCUTGETTER
editButton->setText(tr("&Change shortcut..."));
//#endif
//updateView(); // The actions are translated later, so it's useless
}
bool CAActionsEditor::isEmpty()
{
return m_actionsList.isEmpty();
}
void CAActionsEditor::clear()
{
m_actionsList.clear();
}
void CAActionsEditor::addActions(const QList<CASingleAction*>& actionList)
{
CASingleAction* action;
// Issue: Actions not associated to objects anymore due to
// Step that converts QAction -> CASingleAction
//QList<CASingleAction *> actions = widget->findChildren<CASingleAction *>();
//qWarning() << "CAActionsEditor::addActions - size " << actions.size() << " orig size " << widget->actions().size() << endl;
//QList<QAction *> actions = widget->actions();
for (int n = 0; n < actionList.size(); n++) {
action = actionList[n];
//action->getAction()->setParent(this);
qWarning() << "CAActionsEditor::addActions - objectName " << action->getAction()->objectName() << " inherits " << action->getAction()->inherits("QWidgetAction") << endl;
if (!action->getAction()->objectName().isEmpty() && !action->getAction()->inherits("QWidgetAction"))
m_actionsList.append(action);
}
updateView();
}
void CAActionsEditor::updateView()
{
actionsTable->setRowCount(m_actionsList.count());
CASingleAction* action;
QString accelText, midi_com, midi_scut, description;
//#if !USE_SHORTCUTGETTER
// dont_validate = true;
//#endif
//actionsTable->setSortingEnabled(false);
// @ToDo: Replace with our own list of Canorus actions
for (int n = 0; n < m_actionsList.count(); n++) {
action = m_actionsList[n];
//#if USE_MULTIPLE_SHORTCUTS
// accelText = shortcutsToString( action->shortcuts() );
//#else
accelText = action->getShortCutAsString();
//#endif
description = action->getDescription();
midi_com = action->getMidiKeySequence();
midi_scut = action->getMidiShortCutCombined();
QTableWidgetItem* i_conf = new QTableWidgetItem();
// Command column
QTableWidgetItem* i_command = new QTableWidgetItem(action->getCommandName(true));
// Context column
QTableWidgetItem* i_context = new QTableWidgetItem(description);
// Shortcut column
QTableWidgetItem* i_shortcut = new QTableWidgetItem(accelText);
// Midi command
QTableWidgetItem* i_midi = new QTableWidgetItem(midi_com);
// Midi command
QTableWidgetItem* i_midiscut = new QTableWidgetItem(midi_scut);
// Set flags
//#if !USE_SHORTCUTGETTER
// i_conf->setFlags(Qt::ItemIsEnabled);
// i_command->setFlags(Qt::ItemIsEnabled);
// i_context->setFlags(Qt::ItemIsEnabled);
//#else
i_conf->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
i_command->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
i_context->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
i_shortcut->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEnabled);
i_midi->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
i_midiscut->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
//#endif
// Add items to table
actionsTable->setItem(n, COL_COMMAND, i_command);
actionsTable->setItem(n, COL_DESCRIPTION, i_context);
actionsTable->setItem(n, COL_SHORTCUT, i_shortcut);
actionsTable->setItem(n, COL_MIDI, i_midi);
actionsTable->setItem(n, COL_MIDISCUT, i_midiscut);
}
hasConflicts(); // Check for conflicts
actionsTable->resizeColumnsToContents();
// @ToDo: Set to last edited cell type (Midi or Shortcut ?)
actionsTable->setCurrentCell(0, COL_SHORTCUT);
//#if !USE_SHORTCUTGETTER
dont_validate = false;
//#endif
//actionsTable->setSortingEnabled(true);
}
void CAActionsEditor::applyChanges()
{
qDebug("CAActionsEditor::applyChanges");
for (int row = 0; row < m_actionsList.size(); ++row) {
CASingleAction* action = m_actionsList[row];
QTableWidgetItem* i = actionsTable->item(row, COL_SHORTCUT);
//#if USE_MULTIPLE_SHORTCUTS
// action->setShortcuts( stringToShortcuts(i->text()) );
//#else
// @ToDo Update Midi/Shortcut corresponding but
// Update our own list of settings
action->setShortCutAsString(QKeySequence(i->text()).toString());
//#endif
}
}
CAActionsEditor::fileType CAActionsEditor::getFType(const QString& suffix)
{
CAActionsEditor::fileType type = FT_SHORTCUT;
if (suffix == "cakey")
type = FT_SHORTCUT;
if (suffix == "cakmid")
type = FT_MIDI;
if (suffix == "cacks")
type = FT_MIDISCUT;
return type;
}
//#if !USE_SHORTCUTGETTER
void CAActionsEditor::recordAction(QTableWidgetItem* i)
{
//qDebug("CAActionsEditor::recordAction");
int iCol = i->column();
//QTableWidgetItem * i = actionsTable->currentItem();
if (iCol == COL_SHORTCUT) {
//qDebug("CAActionsEditor::recordAction: %d %d %s", i->row(), i->column(), i->text().toUtf8().data());
oldAccelText = i->text();
} else if (iCol == COL_MIDI)
oldMidiText = i->text();
}
void CAActionsEditor::validateAction(QTableWidgetItem* i)
{
//qDebug("CAActionsEditor::validateAction");
if (dont_validate)
return;
int iCol = i->column();
if (iCol == COL_SHORTCUT) {
QString accelText = QKeySequence(i->text()).toString();
if (accelText.isEmpty() && !i->text().isEmpty()) {
/*
QAction * action = static_cast<QAction*> (actionsList[i->row()]);
QString oldAccelText= action->accel().toString();
*/
i->setText(oldAccelText);
} else {
i->setText(accelText);
}
// @ToDo: Only optional beep ?
if (hasConflicts())
qApp->beep();
} else if (iCol == COL_MIDI) {
QString midiText = i->text();
if (midiText.isEmpty() && !i->text().isEmpty()) {
/*
QAction * action = static_cast<QAction*> (actionsList[i->row()]);
QString oldAccelText= action->accel().toString();
*/
i->setText(oldMidiText);
} else {
i->setText(midiText);
}
// @ToDo: Only optional beep ?
if (hasConflicts())
qApp->beep();
}
}
void CAActionsEditor::editShortcut()
{
QTableWidgetItem* i = actionsTable->item(actionsTable->currentRow(), COL_SHORTCUT);
if (i) {
ShortcutGetter d(this);
QString result = d.exec(i->text());
if (!result.isNull()) {
QString accelText = QKeySequence(result).toString(QKeySequence::PortableText);
i->setText(accelText);
if (hasConflicts())
qApp->beep();
}
}
}
int CAActionsEditor::findActionCommand(const QString& name)
{
for (int row = 0; row < actionsTable->rowCount(); row++) {
if (actionsTable->item(row, COL_COMMAND)->text() == name)
return row;
}
return -1;
}
int CAActionsEditor::findActionAccel(const QString& accel, int ignoreRow)
{
for (int row = 0; row < actionsTable->rowCount(); row++) {
QTableWidgetItem* i = actionsTable->item(row, COL_SHORTCUT);
if ((i) && (i->text() == accel)) {
if (ignoreRow == -1)
return row;
else if (ignoreRow != row)
return row;
}
}
return -1;
}
int CAActionsEditor::findActionMidi(const QString& midi, int ignoreRow)
{
for (int row = 0; row < actionsTable->rowCount(); row++) {
QTableWidgetItem* i = actionsTable->item(row, COL_MIDI);
if ((i) && (i->text() == midi)) {
if (ignoreRow == -1)
return row;
else if (ignoreRow != row)
return row;
}
}
return -1;
}
bool CAActionsEditor::hasConflicts(bool bMidi)
{
// @ToDo: Consider if we should have two different conflict columns
int found, iType = bMidi ? COL_MIDI : COL_SHORTCUT;
bool conflict = false;
QString accelText;
QTableWidgetItem* i;
for (int n = 0; n < actionsTable->rowCount(); n++) {
//i = actionsTable->item( n, COL_CONFLICTS );
i = actionsTable->item(n, iType);
if (i)
i->setIcon(QPixmap());
if (i) {
accelText = i->text();
if (!accelText.isEmpty()) {
found = bMidi ? findActionMidi(accelText, n) : findActionAccel(accelText, n);
if ((found != -1) && (found != n)) {
conflict = true;
}
}
}
}
//if (conflict) qApp->beep();
return conflict;
}
void CAActionsEditor::saveActionsTable()
{
QString sk;
sk = tr("Shortcut files") + " (*.cakey);;" + tr("Midi Key Sequence files") + " (*.cakmid);;" + tr("Combined Key Sequence files") + "(*.cacks)";
QString s = QFileDialog::getSaveFileName(
this, tr("Choose a filename"),
latest_dir, sk);
QFileInfo shortCutFileInfo(s);
if (!s.isEmpty()) {
// If filename has no extension, add it
/*if (QFileInfo(s).completeSuffix().isEmpty()) {
s = s + end;
}*/
if (QFileInfo(s).exists()) {
int res = QMessageBox::question(this,
tr("Confirm overwrite?"),
tr("The file %1 already exists.\n"
"Do you want to overwrite?")
.arg(s),
QMessageBox::Yes,
QMessageBox::No,
Qt::NoButton);
if (res == QMessageBox::No) {
return;
}
}
latest_dir = QFileInfo(s).absolutePath();
enum fileType type = getFType(shortCutFileInfo.completeSuffix());
bool r = saveActionsTable(s, type);
if (!r) {
QMessageBox::warning(this, tr("Error"),
tr("The file couldn't be saved"),
QMessageBox::Ok, Qt::NoButton);
}
}
}
bool CAActionsEditor::saveActionsTable(const QString& filename, enum fileType type /* = FT_SHORTCUT */)
{
qDebug("CAActionsEditor::saveActions: '%s'", filename.toUtf8().data());
QFile f(filename);
if (f.open(QIODevice::WriteOnly)) {
QTextStream stream(&f);
QString accelText;
stream.setCodec("UTF-8");
// @ToDo: Pretty Format output by adding \t as necessary
for (int row = 0; row < actionsTable->rowCount(); row++) {
stream << actionsTable->item(row, COL_COMMAND)->text() << "\t"
<< actionsTable->item(row, COL_DESCRIPTION)->text() << "\t";
if (type == FT_SHORTCUT /*|| type == FT_MIDISCUT*/) {
accelText = actionsTable->item(row, COL_SHORTCUT)->text();
if (accelText.isEmpty())
accelText = "none";
stream << accelText << "\t";
}
stream << actionsTable->item(row, COL_MIDI)->text() << "\n";
}
f.close();
return true;
}
return false;
}
void CAActionsEditor::loadActionsTable()
{
QString sk;
sk = tr("Shortcut files") + " (*.cakey *.cakmid *.cacks)";
QString s = QFileDialog::getOpenFileName(
this, tr("Choose a file"),
latest_dir, sk);
QFileInfo shortCutFileInfo(s);
enum fileType type = getFType(shortCutFileInfo.completeSuffix());
if (!s.isEmpty()) {
latest_dir = QFileInfo(s).absolutePath();
bool r = loadActionsTable(s, type);
if (!r) {
QMessageBox::warning(this, tr("Error"),
tr("The file couldn't be loaded"),
QMessageBox::Ok, Qt::NoButton);
}
}
}
bool CAActionsEditor::loadActionsTable(const QString& filename, enum fileType type /* = FT_SHORTCUT */)
{
qDebug("CAActionsEditor::loadActions: '%s'", filename.toUtf8().data());
// Lines with '#' (comments) will be ignored
QRegExp rx("^(.*)\\t|\\s*(.*)\\t|\\s*(.*)\\t|\\s*(.*)\\t|\\s*(.*)\\t|\\s*(.*)");
int row = -1;
QFile f(filename);
if (f.open(QIODevice::ReadOnly)) {
//#if !USE_SHORTCUTGETTER
dont_validate = true;
//#endif
QTextStream stream(&f);
stream.setCodec("UTF-8");
QString line;
QString command, context, accelText, midiText;
while (!stream.atEnd()) {
line = stream.readLine();
qDebug("line: '%s'", line.toUtf8().data());
if (rx.indexIn(line) > -1) {
command = rx.cap(1);
context = rx.cap(2);
if (type == FT_SHORTCUT /*|| type == FT_MIDISCUT*/) {
accelText = rx.cap(3);
if (accelText == "none")
accelText.clear();
midiText = rx.cap(4) + " " + rx.cap(5) + " " + rx.cap(6);
qDebug(" command: '%s' context: '%s' accel: '%s' midi: '%s'",
command.toUtf8().data(), context.toUtf8().data(),
accelText.toUtf8().data(), midiText.toUtf8().data());
// @ToDo: command name is not identical to command identifier!
row = findActionCommand(command);
if (row > -1) {
qDebug("Action found!");
actionsTable->item(row, COL_SHORTCUT)->setText(accelText);
}
}
if (type == FT_MIDI /*|| type == FT_MIDISCUT*/) {
midiText = rx.cap(3) + " " + rx.cap(4) + " " + rx.cap(5);
qDebug(" command: '%s' context: '%s' midi: '%s'",
command.toUtf8().data(), accelText.toUtf8().data(), midiText.toUtf8().data());
}
actionsTable->item(row, COL_MIDI)->setText(accelText);
} else {
qDebug(" wrong line");
}
}
f.close();
hasConflicts(); // Check for conflicts
//#if !USE_SHORTCUTGETTER
dont_validate = false;
//#endif
return true;
} else {
return false;
}
}
// Static functions
void CAActionsEditor::saveToConfig(QWidget* widget, QSettings* set)
{
qDebug("ActionsEditor::saveToConfig");
set->beginGroup("actions");
CASingleAction* action;
// Issue: Actions not associated to objects anymore due to
// Step that converts QAction -> CASingleAction
//QList<CASingleAction *> actions = o->findChildren<CASingleAction *>();
QString accelText;
QList<QAction*> actions = widget->actions();
for (int n = 0; n < actions.count(); n++) {
action = reinterpret_cast<CASingleAction*>(actions[n]);
if (!action->getAction()->text().isEmpty() && !action->getAction()->inherits("QWidgetAction")) {
//#if USE_MULTIPLE_SHORTCUTS
// accelText = shortcutsToString(action->shortcuts());
//#else
accelText = action->getShortCutAsString();
//#endif
if (accelText.isEmpty())
set->setValue(action->getAction()->text(), "none");
else
set->setValue(action->getAction()->text(), accelText);
}
}
set->endGroup();
}
void CAActionsEditor::loadFromConfig(QWidget* widget, QSettings* set)
{
qDebug("ActionsEditor::loadFromConfig");
set->beginGroup("actions");
CASingleAction* action;
QString accelText;
// Issue: Actions not associated to objects anymore due to
// Step that converts QAction -> CASingleAction
//QList<CASingleAction *> actions = o->findChildren<CASingleAction *>();
//#if USE_MULTIPLE_SHORTCUTS
// QString current;
//#endif
QList<QAction*> actions = widget->actions();
for (int n = 0; n < actions.count(); n++) {
action = reinterpret_cast<CASingleAction*>(actions[n]);
if (!action->getAction()->objectName().isEmpty() && !action->getAction()->inherits("QWidgetAction")) {
//#if USE_MULTIPLE_SHORTCUTS
// current = shortcutsToString(action->shortcuts());
// accelText = set->value(action->objectName(), current).toString();
// action->setShortcuts( stringToShortcuts( accelText ) );
//#else
accelText = set->value(action->getAction()->text(), action->getShortCutAsString()).toString();
if (accelText != "none")
action->setShortCutAsString(QKeySequence(accelText).toString());
//#endif
}
}
set->endGroup();
}
CASingleAction* CAActionsEditor::findAction(QWidget* widget, const QString& name)
{
CASingleAction* action;
// Issue: Actions not associated to objects anymore due to
// Step that converts QAction -> CASingleAction
//QList<CASingleAction *> actions = o->findChildren<CASingleAction *>();
QList<QAction*> actions = widget->actions();
for (int n = 0; n < actions.count(); n++) {
action = reinterpret_cast<CASingleAction*>(actions[n]);
if (name == action->getAction()->objectName())
return action;
}
return nullptr;
}
QStringList CAActionsEditor::actionsNames(QWidget* widget)
{
QStringList l;
CASingleAction* action;
// Issue: Actions not associated to objects anymore due to
// Step that converts QAction -> CASingleAction
//QList<CASingleAction *> actions = o->findChildren<CASingleAction *>();
QList<QAction*> actions = widget->actions();
for (int n = 0; n < actions.count(); n++) {
action = reinterpret_cast<CASingleAction*>(actions[n]);
//qDebug("action name: '%s'", action->objectName().toUtf8().data());
//qDebug("action name: '%s'", action->text().toUtf8().data());
if (!action->getAction()->text().isEmpty())
l.append(action->getAction()->text());
}
return l;
}
// Language change stuff
void CAActionsEditor::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
retranslateStrings();
} else {
QWidget::changeEvent(e);
}
}
static QString keyToString(int k)
{
if (k == Qt::Key_Shift || k == Qt::Key_Control || k == Qt::Key_Meta || k == Qt::Key_Alt || k == Qt::Key_AltGr)
return QString();
return QKeySequence(k).toString();
}
static QStringList modToString(Qt::KeyboardModifiers k)
{
//qDebug("modToString: k: %x", (int) k);
QStringList l;
if (k & Qt::ShiftModifier)
l << "Shift";
if (k & Qt::ControlModifier)
l << "Ctrl";
if (k & Qt::AltModifier)
l << "Alt";
if (k & Qt::MetaModifier)
l << "Meta";
if (k & Qt::GroupSwitchModifier)
;
if (k & Qt::KeypadModifier)
;
return l;
}
ShortcutGetter::ShortcutGetter(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Modify shortcut"));
QVBoxLayout* vbox = new QVBoxLayout(this);
vbox->setMargin(2);
vbox->setSpacing(4);
QLabel* l = new QLabel(this);
l->setText(tr("Press the key combination you want to assign"));
vbox->addWidget(l);
leKey = new QLineEdit(this);
leKey->installEventFilter(this);
vbox->addWidget(leKey);
// Change by rvm: use a QDialogButtonBox instead of QPushButtons
// and add a clear button
setCaptureKeyboard(true);
QDialogButtonBox* buttonbox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Reset);
QPushButton* clearbutton = buttonbox->button(QDialogButtonBox::Reset);
clearbutton->setText(tr("Clear"));
QPushButton* captureButton = new QPushButton(tr("Capture"), this);
captureButton->setToolTip(tr("Capture keystrokes"));
captureButton->setCheckable(captureKeyboard());
captureButton->setChecked(captureKeyboard());
connect(captureButton, SIGNAL(toggled(bool)),
this, SLOT(setCaptureKeyboard(bool)));
buttonbox->addButton(captureButton, QDialogButtonBox::ActionRole);
connect(buttonbox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonbox, SIGNAL(rejected()), this, SLOT(reject()));
connect(clearbutton, SIGNAL(clicked()), leKey, SLOT(clear()));
vbox->addWidget(buttonbox);
}
void ShortcutGetter::setCaptureKeyboard(bool b)
{
capture = b;
leKey->setReadOnly(b);
leKey->setFocus();
}
QString ShortcutGetter::exec(const QString& s)
{
bStop = false;
leKey->setText(s);
if (QDialog::exec() == QDialog::Accepted)
return leKey->text();
return QString();
}
bool ShortcutGetter::event(QEvent* e)
{
if (!capture)
return QDialog::event(e);
QString key;
QStringList mods;
QKeyEvent* k = static_cast<QKeyEvent*>(e);
switch (e->type()) {
case QEvent::KeyPress:
if (bStop) {
lKeys.clear();
bStop = false;
}
key = keyToString(k->key());
mods = modToString(k->modifiers());
//qDebug("event: key.count: %d, mods.count: %d", key.count(), mods.count());
if (key.count() || mods.count()) {
if (key.count() && !lKeys.contains(key))
lKeys << key;
foreach (key, mods)
if (!lKeys.contains(key))
lKeys << key;
} else {
key = k->text();
if (!lKeys.contains(key))
lKeys << key;
}
setText();
break;
case QEvent::KeyRelease:
bStop = true;
break;
/*
case QEvent::ShortcutOverride :
leKey->setText("Shortcut override");
break;
*/
default:
return QDialog::event(e);
}
return true;
}
bool ShortcutGetter::eventFilter(QObject* o, QEvent* e)
{
if (!capture)
return QDialog::eventFilter(o, e);
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease)
return event(e);
else
return QDialog::eventFilter(o, e);
}
void ShortcutGetter::setText()
{
QStringList seq;
if (lKeys.contains("Shift"))
seq << "Shift";
if (lKeys.contains("Ctrl"))
seq << "Ctrl";
if (lKeys.contains("Alt"))
seq << "Alt";
if (lKeys.contains("Meta"))
seq << "Meta";
foreach (QString s, lKeys) {
//qDebug("setText: s: '%s'", s.toUtf8().data());
if (s != "Shift" && s != "Ctrl"
&& s != "Alt" && s != "Meta")
seq << s;
}
leKey->setText(seq.join("+"));
//leKey->selectAll();
}
| 27,996
|
C++
|
.cpp
| 741
| 30.634278
| 177
| 0.614663
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,385
|
pyconsole.cpp
|
canorusmusic_canorus/src/widgets/pyconsole.cpp
|
/*!
Copyright (c) 2006-2020, Štefan Sakalík, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "scripting/swigpython.h" // Must be included first (includes Python.h).
#include "canorus.h"
#include "interface/plugin.h"
#include "interface/pluginmanager.h"
#include "widgets/pyconsole.h"
#include <QKeyEvent>
#include <qwaitcondition.h>
#include <stdio.h>
#ifdef USE_PYTHON
/*!
\class CAPyConsole
\brief Canorus console widget
Class CAPyConsole is the GUI part of Canorus python-based command line interface.
Utilizes CAPyConsoleInterface and pycli plugin to provide the functionality needed.
\warning exit() terminates whole Canorus
\warning trying to execute more than one pyCLI (from CLI menu) => undefined behaviour
When plugin tries to interact with this; it calls asyncInput
-> when plugin is terminated, mutexes must be cleared
Still under development (beta)
*/
// --python shell emulation; script interaction--
// document as parameter won't work (solved like in pluginaction.cpp)
/// \todo pycli: interactive help won't work. More sys.std* overrides?
/// \todo command queuing, when busy
/// \todo [CRLF on windows] in QTextEdit & python
/// \todo (design) remove unnecessary _fmtNormal changes
/// \todo processes
// --Behaviour, internal commands (at the bottom of source)--
/// \todo redesign 2: CAPyConsole TextWidget (future)
/// \todo design: history <-> text edition <-> text changed signal <-> text Revert
/// \todo design: specify behaviour
//
/// \todo maybe TABS? -> anyone wants this?
//
//
// Internal commands: are entered to python shell
// looks like this "/commandx", have / at the beginning
// are interpreted in canorus not python
// "/callscript <script>", "/entryfunc", "entryfunc <function>"
//
// /todo autoindentation, internal variable (like in idle), test it!
CAPyConsole::CAPyConsole(CADocument* doc, QWidget* parent)
: QTextEdit(parent)
{
_parent = parent;
_canorusDoc = doc;
_strEntryFunc = "main";
_histIndex = -1;
_bufSend = "";
_strInput = "";
_bIgnTxtChange = false;
_iCurStart = 0;
setUndoRedoEnabled(false);
setFontFamily("Courier 10 Pitch");
setFontPointSize(9);
auto txt = "Welcome to the Python CLI. In addition to standard python CLI, you can use\n"
" /callscript path_to_script.py to call external script\n"
" /entryfunc entry_function to set or display entry function in script ran by /callscript\n"
" document variable to manipulate canorus itself\n"
" CanorusPython library to create Canorus objects\n"
"\n"
">>> ";
setText(txt);
// Above string obviously is smaller then sizeof(int)
_iCurStart = static_cast<int>(strlen(txt));
_fmtStderr = _fmtStdout = _fmtNormal = currentCharFormat();
_fmtStdout.setForeground(QColor(0, 0, 255));
_fmtStderr.setForeground(QColor(255, 0, 0));
// this must be set for on_txtChanged [_bIgnTxtChange=false] not to crash
_curInput = QTextCursor(document());
_curInput.movePosition(QTextCursor::End);
// slots
qRegisterMetaType<TxtType>("TxtType");
connect(this, SIGNAL(textChanged()), SLOT(on_txtChanged()));
connect(this, SIGNAL(cursorPositionChanged()), SLOT(on_posChanged()));
connect(this, SIGNAL(selectionChanged()), SLOT(on_selChanged()));
connect(this, SIGNAL(currentCharFormatChanged(const QTextCharFormat&)), SLOT(on_fmtChanged()));
// thread
connect(this, SIGNAL(sig_txtAppend(const QString&, TxtType)), SLOT(txtAppend(const QString&, TxtType)), Qt::QueuedConnection);
connect(this, SIGNAL(sig_syncPluginInit()), SLOT(syncPluginInit()), Qt::QueuedConnection);
_thrWaitMut = new QMutex();
_thrWait = new QWaitCondition();
_thrIntrWaitMut = new QMutex();
_thrIntrWait = new QWaitCondition();
}
// --------------------------------
// ----------FUNCTIONS-------------
// --------------------------------
/*!
Revert text to previous state (like undo)
*/
void CAPyConsole::txtRevert()
{
_bIgnTxtChange = true;
clear();
QList<TxtFragment*>::iterator i;
for (i = _txtFixed.begin(); i != _txtFixed.end(); i++) {
switch ((*i)->type) {
case txtNormal:
setCurrentCharFormat(_fmtNormal);
break;
case txtStdout:
setCurrentCharFormat(_fmtStdout);
break;
case txtStderr:
setCurrentCharFormat(_fmtStderr);
break;
}
insertPlainText((*i)->text);
}
setCurrentCharFormat(_fmtNormal);
insertPlainText(_strInput);
_bIgnTxtChange = false;
}
/*!
Get console input text. In most cases call txtGetInput()
if bReadText is true, input will be reconstructed from text [used in on_txtChanged]
otherwise, _strInput will be returned (default)
*/
QString CAPyConsole::txtGetInput(bool bReadText)
{
if (bReadText) {
_curInput.setPosition(_iCurStart);
_curInput.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
return _curInput.selectedText();
} else
return _strInput;
}
/*!
Set console input text. In most cases call txtSetInput(QString bUpdateText)
if bUpdateText is false,_strInput will be just set, [used in on_txtChanged]
otherwise, text in console will be updated
*/
void CAPyConsole::txtSetInput(QString input, bool bUpdateText)
{
_strInput = input;
if (bUpdateText) {
bool ignWasSet = _bIgnTxtChange;
_bIgnTxtChange = true;
_curInput.setPosition(_iCurStart);
_curInput.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
_curInput.insertText(_strInput);
_bIgnTxtChange = ignWasSet;
}
}
// --------------------------------
// -------------SLOTS--------------
// --------------------------------
/*!
Appends text at the end of the documents; no extra newlines.
emit sig_txtAppend, if accessed from thread (it is slot too)
WARNING: it also updates cursor positions => user input is lost
*/
void CAPyConsole::txtAppend(const QString& text, TxtType txtType)
{
_bIgnTxtChange = true;
// backup
_tf = new TxtFragment;
_tf->text = text;
_tf->type = txtType;
_txtFixed += _tf;
moveCursor(QTextCursor::End);
switch (txtType) {
case txtNormal:
setCurrentCharFormat(_fmtNormal);
break;
case txtStdout:
setCurrentCharFormat(_fmtStdout);
break;
case txtStderr:
setCurrentCharFormat(_fmtStderr);
break;
}
insertPlainText(text);
setCurrentCharFormat(_fmtNormal);
_iCurStart = _iCurNowOld = _iCurNow = textCursor().position();
_strInput = "";
ensureCursorVisible();
_bIgnTxtChange = false;
}
/*!
Slot for textChanged signal.
Input is after '>>> ', user can edit it: _strInput
Text before '>>> ' inclusive -> is not editable: _txtFixed
So, the text in the widget might be changed:
Allowed change:
1) user changes input -> save input into the variable (yes, after each keystroke)
2) output from python arrives
Not allowed change:
3) user attempts to change fixed text. It must be reverted into previous state
*/
void CAPyConsole::on_txtChanged()
{
if (_bIgnTxtChange) // for example on_txtChanged() changes text sometimes, too
return;
// cursor is/was in not allowed position; revert
if ((_iCurNow < _iCurStart) || (_iCurNowOld < _iCurStart)) {
_bIgnTxtChange = true;
int icno = _iCurNowOld; // save cursor pos. before text was modified
txtRevert();
_iCurNowOld = _iCurNow = icno;
_curNew = textCursor();
_curNew.setPosition(_iCurNow);
setTextCursor(_curNew);
setCurrentCharFormat(_fmtNormal);
_bIgnTxtChange = false;
} else {
// input was changed, update it -> special setInput and getInput calls, see doc
txtSetInput(txtGetInput(true), false);
}
ensureCursorVisible();
}
/*!
Tracks the position of the cursor.
Saves old new cursor position.
If old or new cursor pos is in the forbidden area, then on_txtChanged will revert the operation
Undo/Redo mechanism is not used, because it's hard to control (or impossible?) Undo marks.
Also we need to forbit user to undo
*/
void CAPyConsole::on_posChanged()
{
_iCurNowOld = _iCurNow;
_iCurNow = textCursor().position();
if (_iCurNow == _iCurStart) // TextCursor can change format
setCurrentCharFormat(_fmtNormal);
}
/*!
\todo: implementation
User can with selected text overwrite non-overwritable text
*/
void CAPyConsole::on_selChanged()
{
}
/*!
\todo: implementation maybe?
*/
void CAPyConsole::on_fmtChanged()
{
}
// --------------------------------
// --------THREAD-RELATED----------
// --------------------------------
/*!
when plugin initializes
\todo: no more pyCLIs than one
\todo: is this approach safe? (future)
*/
void CAPyConsole::syncPluginInit(void)
{
if (_parent != nullptr)
_parent->show();
setFocus(Qt::OtherFocusReason);
}
/*!
Emit signal sig_syncPluginInit -> slot syncPluginInit (synchronized)
*/
void CAPyConsole::asyncPluginInit(void)
{
emit sig_syncPluginInit();
}
/*!
Pycli calls this function (through CAPyConsoleInterface) to get input from the console
\todo: remove QString prompt; (do we need to know which prompt is used ps1/ps2?)
*/
QString CAPyConsole::asyncBufferedInput(QString prompt)
{
emit sig_txtAppend(prompt, txtNormal);
// blocking operation;
PyThreadState_Swap(CASwigPython::mainThreadState);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
//Py_BEGIN_ALLOW_THREADS
_thrWaitMut->lock();
_thrWait->wait(_thrWaitMut);
//Py_END_ALLOW_THREADS
PyEval_RestoreThread(CASwigPython::mainThreadState);
PyThreadState_Swap(CASwigPython::pycliThreadState);
QString* str = new QString(_bufSend); //put contents of _bufSend into buffer \todo: synch
if (_bufSend == "html") {
std::cout << toHtml().toLatin1().data() << std::endl;
}
_bufSend = "";
_thrWaitMut->unlock();
return *str;
}
/*
Pycli calls this function (through CAPyConsoleInterface) to send some output to console
*/
void CAPyConsole::asyncBufferedOutput(QString bufInp, bool bStdErr)
{
emit sig_txtAppend(bufInp, bStdErr ? txtStderr : txtStdout);
}
void CAPyConsole::asyncKeyboardInterrupt()
{
Py_BEGIN_ALLOW_THREADS
_thrIntrWaitMut->lock();
_thrIntrWait->wait(_thrIntrWaitMut);
_thrIntrWaitMut->unlock();
Py_END_ALLOW_THREADS
}
// --------------------------------
// -------EVENTS,BEHAVIOUR---------
// --------------------------------
// history, hist* functions take care of _strInput
void CAPyConsole::histAdd()
{
// dont add "" to history
if (_strInput == "")
return;
// dont add item, that's already at the end
if (!_histList.isEmpty())
if (_strInput == _histList[0])
return;
_histIndex = -1;
_histList.prepend(_strInput);
}
void CAPyConsole::histGet(HistLay histLay)
{
moveCursor(QTextCursor::End);
if (_histList.isEmpty())
return;
// error check (just for debugging)
if (_histIndex < -1) {
std::cout << "ERROR!: PyConsole->histGet index below -1" << std::endl;
_histIndex = -1;
} else if (_histIndex >= _histList.size()) {
std::cout << "ERROR!: PyConsole->histGet index above MAX" << std::endl;
_histIndex = _histList.size();
}
if (_histIndex == -1)
_histOldInput = txtGetInput();
else
_histList[_histIndex] = txtGetInput();
if (histLay == histPrev)
_histIndex++;
else // must be histNext
_histIndex--;
if (_histIndex < 0) {
_histIndex = -1;
txtSetInput(_histOldInput);
return;
} else if (_histIndex >= _histList.size())
_histIndex = _histList.size() - 1;
txtSetInput(_histList[_histIndex]);
}
/*
Watches for some keyboard events:
Enter pressed: run the command
\todo queue
*/
void CAPyConsole::keyPressEvent(QKeyEvent* e)
{
bool defCase = false;
//sometimes it's Key_Enter instead of Key_Return, weird
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
histAdd();
_bufSend = txtGetInput();
_tf = new TxtFragment;
_tf->text = _strInput + "\n";
_tf->type = txtNormal;
_txtFixed += _tf;
txtAppend("\n"); //update all necessary pointers, and stuff
if (!cmdIntern(_bufSend))
_thrWait->wakeOne();
break;
case Qt::Key_Up:
histGet(histPrev);
break;
case Qt::Key_Down:
histGet(histNext);
break;
case Qt::Key_Left:
if (_iCurNow <= _iCurStart) {
_iCurNowOld = _iCurNow = _iCurStart;
_curNew = textCursor();
_curNew.setPosition(_iCurNow);
setTextCursor(_curNew);
setCurrentCharFormat(_fmtNormal);
} else
defCase = true;
break;
case Qt::Key_Home:
_iCurNowOld = _iCurNow = _iCurStart;
_curNew = textCursor();
_curNew.setPosition(_iCurNow);
setTextCursor(_curNew);
setCurrentCharFormat(_fmtNormal);
break;
case Qt::Key_Backspace:
if (_iCurNow > _iCurStart)
defCase = true;
break;
default:
defCase = true;
break;
}
if (defCase) { // enhanced default: (switch)
if (_iCurNow == _iCurStart)
setCurrentCharFormat(_fmtNormal);
QTextEdit::keyPressEvent(e);
}
}
// --------------------------------
// -------INTERNAL-COMMANDS--------
// --------------------------------
// internal commands start with "/"
// none of this works, because of some threading issues
bool CAPyConsole::cmdIntern(QString strCmd)
{
// TODO(stefan): we are handling everything with cmdIntern now. If this works we can completely remove the old pycli.
// Handle all txt input this method.
// if (!strCmd.startsWith("/"))
// return false;
if (strCmd == "/i") {
txtAppend("[Can't reset PyCLI]\n");
/*
txtAppend("[Resetting PyCLI...]");
_bufSend = "";
CASwigPython::terminatePycli();
_thrIntrWait->wakeOne();
CAPlugin *plug;
if(plug = CAPluginManager::getPluginByName("pyCLI")){
plug->callActionByName("pycli", 0, _canorusDoc);
}
*/
return true;
} else if (strCmd.startsWith("/callscript ")) {
if (!QFile::exists("scripts:" + strCmd.mid(12))) {
txtAppend("Script not found\n", txtStderr);
txtAppend(">>> ", txtNormal);
return true;
}
QList<PyObject*> argsPython;
QObject* curObject = this;
while (dynamic_cast<CAMainWin*>(curObject) == nullptr && curObject != nullptr) // find the parent which is mainwindow
curObject = curObject->parent();
PyEval_RestoreThread(CASwigPython::mainThreadState);
argsPython << CASwigPython::toPythonObject(static_cast<CAMainWin*>(curObject)->document(), CASwigPython::Document);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
CASwigPython::callFunction(QFileInfo("scripts:" + strCmd.mid(12)).absoluteFilePath(), _strEntryFunc, argsPython, true);
emit sig_txtAppend(">>> ", txtNormal); // if not emitted, error from python and this are not in order
return true;
}
else if (strCmd == "/entryfunc") {
txtAppend("Default entry function: " + _strEntryFunc + "\n", txtStdout);
txtAppend(">>> ", txtNormal);
}
else if (strCmd.startsWith("/entryfunc ")) {
_strEntryFunc = strCmd.mid(11);
txtAppend(">>> ", txtNormal);
} else {
// TODO(stefan): DRY this from the other if condition.
QList<PyObject*> argsPython;
QObject* curObject = this;
while (dynamic_cast<CAMainWin*>(curObject) == nullptr && curObject != nullptr) // find the parent which is mainwindow
curObject = curObject->parent();
PyEval_RestoreThread(CASwigPython::mainThreadState);
argsPython << CASwigPython::toPythonObject(static_cast<CAMainWin*>(curObject)->document(), CASwigPython::Document);
argsPython << PyUnicode_FromString(strCmd.toStdString().c_str());
PyEval_ReleaseThread(CASwigPython::mainThreadState);
// Can't autoreload because we are using global objects in pycl2.py that would get overwritten.
auto ret = CASwigPython::callFunction(QFileInfo("scripts:pycl2.py").absoluteFilePath(), "main", argsPython, false);
if (ret==nullptr) {
return false;
}
emit sig_txtAppend(PyUnicode_AsUTF8(ret), txtNormal);
return true;
}
return true;
}
#else
// If there is no python, generate dummy functions
void CAPyConsole::txtAppend(QString const&, CAPyConsole::TxtType) {}
void CAPyConsole::on_txtChanged() {}
void CAPyConsole::on_posChanged() {}
void CAPyConsole::on_selChanged() {}
void CAPyConsole::on_fmtChanged() {}
void CAPyConsole::syncPluginInit() {}
void CAPyConsole::keyPressEvent(QKeyEvent* e) {}
#endif //USE_PYTHON
| 17,446
|
C++
|
.cpp
| 486
| 30.506173
| 130
| 0.647802
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,386
|
toolbutton.cpp
|
canorusmusic_canorus/src/widgets/toolbutton.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "widgets/toolbutton.h"
#include "ui/mainwin.h"
#include <QDesktopWidget>
#include <QMainWindow>
#include <QMouseEvent>
#include <QScreen>
#include <QStyle>
#include <QStyleOptionToolButton>
/*!
\class CAToolButton
\brief Tool button with a menu at the side
This widget looks like a button with a small dropdown arrow at the side which opens a
custom widget (also called "buttons") where user chooses from various actions then.
When the element is selected, the action's icon is replaced with the previous icon on
the toolbutton and a signal toggled(bool checked, int id) is emitted.
\remarks Subclasses must call setPopupWidget() on the floating widget once it's initialized. Showing/hiding is handled in CAToolButton. Subclasses can connect to the show() or hide() signals, which are emitted just before showing or hiding the widget.
*/
CAToolButton::CAToolButton(QWidget* parent)
: QToolButton(parent)
{
setMainWin(parent ? dynamic_cast<CAMainWin*>(parent) : nullptr);
setPopupMode(QToolButton::MenuButtonPopup);
_popupWidget = new CAToolButtonPopup();
}
CAToolButton::~CAToolButton()
{
delete _popupWidget;
}
/*!
Shows the popup widget if it's set
*/
void CAToolButton::showButtons()
{
if (_popupWidget) {
_popupWidget->move(calculateTopLeft(_popupWidget->sizeHint()));
_popupWidget->show();
}
}
/*!
Hides the popup widget if it's set
*/
void CAToolButton::hideButtons()
{
if (_popupWidget) {
_popupWidget->hide();
}
}
/*!
This function is overriden here in order to show buttons when clicked on the arrow.
*/
void CAToolButton::mousePressEvent(QMouseEvent* e)
{
QStyleOptionToolButton opt;
opt.init(this);
opt.subControls |= QStyle::SC_ToolButtonMenu;
opt.features |= QStyleOptionToolButton::Menu;
QRect popupr = style()->subControlRect(QStyle::CC_ToolButton, &opt,
QStyle::SC_ToolButtonMenu, this);
if (popupr.isValid() && popupr.contains(e->pos())) {
if (!buttonsVisible()) {
showButtons();
} else {
hideButtons();
}
}
QToolButton::mousePressEvent(e);
}
/*!
Emits toggled( bool, int ) signal.
\sa handleToggled()
*/
void CAToolButton::handleTriggered()
{
if (!defaultAction()->isCheckable())
emit toggled(false, currentId());
}
/*!
Emits toggled( bool, int ) signal.
\sa handleTriggered()
*/
void CAToolButton::handleToggled(bool checked)
{
emit toggled(checked, currentId());
}
/*!
Sets the new default action \a a and connects some signals to custom slots made
by CAMenuToolButton. Also calls QToolButton::setDefaultAction().
*/
void CAToolButton::setDefaultAction(QAction* a)
{
if (defaultAction()) {
disconnect(defaultAction(), SIGNAL(toggled(bool)), this, SLOT(handleToggled(bool)));
disconnect(defaultAction(), SIGNAL(triggered()), this, SLOT(handleTriggered()));
}
connect(a, SIGNAL(toggled(bool)), this, SLOT(handleToggled(bool)));
connect(a, SIGNAL(triggered()), this, SLOT(handleTriggered()));
a->setCheckable(true);
QToolButton::setDefaultAction(a);
}
/*!
This function returns the absolute top-left coordinate where the popup menu or whichever
widget should appear when the users clicks on the button.
The problem is that the popup widget should be completely visible in whichever part of
the screen the toolbutton is located. Popup widget should also always stick to one corner
of the toolbutton.
Parameter \a size is the width and height needed for the whole widget to appear.
*/
QPoint CAToolButton::calculateTopLeft(QSize size)
{
int x = 0, y = 0;
QToolBar* toolBar = dynamic_cast<QToolBar*>(parent());
if (mainWin() && toolBar) {
QPoint topLeft = mapToGlobal(QPoint(0, 0)); // get the absolute coordinates of top-left corner of the button
QPoint screenBottomRight = QGuiApplication::primaryScreen()->availableGeometry().bottomRight();
// Set popup menu coordinates which fit on screen.
if (mainWin()->toolBarArea(toolBar) == Qt::LeftToolBarArea) {
if (topLeft.x() + width() + size.width() > screenBottomRight.x())
x = screenBottomRight.x() - size.width();
else
x = topLeft.x() + width();
if (topLeft.y() + size.height() > screenBottomRight.y())
y = screenBottomRight.y() - size.height();
else
y = topLeft.y();
} else if (mainWin()->toolBarArea(toolBar) == Qt::TopToolBarArea) {
if (topLeft.x() + size.width() > screenBottomRight.x())
x = screenBottomRight.x() - size.width();
else
x = topLeft.x();
if (topLeft.y() + height() + size.height() > screenBottomRight.y())
y = screenBottomRight.y() - size.height();
else
y = topLeft.y() + height();
} else if (mainWin()->toolBarArea(toolBar) == Qt::RightToolBarArea) {
if (topLeft.x() - size.width() < 0)
x = 0;
else
x = topLeft.x() - size.width();
if (topLeft.y() + size.height() > screenBottomRight.y())
y = screenBottomRight.y() - size.height();
else
y = topLeft.y();
} else if (mainWin()->toolBarArea(toolBar) == Qt::BottomToolBarArea) {
if (topLeft.x() + size.width() > screenBottomRight.x())
x = screenBottomRight.x() - size.width();
else
x = topLeft.x();
if (topLeft.y() - size.height() < 0)
y = 0;
else
y = topLeft.y() - size.height();
}
}
return QPoint(x, y);
}
| 5,950
|
C++
|
.cpp
| 160
| 31.23125
| 252
| 0.655262
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,387
|
midirecorderview.cpp
|
canorusmusic_canorus/src/widgets/midirecorderview.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include "widgets/midirecorderview.h"
#include "core/midirecorder.h"
#include "canorus.h"
#include <QAction>
#include <QDir>
CAMidiRecorderView::CAMidiRecorderView(CAMidiRecorder* r, QWidget* parent)
: QDockWidget(parent)
, _midiRecorder(r)
{
setupUi(this); // initialize elements created by Qt Designer
setupCustomUi();
_status = Idle;
}
CAMidiRecorderView::~CAMidiRecorderView()
{
if (midiRecorder()) {
delete midiRecorder();
setMidiRecorder(nullptr);
}
if (parent() && dynamic_cast<CAMainWin*>(parent())) {
static_cast<CAMainWin*>(parent())->setMidiRecorderView(nullptr);
}
}
void CAMidiRecorderView::setupCustomUi()
{
setAttribute(Qt::WA_DeleteOnClose, true);
_timer = new QTimer();
_timer->setInterval(1000);
_timer->start();
connect(_timer, SIGNAL(timeout()), this, SLOT(onTimerTimeout()));
uiTime->setText("0:00");
uiRecord->setEnabled(true);
uiPause->setVisible(false);
uiStop->setEnabled(false);
}
void CAMidiRecorderView::onTimerTimeout()
{
if (_midiRecorder) {
if (uiTime->text().isEmpty() || _status != Pause) {
uiTime->setText(QString("%1:%2").arg((_midiRecorder->curTime() / 1000) / 60).arg((_midiRecorder->curTime() / 1000) % 60, 2, 10, QChar('0')));
} else {
uiTime->setText("");
}
}
}
void CAMidiRecorderView::on_uiPause_clicked(bool)
{
uiPause->setVisible(false);
uiRecord->setVisible(true);
_midiRecorder->pauseRecording();
_status = Pause;
}
void CAMidiRecorderView::on_uiStop_clicked(bool)
{
uiRecord->setVisible(true);
uiPause->setVisible(false);
uiStop->setEnabled(false);
_midiRecorder->stopRecording();
_status = Idle;
}
void CAMidiRecorderView::on_uiRecord_clicked(bool)
{
uiRecord->setVisible(false);
uiPause->setVisible(true);
uiStop->setEnabled(true);
_midiRecorder->startRecording();
_status = Recording;
}
| 2,184
|
C++
|
.cpp
| 73
| 25.739726
| 153
| 0.688038
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,388
|
menutoolbutton.cpp
|
canorusmusic_canorus/src/widgets/menutoolbutton.cpp
|
/*!
Copyright (c) 2006-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QApplication>
#include <QDesktopWidget>
#include <QMainWindow>
#include <QStyleOptionToolButton>
#include <QStylePainter>
#include <QToolBar>
#include <QWheelEvent>
#include <QWidgetAction>
#include "ui/mainwin.h"
#include "widgets/menutoolbutton.h"
// Prevent buttons from staying sunken when they're not checked
void CAGroupBoxToolButton::paintEvent(QPaintEvent*)
{
QStylePainter p(this);
QStyleOptionToolButton opt;
initStyleOption(&opt);
if (!isChecked() && (opt.state & QStyle::State_Sunken))
opt.state = (opt.state ^ QStyle::State_Sunken) | QStyle::State_Raised;
p.drawComplexControl(QStyle::CC_ToolButton, opt);
}
/*!
\class CAMenuToolButton
\brief Tool button with a menu at the side and a button box when clicked on
This widget looks like a button with a small dropdown arrow at the side which opens a
button group box of various elements. User can add buttons by calling
addButton(QIcon icon, int Id). When the element is selected, the action's icon is
switched to the selected element's and a signal toggled(bool checked, int id) is emitted.
The class primarily consists of 3 elements:
- the base class QToolButton with enabled side menu
- QButtonGroup
The backend list of buttons and their Ids (QGroupBox doesn't support button Ids)
- QGroupBox
The widget that is shown when menu arrow is clicked.
*/
/*!
Constructs the button menu with the given \a title and \a parent.
*/
CAMenuToolButton::CAMenuToolButton(QString title, int numIconsRow, QWidget* parent)
: CAToolButton(parent)
{
setSpacing(4);
setLayoutMargin(5);
setMargin(0);
setCheckable(true);
setNumIconsPerRow(numIconsRow);
// Size policy: Expanding / Expanding
QSizePolicy boxSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
boxSizePolicy.setHorizontalStretch(0);
boxSizePolicy.setVerticalStretch(0);
QSizePolicy widgetSizePolicy = sizePolicy();
boxSizePolicy.setHeightForWidth(widgetSizePolicy.hasHeightForWidth());
// Visual group box for the button menu
_groupBox = new QGroupBox(title, nullptr);
boxSizePolicy.setHeightForWidth(_groupBox->sizePolicy().hasHeightForWidth());
_groupBox->setSizePolicy(boxSizePolicy);
_groupBox->setBackgroundRole(QPalette::Button);
_groupBox->setAutoFillBackground(true);
setPopupWidget(_groupBox);
// Layout for visual group box
_boxLayout = new QGridLayout(_groupBox);
_boxLayout->setSpacing(spacing());
_boxLayout->setMargin(layoutMargin());
setSizePolicy(boxSizePolicy);
// Abstract group for mutual exclusive toggle
_buttonGroup = new QButtonGroup(_groupBox);
connect(_buttonGroup, SIGNAL(buttonPressed(int)),
this, SLOT(onButtonPressed(int)));
QToolButton::setDefaultAction(nullptr);
// Actual positions of the buttons in the button menu layout
_buttonXPos = _buttonYPos = 0;
}
/*!
Destructs the button menu.
*/
CAMenuToolButton::~CAMenuToolButton()
{
for (int i = 0; i < _buttonList.size(); ++i)
delete _buttonList[i];
delete _buttonGroup;
delete _groupBox;
}
/*!
Adds a Tool button to the menu with the given \a icon and \a buttonId.
*/
void CAMenuToolButton::addButton(const QIcon icon, int buttonId, const QString toolTip)
{
QToolButton* button;
QFontMetrics metrics(_groupBox->font());
int iconSize = 24, // Size of Icon
xMargin = _margin * 2, // Margin around the buttons
yMargin = _margin * 2 + metrics.height(), // includes the height of the menu text
xSize = iconSize,
ySize = iconSize;
// Create new button for menu
button = new CAGroupBoxToolButton(_groupBox);
button->setIcon(icon);
button->setIconSize(QSize(iconSize, iconSize));
button->setCheckable(true);
button->setToolTip(toolTip);
// Useful if you want to switch icons of an associated toolbar
button->setObjectName(objectName());
_buttonList << button;
// Add it to the abstract group
_buttonGroup->addButton(_buttonList.last(), buttonId);
// Create menu that has miNumIconsRow buttons in each row
if (_buttonXPos >= numIconsPerRow()) {
_buttonXPos = 0;
_buttonYPos++;
}
// Add it to the button menu layout
_boxLayout->addWidget(button, _buttonYPos, _buttonXPos, Qt::AlignLeft);
_buttonXPos++;
if (_buttonYPos > 0) {
xSize = numIconsPerRow() * (_spacing + button->width() / 3);
} else {
xSize = _buttonXPos * (_spacing + button->width() / 3);
}
ySize = (_buttonYPos + 1) * (_spacing + button->height());
_groupBox->setMinimumSize(xMargin + xSize, yMargin + ySize);
}
/*!
Hides the buttons menu, changes the current id and emits the toggled() signal.
*/
void CAMenuToolButton::onButtonPressed(int id)
{
if (_buttonGroup->button(id)) {
setCurrentId(id);
if (isChecked())
emit toggled(true, id); // if already on and in any button group
else
click(); // trigger any button groups
setChecked(true); // turn it on if it can turn off
}
hideButtons();
}
/*!
Set the current button, then show the popup widget.
*/
void CAMenuToolButton::showButtons()
{
_buttonGroup->button(currentId())->setChecked(true);
CAToolButton::showButtons();
}
/*!
Cycle through properties using the mouse wheel.
*/
void CAMenuToolButton::wheelEvent(QWheelEvent* event)
{
QList<QAbstractButton*> buttonList = _buttonGroup->buttons();
QAbstractButton* button = _buttonGroup->button(currentId());
int newIdx = buttonList.indexOf(button) + (event->delta() > 0 ? -1 : 1);
if (newIdx == buttonList.size())
newIdx = 0;
else if (newIdx == -1)
newIdx = buttonList.size() - 1;
setCurrentId(_buttonGroup->id(buttonList[newIdx]));
if (isChecked())
emit toggled(true, currentId()); // if already on and in any button group
else
click(); // trigger any button groups
setChecked(true); // turn it on if it can turn off
}
/*!
Sets the currently selected item by passing the item index.
The current icon of the button is changed to the item ones.
The current tool tip is also changed.
Does not change the current item, if the item is not part of the button box.
If \a triggerSignal is False (default) it doesn't emit toggled(), otherwise it does.
*/
void CAMenuToolButton::setCurrentId(int id, bool triggerSignal)
{
CAToolButton::setCurrentId(id);
if (!_buttonGroup->button(id))
return;
if (defaultAction())
defaultAction()->setIcon(_buttonGroup->button(id)->icon());
if (triggerSignal)
emit toggled(false, id);
}
/*!
\fn void CAButtonMenu::toggled( bool checked, int id )
Signal sent when the button is clicked or an element is selected and changed.
*/
| 7,031
|
C++
|
.cpp
| 188
| 33.218085
| 90
| 0.713005
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,389
|
view.cpp
|
canorusmusic_canorus/src/widgets/view.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "widgets/view.h"
#include "canorus.h"
const int CAView::DEFAULT_VIEW_WIDTH = 600;
const int CAView::DEFAULT_VIEW_HEIGHT = 400;
/*!
\class CAView
\brief Base class for various views
CAView is the base widget for different types of views of the document.
Viewport can represent a score view, envelope view, score source view etc.
*/
/*!
The default constructor.
Creates a widget with the parent widget \a p.
*/
CAView::CAView(QWidget* p)
: QWidget(p)
{
setGeometry(0, 0, 0, 0);
}
/*!
Destructor.
*/
CAView::~CAView()
{
CACanorus::removeView(this);
}
void CAView::mousePressEvent(QMouseEvent* e)
{
QWidget::mousePressEvent(e);
emit clicked();
}
/*!
\fn CAView *CAView::clone()
Returns a pointer to the new cloned view with the same parent.
This function is usually called when a user creates a new docked view.
*/
/*!
\fn CAView *CAView::clone(QWidget *parent)
Returns a pointer to the new cloned view with the parent \a parent.
This function is usually called when a user creates a new undocked view.
*/
/*!
\fn void CAView::rebuild()
Synchronizes/Rebuilds the UI part from the abstract one.
This function is usually called when a user creates changes to the score or a new view is introduced.
*/
/*!
\fn void CAView::clicked
This signal is emitted when mousePressEvent() is called. Parent class is usually connected to this event.
*/
/*!
\enum CAView::CAViewType
Holds different view types:
- ScoreView - The main view of the score. All the music elements (staffs, notes, rests) are rendered to this view.
- SourceView - Score source view in various syntices (LilyPond, CanorusML etc.).
*/
| 1,873
|
C++
|
.cpp
| 61
| 28.655738
| 116
| 0.753203
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,390
|
sourceview.cpp
|
canorusmusic_canorus/src/widgets/sourceview.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QGridLayout>
#include <QMouseEvent>
#include <QPushButton>
#include <QTextEdit>
#include <QTextStream>
#include "export/canorusmlexport.h"
#include "score/document.h"
#include "score/voice.h"
#include "widgets/sourceview.h"
#include "export/lilypondexport.h"
#include "import/lilypondimport.h"
class CASourceView::CATextEdit : public QTextEdit {
public:
CATextEdit(CASourceView* v)
: QTextEdit(v)
, _view(v)
{
}
protected:
void focusInEvent(QFocusEvent* event)
{
QTextEdit::focusInEvent(event);
QMouseEvent fake(QEvent::MouseButtonPress, QCursor::pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
_view->mousePressEvent(&fake);
}
private:
CASourceView* _view;
};
/*!
\class CASourceView
\brief Widget that shows the current score source in various syntax
This widget is a view which shows in the main text area the syntax of the current score (or voice, staff).
It includes 2 buttons for committing the changes to the score and reverting any changes back from the score.
\sa CAScoreView
*/
/*!
Constructor for CanorusML syntax - requires the whole document.
\todo This should be merged in the future with other formats.
*/
CASourceView::CASourceView(CADocument* doc, QWidget* parent)
: CAView(parent)
{
setViewType(SourceView);
setSourceViewType(CanorusML);
_document = doc;
_voice = nullptr;
_lyricsContext = nullptr;
setupUI();
}
/*!
Constructor for LilyPond syntax - requires the current voice.
\todo This should be merged in the future with other formats.
*/
CASourceView::CASourceView(CAVoice* voice, QWidget* parent)
: CAView(parent)
{
setViewType(SourceView);
setSourceViewType(LilyPond);
_document = nullptr;
_voice = voice;
_lyricsContext = nullptr;
setupUI();
}
/*!
Constructor for LilyPond syntax - requires the current lyrics context to show the lyrics.
\todo This should be merged in the future with other formats.
*/
CASourceView::CASourceView(CALyricsContext* lc, QWidget* parent)
: CAView(parent)
{
setViewType(SourceView);
setSourceViewType(LilyPond);
_document = nullptr;
_voice = nullptr;
_lyricsContext = lc;
setupUI();
}
void CASourceView::setupUI()
{
_layout = new QGridLayout(this);
_layout->addWidget(_textEdit = new CATextEdit(this));
_layout->addWidget(_commit = new QPushButton(tr("Commit changes")));
_layout->addWidget(_revert = new QPushButton(tr("Revert changes")));
connect(_commit, SIGNAL(clicked()), this, SLOT(on_commit_clicked()));
connect(_revert, SIGNAL(clicked()), this, SLOT(rebuild()));
rebuild();
}
CASourceView::~CASourceView()
{
_textEdit->disconnect();
_commit->disconnect();
_revert->disconnect();
_layout->disconnect();
delete _textEdit;
delete _commit;
delete _revert;
delete _layout;
}
void CASourceView::on_commit_clicked()
{
emit CACommit(_textEdit->toPlainText());
}
CASourceView* CASourceView::clone()
{
CASourceView* v = nullptr;
if (document())
v = new CASourceView(document(), static_cast<QWidget*>(parent()));
else if (voice())
v = new CASourceView(voice(), static_cast<QWidget*>(parent()));
else if (lyricsContext())
v = new CASourceView(lyricsContext(), static_cast<QWidget*>(parent()));
return v;
}
CASourceView* CASourceView::clone(QWidget* parent)
{
CASourceView* v = nullptr;
if (document())
v = new CASourceView(document(), parent);
else if (voice())
v = new CASourceView(voice(), parent);
else if (lyricsContext())
v = new CASourceView(lyricsContext(), parent);
return v;
}
/*!
Generates the score source from the current score and fill the text area with it.
*/
void CASourceView::rebuild()
{
_textEdit->clear();
QString* value = new QString();
QTextStream stream(value);
// CanorusML
if (document()) {
CACanorusMLExport save(&stream);
save.exportDocument(document());
save.wait();
} else {
CALilyPondExport le(&stream);
// LilyPond
if (voice()) {
le.exportVoice(voice());
le.wait();
} else if (lyricsContext()) {
le.exportLyricsContext(lyricsContext());
le.wait();
}
}
_textEdit->insertPlainText(*value);
delete value;
}
| 4,616
|
C++
|
.cpp
| 156
| 25.378205
| 115
| 0.691595
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,391
|
toolbuttonpopup.cpp
|
canorusmusic_canorus/src/widgets/toolbuttonpopup.cpp
|
/*!
Copyright (c) 2007-2020, Itay Perl, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QMouseEvent>
#include <QWidget>
#include "widgets/toolbuttonpopup.h"
/*!
\class CAToolButtonPopup
\brief Container for tool button popup widgets
This container sets the correct popup behavior for tool button floating widgets.
*/
CAToolButtonPopup::CAToolButtonPopup(QWidget* parent)
: QWidget(parent)
, _widget(nullptr)
{
setWindowFlags(Qt::Popup);
}
void CAToolButtonPopup::mousePressEvent(QMouseEvent* e)
{
QWidget::mousePressEvent(e);
if (!QRect(x(), y(), width(), height()).contains(e->globalPos()))
hide();
}
| 772
|
C++
|
.cpp
| 25
| 28.16
| 81
| 0.754743
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,392
|
scoreview.cpp
|
canorusmusic_canorus/src/widgets/scoreview.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QBrush>
#include <QColor>
#include <QDebug>
#include <QGridLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QPalette>
#include <QScrollBar>
#include <QTimer>
#include <QWheelEvent>
#include <math.h> // needed for square root in animated scrolls/zoom
#include <iostream>
#include "layout/drawable.h"
#include "layout/drawableaccidental.h"
#include "layout/drawablebarline.h"
#include "layout/drawablecontext.h"
#include "layout/drawablelyricscontext.h" // syllable edit creation
#include "layout/drawablemuselement.h"
#include "layout/drawablenote.h"
#include "layout/drawablestaff.h"
#include "layout/drawabletimesignature.h"
#include "layout/layoutengine.h"
#include "widgets/scoreview.h"
#include "score/barline.h"
#include "score/bookmark.h"
#include "score/chordname.h"
#include "score/context.h"
#include "score/document.h"
#include "score/lyricscontext.h"
#include "score/muselement.h"
#include "score/note.h"
#include "score/rest.h"
#include "score/sheet.h"
#include "score/staff.h"
#include "score/syllable.h"
#include "score/text.h"
#include "score/timesignature.h"
#include "score/voice.h"
#include "canorus.h"
#include "core/settings.h"
const int CAScoreView::RIGHT_EXTRA_SPACE = 100; // Gives some space after the music so you're able to insert music elements after the last element
const int CAScoreView::BOTTOM_EXTRA_SPACE = 30; // Gives some space after the music so you're able to insert new contexts below the last context
const int CAScoreView::RULER_HEIGHT = 15;
const int CAScoreView::ANIMATION_STEPS = 7;
const int CAScoreView::SELECTION_REGION_THRESHOLD = 10;
/*!
\class CATextEdit
\brief A text edit widget based on QLineEdit
This widget is extended QLineEdit with custom actions on keypress events - caught and determined usually by the main
window then. A new signal CAKeyPressEvent() was introduced for this.
Widget is usually used for editing the lyrics syllables or writing other text in the score.
For syllable editing, when left/right cursors are hit at the beginning/end of the line, the next/previous syllable in
the score should be selected. This isn't possible to achieve with standard QLineEdit as we need to control KeyPressEvent.
This behaviour is again determined in the main window.
*/
CATextEdit::CATextEdit(QWidget* parent)
: QLineEdit(parent)
{
}
CATextEdit::~CATextEdit()
{
}
void CATextEdit::keyPressEvent(QKeyEvent* e)
{
int oldCurPos = cursorPosition();
QLineEdit::keyPressEvent(e); // call parent's keyPressEvent()
if ((e->key() == Qt::Key_Left || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Right) && cursorPosition() != oldCurPos)
return;
emit CAKeyPressEvent(e);
}
/*!
\class CAScoreView
Widget for rendering the score.
This class represents the widget capable of rendering the score. It is usually used as a central widget in the main window, but might be used
for example, in a list of possible harmonization or improvization solutions, score layout window and more as an independent widget or only as
a drawable content on a button.
Score view consists of a virtual workspace full of drawable elements which represent the abstract music elements or contexts. Every drawable
element has its absolute X, Y, Width and Height geometry properties. Score view also shows usually a small part of the whole workspace
(depending on scroll bars values and a zoom level). When drawable elements are drawn, their CADrawable::draw() methods are called with the
views X and Y coordinates, zoom level, pen color and other properties needed to correctly draw an element to the score view's canvas.
Note that this widget is only capable of correctly rendering the drawable elements. No Control part of the MVC model is implemented here. The
view logic is implemented outside of this class (usually main window). Score view only provides various signals to communicate with
outer world. However, this class provides various modes (eg. drawing the shadow notes when inserting music elements, coloring only one voice,
hiding certain staffs, animating the scroll etc.) the controller might use.
This widget also provides horizontal and vertical scrollbars (see _hScrollBar and _vScrollBar).
*/
CAScoreView::CAScoreView(CASheet* sheet, QWidget* parent)
: CAView(parent)
{
initScoreView(sheet);
}
CAScoreView::CAScoreView(QWidget* parent)
: CAView(parent)
{
initScoreView(nullptr);
}
void CAScoreView::initScoreView(CASheet* sheet)
{
setViewType(ScoreView);
setSheet(sheet);
_worldX = _worldY = 0;
_worldW = _worldH = 0;
_zoom = 1.0;
_holdRepaint = false;
_hScrollBarDeadLock = false;
_vScrollBarDeadLock = false;
_checkScrollBarsDeadLock = false;
_playing = false;
_currentContext = nullptr;
_xCursor = _yCursor = 0;
setResizeDirection(CADrawable::Undefined);
// init layout
_layout = new QGridLayout(this);
_layout->setMargin(2);
_layout->setSpacing(2);
_drawBorder = false;
_grabTabKey = true;
setFocusPolicy(Qt::StrongFocus);
// init virtual canvas
_canvas = new QWidget(this);
setMouseTracking(true);
_repaintArea = nullptr;
// init animation stuff
_animationTimer = new QTimer(this);
_animationTimer->setInterval(50);
connect(_animationTimer, SIGNAL(timeout()), this, SLOT(on_animationTimer_timeout()));
// init click timer (used for measuring double/triple click since Qt4 doesn't support triple click yet ;))
_clickTimer = new QTimer(this);
_clickTimer->setSingleShot(true);
_clickTimer->setInterval(static_cast<int>(QApplication::doubleClickInterval() * 1.5));
connect(_clickTimer, SIGNAL(timeout()), this, SLOT(on_clickTimer_timeout()));
// init helpers
setSelectedVoice(nullptr);
setShadowNoteVisible(false);
setShadowNoteVisibleOnLeave(false);
setShadowNoteAccs(0);
setNoteNameVisible(false);
setDrawShadowNoteAccs(false);
setTextEdit(new CATextEdit(_canvas));
setTextEditVisible(false);
// init scrollbars
_vScrollBar = new QScrollBar(Qt::Vertical, this);
_hScrollBar = new QScrollBar(Qt::Horizontal, this);
_vScrollBar->setMinimum(0);
_hScrollBar->setMinimum(0);
_vScrollBar->setTracking(true); // trigger valueChanged() when dragging the slider, not only releasing it
_hScrollBar->setTracking(true);
_vScrollBar->hide();
_hScrollBar->hide();
_scrollBarVisible = ScrollBarShowIfNeeded;
_allowManualScroll = true;
connect(_hScrollBar, SIGNAL(valueChanged(int)), this, SLOT(HScrollBarEvent(int)));
connect(_vScrollBar, SIGNAL(valueChanged(int)), this, SLOT(VScrollBarEvent(int)));
// connect layout and widgets
_layout->addWidget(_canvas, 0, 0);
_layout->addWidget(_vScrollBar, 0, 1);
_layout->addWidget(_hScrollBar, 1, 0);
_oldWorldW = 0;
_oldWorldH = 0;
setBackgroundColor(CACanorus::settings()->backgroundColor());
setForegroundColor(CACanorus::settings()->foregroundColor());
setSelectionColor(CACanorus::settings()->selectionColor());
setSelectionAreaColor(CACanorus::settings()->selectionAreaColor());
setSelectedContextColor(CACanorus::settings()->selectedContextColor());
setHiddenElementsColor(CACanorus::settings()->hiddenElementsColor());
setDisabledElementsColor(CACanorus::settings()->disabledElementsColor());
}
CAScoreView::~CAScoreView()
{
// Delete the drawable elements/contexts
_drawableMList.clear(true);
_drawableCList.clear(true);
_drawableNCEList.clear(true);
while (!_shadowNote.isEmpty()) {
delete _shadowNote.takeFirst();
delete _shadowDrawableNote.takeFirst(); // same size
}
_animationTimer->disconnect();
_animationTimer->stop();
delete _animationTimer;
_hScrollBar->disconnect();
_vScrollBar->disconnect();
}
void CAScoreView::on_animationTimer_timeout()
{
_animationStep++;
double newZoom = _zoom + (_targetZoom - _zoom) * sqrt(static_cast<double>(_animationStep) / ANIMATION_STEPS);
double newWorldX = _worldX + (_targetWorldX - _worldX) * sqrt(static_cast<double>(_animationStep) / ANIMATION_STEPS);
double newWorldY = _worldY + (_targetWorldY - _worldY) * sqrt(static_cast<double>(_animationStep) / ANIMATION_STEPS);
double newWorldW = drawableWidth() / newZoom;
double newWorldH = drawableHeight() / newZoom;
setWorldCoords(newWorldX, newWorldY, newWorldW, newWorldH);
if (_animationStep == ANIMATION_STEPS)
_animationTimer->stop();
repaint();
}
/**
Reimplementation of the original QWidget's setMouseTracking to set both the
widget and the _canvas mouse tracking property.
*/
void CAScoreView::setMouseTracking(bool mt)
{
CAView::setMouseTracking(mt);
_canvas->setMouseTracking(mt);
}
CAScoreView* CAScoreView::clone()
{
CAScoreView* v = new CAScoreView(_sheet, static_cast<QWidget*>(parent()));
v->rebuild();
v->setWorldX(worldX(), false);
v->setWorldY(worldY(), false);
v->repaint();
return v;
}
CAScoreView* CAScoreView::clone(QWidget* parent)
{
CAScoreView* v = new CAScoreView(_sheet, parent);
v->rebuild();
v->setWorldX(worldX(), false);
v->setWorldY(worldY(), false);
v->repaint();
return v;
}
/*!
Adds a drawable music element \a elt to the score view and selects it, if \a select is true.
*/
void CAScoreView::addMElement(CADrawableMusElement* elt, bool select)
{
_drawableMList.addElement(elt);
_mapDrawable.insertMulti(elt->musElement(), elt);
if (select) {
_selection.clear();
addToSelection(elt);
}
elt->drawableContext()->addMElement(elt);
emit selectionChanged();
}
/*!
Adds a drawable music element \a elt to the score view and selects it, if \a select is true.
*/
void CAScoreView::addCElement(CADrawableContext* elt, bool select)
{
_drawableCList.addElement(elt);
_mapDrawable.insertMulti(elt->context(), elt);
if (select)
setCurrentContext(elt);
if (elt->drawableContextType() == CADrawableContext::DrawableStaff && static_cast<CAStaff*>(elt->context())->voiceList().size()) {
_shadowNote << new CANote(CADiatonicPitch(), CAPlayableLength(CAPlayableLength::Quarter, 0), static_cast<CAStaff*>(elt->context())->voiceList()[0], 0);
_shadowDrawableNote << new CADrawableNote(_shadowNote.back(), elt, 0, 0, true);
}
}
/*!
Adds a drawable music element \a elt to the score view and selects it, if \a select is true.
*/
void CAScoreView::addDrawableNoteCheckerError(CADrawableNoteCheckerError* dnce)
{
_drawableNCEList.addElement(dnce);
_mapDrawable.insertMulti(nullptr, dnce);
}
/*!
Selects the drawable context of the given abstract context.
If there are multiple drawable elements representing a single abstract element, selects the first one.
Returns a pointer to the drawable instance of the given context or nullptr if the context was not found.
\sa selectMElement(CAMusElement*)
*/
CADrawableContext* CAScoreView::selectContext(CAContext* context)
{
if (!context) {
setCurrentContext(nullptr);
return nullptr;
}
QList<CADrawableContext*> drawableContexts = _drawableCList.list();
for (int i = 0; i < drawableContexts.size(); i++) {
CAContext* c = drawableContexts[i]->context();
if (c == context) {
setCurrentContext(drawableContexts[i]);
return drawableContexts[i];
}
}
return nullptr;
}
/*!
Change the x-coord of the last mouse press coords to after the right most element on the given list.
*/
void CAScoreView::setLastMousePressCoordsAfter(const QList<CAMusElement*> list)
{
double maxX = 0;
for (int i = 0; i < list.size(); i++) {
QList<CADrawable*> drawables = _mapDrawable.values(list[i]);
for (int j = 0; j < drawables.size(); j++) {
maxX = qMax(drawables[j]->xPos() + drawables[j]->width(), maxX);
}
}
QPoint newCoords(lastMousePressCoords());
// Note Reinhard: I see a lot of coordinate conversions. A simple cast is probably not what you want.
// Do you want to have the same result (0) for 0.2 and 0.8 ? also the floor, round etc. methods
// probably have a better performance (they are fpu commands).
newCoords.setX(maxX);
setLastMousePressCoords(newCoords);
}
/*!
Selects a drawable context element at the given coordinates, if it exists.
Returns a pointer to its abstract context element.
If multiple elements exist at the same coordinates, they are selected one by another if you click at the same coordinates multiple times.
If no elements are present at the coordinates, clear the selection.
*/
CADrawableContext* CAScoreView::selectCElement(double x, double y)
{
QList<CADrawableContext*> l = _drawableCList.findInRange(x, y);
if (l.size() != 0) {
setCurrentContext(l.front());
} else
setCurrentContext(nullptr);
return currentContext();
}
/*!
Returns a list of pointers to the drawable music elements at the given coordinates.
Multiple elements can exist at the same coordinates.
If there is a currently selected voice, only elements belonging to this voice are selected.
*/
QList<CADrawableMusElement*> CAScoreView::musElementsAt(double x, double y)
{
QList<CADrawableMusElement*> l = _drawableMList.findInRange(x, y);
for (int i = 0; i < l.size(); i++)
if (!l[i]->isSelectable() || (selectedVoice() && l[i]->musElement() && l[i]->musElement()->isPlayable() && static_cast<CAPlayable*>(l[i]->musElement())->voice() != selectedVoice()))
l.removeAt(i--);
return l;
}
/*!
Selects the drawable music element of the given abstract music element.
If there are multiple drawable elements representing a single abstract element, selects the first one.
Returns a pointer to the drawable instance of the given music element or 0 if the music element was not found.
\sa selectCElement(CAContext*)
*/
CADrawableMusElement* CAScoreView::selectMElement(CAMusElement* elt)
{
_selection.clear();
QList<CADrawable*> drawables = _mapDrawable.values(elt);
for (int i = 0; i < drawables.size(); i++) {
if (drawables[i]->drawableType() == CADrawable::DrawableMusElement && static_cast<CADrawableMusElement*>(drawables[i])->musElement() == elt && drawables[i]->isSelectable()) {
addToSelection(static_cast<CADrawableMusElement*>(drawables[i]));
}
}
emit selectionChanged();
if (selection().size())
return selection().back();
else
return nullptr;
}
/**!
* This function clones the given drawable instances of musElements and contexts.
*
* \obsolete This Function was used in the past when cloning the views to also clone the
* elements. This behaviour was replaced for creating a new drawable instances
* from the scene from scratch.
*/
void CAScoreView::importElements(CAKDTree<CADrawableMusElement*>* origDMusElts, CAKDTree<CADrawableContext*>* origDContexts)
{
QList<CADrawableContext*> drawableContexts = origDContexts->list();
for (int i = 0; i < drawableContexts.size(); i++) {
addCElement(drawableContexts[i]->clone());
}
QList<CADrawableContext*> newDrawableContexts = _drawableCList.list();
QList<CADrawableMusElement*> drawableMusElements = origDMusElts->list();
for (int i = 0; i < drawableMusElements.size(); i++) {
int idx = drawableContexts.indexOf(drawableMusElements[i]->drawableContext());
if (idx == -1) {
std::cerr << "ERROR: Music element " << drawableMusElements[i] << " does not have a drawable context!" << std::endl;
} else if (newDrawableContexts.size() <= idx) {
std::cerr << "ERROR: Index out of range. " << newDrawableContexts.size() << " new drawable contexts created. Request for idx=" << idx << std::endl;
} else {
addMElement(drawableMusElements[i]->clone(newDrawableContexts[idx]));
}
}
}
/*!
Returns a pointer to the nearest drawable music element left of the current coordinates with the largest startTime.
Drawable elements left borders are taken into account.
If \a context is non-zero, returns the nearest element in the given context only.
*/
CADrawableMusElement* CAScoreView::nearestLeftElement(double x, double, CADrawableContext* context)
{
return _drawableMList.findNearestLeft(x, true, context);
}
/*!
Returns a pointer to the nearest drawable music element left of the current coordinates with the
largest startTime in the given voice.
Drawable elements left borders are taken into account.
*/
CADrawableMusElement* CAScoreView::nearestLeftElement(double x, double, CAVoice* voice)
{
return _drawableMList.findNearestLeft(x, true, nullptr, voice);
}
/*!
Returns a pointer to the nearest drawable music element right of the current coordinates with the largest startTime.
Drawable elements left borders are taken into account.
If \a context is non-zero, returns the nearest element in the given context only.
*/
CADrawableMusElement* CAScoreView::nearestRightElement(double x, double, CADrawableContext* context)
{
return _drawableMList.findNearestRight(x, true, context);
}
/*!
Returns a pointer to the nearest drawable music element right of the current coordinates with the
largest startTime in the given voice.
Drawable elements left borders are taken into account.
*/
CADrawableMusElement* CAScoreView::nearestRightElement(double x, double, CAVoice* voice)
{
return _drawableMList.findNearestRight(x, true, nullptr, voice);
}
/*!
Returns a pointer to the nearest upper drawable context from the given coordinates.
\todo Also look at X coordinate
*/
CADrawableContext* CAScoreView::nearestUpContext(double, double y)
{
return static_cast<CADrawableContext*>(_drawableCList.findNearestUp(y));
}
/*!
Returns a pointer to the nearest upper drawable context from the given coordinates.
\todo Also look at X coordinate
*/
CADrawableContext* CAScoreView::nearestDownContext(double, double y)
{
return static_cast<CADrawableContext*>(_drawableCList.findNearestDown(y));
}
/*!
Calculates the logical time at the given coordinates \a x and \a y.
*/
int CAScoreView::calculateTime(double x, double)
{
CADrawableMusElement* left = _drawableMList.findNearestLeft(x, true);
CADrawableMusElement* right = _drawableMList.findNearestRight(x, true);
if (left) //the user clicked right of the element - return the nearest left element end time
return left->musElement()->timeStart() + left->musElement()->timeLength();
else if (right) //the user clicked left of the element - return the nearest right element start time
return right->musElement()->timeStart();
else //no elements found in the score at all - return 0
return 0;
}
/*!
Creates a map of a bar number -> drawable barline in the score of a staff
with most barlines and enumerates them.
This function is usually called when drawing a ruler or jumping to specific bar.
\param dotted Also include dotted barlines in the list (which are usually ignored in the bar count)
\return Map of bar number -> drawable barline of the staff with most barlines
*/
QMap<int, CADrawableBarline*> CAScoreView::computeBarlinePositions(bool dotted)
{
QList<CADrawableContext*> dContextList = _drawableCList.list();
QMap<int, CADrawableBarline*> result;
// determine staff with most barlines
CADrawableStaff* dStaff = nullptr;
for (int i = 0; i < dContextList.size(); i++) {
if ((dContextList[i]->drawableContextType() == CADrawableContext::DrawableStaff) && (!dStaff || dStaff->drawableBarlineList().size() < static_cast<CADrawableStaff*>(dContextList[i])->drawableBarlineList().size())) {
dStaff = static_cast<CADrawableStaff*>(dContextList[i]);
}
}
if (!dStaff) {
return result;
}
QList<CADrawableBarline*> drawableBarlineList = dStaff->drawableBarlineList();
// remove dotted barlines, if dotted=false
if (!dotted) {
for (int i = 0; i < drawableBarlineList.size(); i++) { // filter out dotted barlines
if (drawableBarlineList[i]->barline()->barlineType() == CABarline::Dotted) {
drawableBarlineList.removeAt(i);
i--;
}
}
}
if (dStaff && !drawableBarlineList.isEmpty()) {
// determine the bar number + do we have a pickup measure in the beginning
CADrawableTimeSignature* firstDTimeSig = (dStaff->drawableTimeSignatureList().size() ? dStaff->drawableTimeSignatureList()[0] : nullptr);
int barlineOffset = 2;
if (firstDTimeSig && drawableBarlineList[0]->barline()->timeStart() < firstDTimeSig->timeSignature()->barDuration()) {
barlineOffset = 1;
}
for (int i = 0; i < drawableBarlineList.size(); i++) {
result[i + barlineOffset] = drawableBarlineList[i];
}
}
return result;
}
/*!
If the given coordinates hit any of the contexts, returns that context.
*/
CAContext* CAScoreView::contextCollision(double x, double y)
{
QList<CADrawableContext*> l = _drawableCList.findInRange(x, y, 0, 0);
if (l.size() == 0) {
return nullptr;
} else {
CAContext* context = l.front()->context();
return context;
}
}
/*!
Calls the engraver to reposition the music elements on the canvas.
Also updates scrollbars.
*/
void CAScoreView::rebuild()
{
// clear the shadow notes
CAPlayableLength l(CAPlayableLength::Quarter);
for (int i = 0; i < _shadowNote.size(); i++) {
delete _shadowDrawableNote[i];
l = _shadowNote[i]->playableLength();
delete _shadowNote[i];
}
_shadowNote.clear();
_shadowDrawableNote.clear();
QList<CAMusElement*> musElementSelection;
for (int i = 0; i < _selection.size(); i++) {
if (!musElementSelection.contains(_selection[i]->musElement()))
musElementSelection << _selection[i]->musElement();
}
_selection.clear();
_drawableMList.clear(true);
int contextIdx = (_currentContext ? _drawableCList.list().indexOf(_currentContext) : -1); // remember the index of last used context
_drawableCList.clear(true);
_drawableNCEList.clear(true);
_mapDrawable.clear();
CALayoutEngine::reposit(this);
for (int i = 0; i < _shadowNote.size(); i++) {
_shadowNote[i]->setPlayableLength(l);
}
if (contextIdx != -1) // restore the last used context
setCurrentContext(static_cast<CADrawableContext*>((_drawableCList.size() > contextIdx) ? _drawableCList.list().at(contextIdx) : nullptr));
else
setCurrentContext(nullptr);
addToSelection(musElementSelection);
setWorldCoords(worldCoords()); // needed to update the scrollbars
checkScrollBars();
updateHelpers();
}
/*!
Sets the world Top-Left X coordinate of the view. Animates the scroll, if \a animate is True.
If \a force is True, sets the value despite the potential illegal value (like negative coordinates).
\warning Repaint is not done automatically!
*/
void CAScoreView::setWorldX(double x, bool animate, bool force)
{
if (!force) {
double maxX = (getMaxXExtended(_drawableMList) > getMaxXExtended(_drawableCList)) ? getMaxXExtended(_drawableMList) : getMaxXExtended(_drawableCList);
if (x > maxX - _worldW)
x = maxX - _worldW;
if (x < 0)
x = 0;
}
if (animate) {
_targetWorldX = x;
_targetWorldY = _worldY;
_targetZoom = _zoom;
startAnimationTimer();
return;
}
_oldWorldX = _worldX;
_worldX = x;
_hScrollBarDeadLock = true;
_hScrollBar->setValue(x);
_hScrollBarDeadLock = false;
checkScrollBars();
updateHelpers();
}
/*!
Sets the world Top-Left Y coordinate of the view. Animates the scroll, if \a animate is True.
If \a force is True, sets the value despite the potential illegal value (like negative coordinates).
\warning Repaint is not done automatically!
*/
void CAScoreView::setWorldY(double y, bool animate, bool force)
{
if (!force) {
int maxY = getMaxYExtended(_drawableMList) > getMaxYExtended(_drawableCList) ? getMaxYExtended(_drawableMList) : getMaxYExtended(_drawableCList);
if (y > maxY - _worldH)
y = maxY - _worldH;
if (y < 0)
y = 0;
}
if (animate) {
_targetWorldX = _worldX;
_targetWorldY = y;
_targetZoom = _zoom;
startAnimationTimer();
return;
}
_oldWorldY = _worldY;
_worldY = y;
_vScrollBarDeadLock = true;
_vScrollBar->setValue(y);
_vScrollBarDeadLock = false;
checkScrollBars();
updateHelpers();
}
/*!
Sets the world width of the view.
If \a force is True, sets the value despite the potential illegal value (like negative coordinates).
\warning Repaint is not done automatically!
*/
void CAScoreView::setWorldWidth(double w, bool force)
{
if (!force) {
if (w < 1)
return;
}
_oldWorldW = _worldW;
_worldW = w;
double scrollMax;
if ((scrollMax = ((getMaxXExtended(_drawableMList) > getMaxXExtended(_drawableCList)) ? getMaxXExtended(_drawableMList) : getMaxXExtended(_drawableCList)) - _worldW) >= 0) {
if (scrollMax < _worldX) //if you resize the widget at a large zoom level and if the getMax border has been reached
setWorldX(scrollMax); //scroll the view away from the border
_hScrollBarDeadLock = true;
_hScrollBar->setMaximum(scrollMax);
_hScrollBar->setPageStep(_worldW);
_hScrollBarDeadLock = false;
}
_zoom = static_cast<double>(drawableWidth() / _worldW);
checkScrollBars();
}
/*!
Sets the world height of the view.
If \a force is True, sets the value despite the potential illegal value (like negative coordinates).
\warning Repaint is not done automatically!
*/
void CAScoreView::setWorldHeight(double h, bool force)
{
if (!force) {
if (h < 1)
return;
}
_oldWorldH = _worldH;
_worldH = h;
double scrollMax;
if ((scrollMax = ((getMaxYExtended(_drawableMList) > getMaxYExtended(_drawableCList)) ? getMaxYExtended(_drawableMList) : getMaxYExtended(_drawableCList)) - _worldH) >= 0) {
if (scrollMax < _worldY) //if you resize the widget at a large zoom level and if the getMax border has been reached
setWorldY(scrollMax); //scroll the view away from the border
_vScrollBarDeadLock = true;
_vScrollBar->setMaximum(scrollMax);
_vScrollBar->setPageStep(_worldH);
_vScrollBarDeadLock = false;
}
_zoom = static_cast<double>(drawableHeight() / _worldH);
checkScrollBars();
}
/*!
Sets the world coordinates of the view to the given rectangle \a coords.
This is an overloaded member function, provided for convenience.
\warning Repaint is not done automatically!
*/
void CAScoreView::setWorldCoords(QRectF coords, bool animate, bool force)
{
_checkScrollBarsDeadLock = true;
if (!drawableWidth() && !drawableHeight())
return;
double scale = static_cast<double>(drawableWidth()) / drawableHeight(); //always keep the world rectangle area in the same scale as the actual width/height of the drawable canvas
if (coords.height()) { //avoid division by zero
if (coords.width() / coords.height() > scale)
coords.setHeight(coords.width() / scale);
else
coords.setWidth(coords.height() * scale);
} else
coords.setHeight(coords.width() / scale);
setWorldWidth(coords.width(), force);
setWorldHeight(coords.height(), force);
setWorldX(coords.x(), animate, force);
setWorldY(coords.y(), animate, force);
_checkScrollBarsDeadLock = false;
checkScrollBars();
}
/*!
\fn void CAScoreView::setWorldCoords(int x, int y, int w, int h, bool animate, bool force)
Sets the world coordinates of the view.
This is an overloaded member function, provided for convenience.
\warning Repaint is not done automatically!
\param x Top-left X coordinate of the new view area in absolute world units.
\param y Top-left Y coordinate of the new view area in absolute world units.
\param w Width of the new view area in absolute world units.
\param h Height of the new view area in absolute world units.
\param animate Use animated scroll.
\param force Use the given world units despite their illegal values (like negative coordinates etc.).
*/
void CAScoreView::zoomToSelection(bool animate, bool force)
{
if (!_selection.size())
return;
QRect rect;
rect.setX(_selection[0]->xPos());
rect.setY(_selection[0]->yPos());
rect.setWidth(_selection[0]->width());
rect.setHeight(_selection[0]->height());
for (int i = 1; i < _selection.size(); i++) {
if (_selection[i]->xPos() < rect.x())
rect.setX(_selection[i]->xPos());
if (_selection[i]->yPos() < rect.y())
rect.setY(_selection[i]->yPos());
if (_selection[i]->xPos() + _selection[i]->width() > rect.x() + rect.width())
rect.setWidth(_selection[i]->xPos() + _selection[i]->width() - rect.x());
if (_selection[i]->yPos() + _selection[i]->height() > rect.y() + rect.height())
rect.setHeight(_selection[i]->yPos() + _selection[i]->height() - rect.y());
}
setWorldCoords(rect, animate, force);
}
void CAScoreView::zoomToWidth(bool animate, bool force)
{
int maxX = (getMaxXExtended(_drawableCList) > getMaxXExtended(_drawableMList)) ? getMaxXExtended(_drawableCList) : getMaxXExtended(_drawableMList);
setWorldCoords(0, 0, maxX, 0, animate, force);
}
void CAScoreView::zoomToHeight(bool animate, bool force)
{
int maxY = (getMaxYExtended(_drawableCList) > getMaxYExtended(_drawableMList)) ? getMaxYExtended(_drawableCList) : getMaxYExtended(_drawableMList);
setWorldCoords(0, 0, 0, maxY, animate, force);
}
void CAScoreView::zoomToFit(bool animate, bool force)
{
int maxX = ((_drawableCList.getMaxX() > _drawableMList.getMaxX()) ? _drawableCList.getMaxX() : _drawableMList.getMaxX());
int maxY = ((_drawableCList.getMaxY() > _drawableMList.getMaxY()) ? _drawableCList.getMaxY() : _drawableMList.getMaxY());
setWorldCoords(0, 0, maxX, maxY, animate, force);
}
/*!
Sets the world coordinates of the view, so the given coordinates are the center of the new view area.
If the area has for eg. negative top-left coordinates, the area is moved to the (0,0) coordinates if \a force is False.
View's width and height stay intact.
\warning Repaint is not done automatically!
*/
void CAScoreView::setCenterCoords(double x, double y, bool animate, bool force)
{
// _checkScrollBarsDeadLock = true;
setWorldX(x - 0.5 * _worldW, animate, force);
setWorldY(y - 0.5 * _worldH, animate, force);
// _checkScrollBarsDeadLock = false;
checkScrollBars();
}
/*!
Zooms to the given level to given direction.
\warning Repaint is not done automatically, if \a animate is False!
\param z Zoom level. (1.0 = 100%, 1.5 = 150% etc.)
\param x X coordinate of the point of the zoom direction.
\param y Y coordinate of the point of the zoom direction.
\param animate Use smooth animated zoom.
\param force Use the given world units despite their illegal values (like negative coordinates etc.).
*/
void CAScoreView::setZoom(float z, double x, double y, bool animate, bool force)
{
bool zoomOut = false;
if (_zoom - z > 0.0)
zoomOut = true;
if (animate) {
if (!zoomOut) {
_targetWorldX = (_worldX - (_worldW / 2) + x) / 2;
_targetWorldY = (_worldY - (_worldH / 2) + y) / 2;
_targetZoom = z;
startAnimationTimer();
return;
} else {
_targetWorldX = 1.5 * _worldX + 0.25 * _worldW - 0.5 * x;
_targetWorldY = 1.5 * _worldY + 0.25 * _worldH - 0.5 * y;
_targetZoom = z;
startAnimationTimer();
return;
}
}
//set the world width - updates the zoom level zoom_ as well
setWorldWidth(drawableWidth() / z);
setWorldHeight(drawableHeight() / z);
if (!zoomOut) { //zoom in
//the new view's center coordinates will become the middle point of the current view center coords and the mouse pointer coords
setCenterCoords((_worldX + (_worldW / 2) + x) / 2,
(_worldY + (_worldH / 2) + y) / 2,
force);
} else { //zoom out
//the new view's center coordinates will become the middle point of the current view center coords and the mirrored over center pointer coords
//worldX_ + (worldW_/2) + (worldX_ + (worldW_/2) - x)/2
setCenterCoords(1.5 * _worldX + 0.75 * _worldW - 0.5 * x,
1.5 * _worldY + 0.75 * _worldH - 0.5 * y,
force);
}
checkScrollBars();
updateHelpers();
}
/*!
\fn void CAScoreView::setZoom(float z, QPoint p, bool animate, bool force);
Zooms to the given level to given direction.
This is an overloaded member function, provided for convenience.
\warning Repaint is not done automatically, if \a animate is False!
\param z Zoom level. (1.0 = 100%, 1.5 = 150% etc.)
\param p QPoint of the zoom direction.
\param animate Use smooth animated zoom.
\param force Use the given world units despite their illegal values (like negative coordinates etc.).
*/
/*!
General Qt's paint event.
All the music elements get actually rendered in this method.
*/
#include <sys/time.h> //benchmarking
#include <time.h> //benchmarking
void CAScoreView::paintEvent(QPaintEvent*)
{
if (_holdRepaint)
return;
// draw the border
QPainter p(this);
if (_drawBorder) {
p.setPen(_borderPen);
p.drawRect(0, 0, width() - 1, height() - 1);
}
// draw the background
if (_repaintArea)
p.fillRect(qRound((_repaintArea->x() - _worldX) * _zoom), qRound((_repaintArea->y() - _worldY) * _zoom), qRound(_repaintArea->width() * _zoom), qRound(_repaintArea->height() * _zoom), _backgroundColor);
else
p.fillRect(_canvas->x(), _canvas->y(), _canvas->width(), _canvas->height(), _backgroundColor);
// draw contexts
timeval timeStart, timeEnd, timeEnd2;
gettimeofday(&timeStart, nullptr);
QList<CADrawableContext*> cList;
//int j = _drawableCList.size();
if (_repaintArea)
cList = _drawableCList.findInRange(_repaintArea->x(), _repaintArea->y(), _repaintArea->width(), _repaintArea->height());
else
cList = _drawableCList.findInRange(_worldX, _worldY, _worldW, _worldH);
for (int i = 0; i < cList.size(); i++) {
CADrawSettings s = {
_zoom,
qRound((cList[i]->xPos() - _worldX) * _zoom),
qRound((cList[i]->yPos() - _worldY) * _zoom),
drawableWidth(), drawableHeight(),
((_currentContext == cList[i]) ? selectedContextColor() : foregroundColor()),
_worldX,
_worldY
};
cList[i]->draw(&p, s);
}
// draw music elements
QList<CADrawableMusElement*> mList;
if (_repaintArea)
mList = _drawableMList.findInRange(_repaintArea->x(), _repaintArea->y(), _repaintArea->width(), _repaintArea->height());
else
mList = _drawableMList.findInRange(_worldX, _worldY, _worldW, _worldH);
gettimeofday(&timeEnd, nullptr);
p.setRenderHint(QPainter::Antialiasing, CACanorus::settings()->antiAliasing());
for (int i = 0; i < mList.size(); i++) {
QColor color;
CAMusElement* elt = mList[i]->musElement();
// determine element color (based on selection, current mode, active voice etc.)
if (_selection.contains(mList[i])) {
color = selectionColor();
} else if ((selectedVoice() && ((elt && ((elt->isPlayable() && static_cast<CAPlayable*>(elt)->voice() == selectedVoice()) || (!elt->isPlayable() && elt->context() == selectedVoice()->staff()) || elt->context() != selectedVoice()->staff())) || (!elt && mList[i]->drawableContext()->context() == selectedVoice()->staff()))) || (!selectedVoice())) {
if (elt && elt->musElementType() == CAMusElement::Rest && static_cast<CAPlayable*>(elt)->voice() == selectedVoice() && static_cast<CARest*>(elt)->restType() == CARest::Hidden) {
color = hiddenElementsColor();
} else if ((elt && elt->musElementType() == CAMusElement::Rest && static_cast<CARest*>(elt)->restType() == CARest::Hidden) || (elt && !elt->isVisible())) {
color = QColor(0, 0, 0, 0); // transparent color
} else if (elt && elt->color().isValid()) {
color = elt->color(); // set elements color, if defined
} else {
color = foregroundColor(); // set default color for foreground elements
}
} else {
if (elt && elt->musElementType() == CAMusElement::Rest && static_cast<CARest*>(elt)->restType() == CARest::Hidden) {
color = QColor(0, 0, 0, 0); // transparent color
} else {
color = disabledElementsColor();
}
}
CADrawSettings s = {
_zoom,
qRound((mList[i]->xPos() - _worldX) * _zoom),
qRound((mList[i]->yPos() - _worldY) * _zoom),
drawableWidth(), drawableHeight(),
color,
_worldX,
_worldY
};
mList[i]->draw(&p, s);
if (_selection.contains(mList[i]) && mList[i]->isHScalable()) {
s.color = foregroundColor();
mList[i]->drawHScaleHandles(&p, s);
}
if (_selection.contains(mList[i]) && mList[i]->isVScalable()) {
s.color = foregroundColor();
mList[i]->drawVScaleHandles(&p, s);
}
}
// draw ruler
if (CACanorus::settings()->showRuler()) {
p.fillRect(0, 0, width(), RULER_HEIGHT, QColor::fromRgb(200, 200, 200, 128));
QFont font("FreeSans");
font.setPixelSize(qRound(RULER_HEIGHT * 0.8));
p.setFont(font);
p.setPen(Qt::black);
QMap<int, CADrawableBarline*> dBarlineMap = computeBarlinePositions(false);
if (!dBarlineMap.isEmpty()) {
int curBarlineNumber;
for (curBarlineNumber = dBarlineMap.firstKey(); curBarlineNumber <= dBarlineMap.lastKey() && dBarlineMap[curBarlineNumber]->xPos() < _worldX; curBarlineNumber++)
;
for (; curBarlineNumber <= dBarlineMap.lastKey() && dBarlineMap[curBarlineNumber]->xPos() > _worldX && dBarlineMap[curBarlineNumber]->xPos() + dBarlineMap[curBarlineNumber]->width() < _worldX + _worldW;
curBarlineNumber++) {
CADrawableBarline* curDBarline = dBarlineMap[curBarlineNumber];
if (dBarlineMap.contains(curBarlineNumber + 1)) { // don't draw the last bar number
double center = qRound((curDBarline->xPos() - _worldX) * _zoom);
p.drawText(center - 1, RULER_HEIGHT - 2, QString::number(curBarlineNumber));
}
}
}
// TODO: draw the time marks on the left as in NoteEdit
}
// draw note checker errors
{
QList<CADrawableNoteCheckerError*> dnceList = _drawableNCEList.findInRange(_worldX, _worldY, _worldW, _worldH);
for (int i = 0; i < dnceList.size(); i++) {
CADrawSettings c = {
_zoom,
qRound((dnceList[i]->xPos() - _worldX) * _zoom),
qRound((dnceList[i]->yPos() - _worldY) * _zoom),
drawableWidth(), drawableHeight(),
Qt::red,
_worldX,
_worldY
};
dnceList[i]->draw(&p, c);
}
}
// draw selection regions
for (int i = 0; i < selectionRegionList().size(); i++) {
CADrawSettings c = {
_zoom,
qRound((selectionRegionList().at(i).x() - _worldX) * _zoom),
qRound((selectionRegionList().at(i).y() - _worldY) * _zoom),
qRound(selectionRegionList().at(i).width() * _zoom),
qRound(selectionRegionList().at(i).height() * _zoom),
selectionAreaColor(),
_worldX,
_worldY
};
drawSelectionRegion(&p, c);
}
// draw shadow note
if (_shadowNoteVisible) {
for (int i = 0; i < _shadowDrawableNote.size(); i++) {
if (CACanorus::settings()->shadowNotesInOtherStaffs() || _shadowDrawableNote[i]->drawableContext() == currentContext()) {
CADrawSettings s = {
_zoom,
qRound((_shadowDrawableNote[i]->xPos() - _worldX - _shadowDrawableNote[i]->width() / 2) * _zoom),
qRound((_shadowDrawableNote[i]->yPos() - _worldY) * _zoom),
drawableWidth(), drawableHeight(),
disabledElementsColor(),
_worldX,
_worldY
};
_shadowDrawableNote[i]->draw(&p, s);
if (_drawShadowNoteAccs) {
CADrawableAccidental acc(_shadowNoteAccs, nullptr, nullptr, 0, _shadowDrawableNote[i]->yCenter());
s.x -= qRound((acc.width() + 2) * _zoom);
s.y = qRound((acc.yPos() - _worldY) * _zoom);
acc.draw(&p, s);
}
}
}
// draw note name
if (_shadowNote.size()) {
QFont font("FreeSans");
font.setPixelSize(20);
p.setFont(font);
p.setPen(disabledElementsColor());
p.drawText(qRound((_xCursor - _worldX + 10) * _zoom), qRound((_yCursor - _worldY - 10) * _zoom), CANote::generateNoteName(_shadowNote[0]->diatonicPitch().noteName(), _shadowNoteAccs));
}
}
gettimeofday(&timeEnd2, nullptr);
// std::cout << "finding elements to draw took " << timeEnd.tv_sec-timeStart.tv_sec+(timeEnd.tv_usec-timeStart.tv_usec)/1000000.0 << "s." << std::endl;
// std::cout << "painting " << mList.size() << " elements took " << timeEnd2.tv_sec-timeEnd.tv_sec+(timeEnd2.tv_usec-timeEnd.tv_usec)/1000000.0 << "s." << std::endl;
// flush the oldWorld coordinates as they're needed for the first repaint only
_oldWorldX = _worldX;
_oldWorldY = _worldY;
_oldWorldW = _worldW;
_oldWorldH = _worldH;
if (_repaintArea) {
delete _repaintArea;
_repaintArea = nullptr;
}
}
void CAScoreView::updateHelpers()
{
// Shadow notes
if (currentContext() ? (currentContext()->drawableContextType() == CADrawableContext::DrawableStaff) : 0) {
int pitch = (static_cast<CADrawableStaff*>(currentContext()))->calculatePitch(_xCursor, _yCursor); // the current staff has the real pitch we need
for (int i = 0; i < _shadowNote.size(); i++) { // apply this pitch to all shadow notes in all staffs
//CAClef *clef = (static_cast<CADrawableStaff*>(_shadowDrawableNote[i]->drawableContext()))->getClef( _xCursor );
CADiatonicPitch dPitch(pitch, 0);
_shadowNote[i]->setDiatonicPitch(dPitch);
if (selectedVoice()) {
_shadowNote[i]->setStemDirection(selectedVoice()->stemDirection());
}
CADrawableContext* c = _shadowDrawableNote[i]->drawableContext();
delete _shadowDrawableNote[i];
_shadowDrawableNote[i] = new CADrawableNote(_shadowNote[i], c, _xCursor, static_cast<CADrawableStaff*>(c)->calculateCenterYCoord(pitch, _xCursor), true);
}
}
// Text edit widget
if (textEditVisible()) {
textEdit()->setFont(QFont("Century Schoolbook L", qRound(zoom() * (12 - 2))));
textEdit()->setGeometry(
qRound((textEditGeometry().x() - worldX()) * zoom()),
qRound((textEditGeometry().y() - worldY()) * zoom()),
qRound(textEditGeometry().width() * zoom()),
qRound(textEditGeometry().height() * zoom()));
textEdit()->show();
} else {
textEdit()->hide();
}
}
void CAScoreView::drawSelectionRegion(QPainter* p, CADrawSettings s)
{
p->fillRect(s.x, s.y, s.w, s.h, QBrush(s.color));
}
/*!
Draws the border with the given pen style, color, width and other pen settings.
Enables border.
*/
void CAScoreView::setBorder(const QPen pen)
{
_borderPen = pen;
_drawBorder = true;
}
/*!
Disables the border.
*/
void CAScoreView::unsetBorder()
{
_drawBorder = false;
}
/*!
Called when the user resizes the widget.
Note that repaint() event is also triggered when the internal drawable canvas changes its size (for eg. when scrollbars are shown/hidden) and the size of the view does not change.
*/
void CAScoreView::resizeEvent(QResizeEvent*)
{
setWorldCoords(_worldX, _worldY, drawableWidth() / _zoom, drawableHeight() / _zoom);
// setWorld methods already check for scrollbars
}
/*!
Checks whether the scrollbars are needed (the whole scene is not rendered) or not.
Scrollbars get shown or hidden here.
Repaint is done automatically, if needed.
*/
void CAScoreView::checkScrollBars()
{
if ((isScrollBarVisible() != ScrollBarShowIfNeeded) || (_checkScrollBarsDeadLock))
return;
bool change = false;
_holdRepaint = true; // disable repaint until the scrollbar values are set
_checkScrollBarsDeadLock = true; // disable any further method calls until the method is over
if ((((getMaxXExtended(_drawableMList) > getMaxXExtended(_drawableCList)) ? getMaxXExtended(_drawableMList) : getMaxXExtended(_drawableCList)) - worldWidth() > 0) || (_hScrollBar->value() != 0)) { //if scrollbar is needed
if (!_hScrollBar->isVisible()) {
_hScrollBar->show();
change = true;
}
} else // if the whole scene can be drawn on the canvas and the scrollbars are at position 0
if (_hScrollBar->isVisible()) {
_hScrollBar->hide();
change = true;
}
if ((((getMaxYExtended(_drawableMList) > getMaxYExtended(_drawableCList)) ? getMaxYExtended(_drawableMList) : getMaxYExtended(_drawableCList)) - worldHeight() > 0) || (_vScrollBar->value() != 0)) { //if scrollbar is needed
if (!_vScrollBar->isVisible()) {
_vScrollBar->show();
change = true;
}
} else // if the whole scene can be drawn on the canvas and the scrollbars are at position 0
if (_vScrollBar->isVisible()) {
_vScrollBar->hide();
change = true;
}
if (change) {
setWorldHeight(drawableHeight() / _zoom);
setWorldWidth(drawableWidth() / _zoom);
}
_holdRepaint = false;
_checkScrollBarsDeadLock = false;
}
/*!
This functions forward the Tab and Shift+Tab keys to keyPressEvent(), if grabTabKey is True.
*/
bool CAScoreView::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if ((keyEvent->key() == Qt::Key_Tab || keyEvent->key() == Qt::Key_Backtab) && _grabTabKey) {
keyPressEvent(keyEvent);
return true;
}
}
return QWidget::event(event);
}
/*!
Processes the mousePressEvent().
A new signal is emitted: CAMousePressEvent(), which usually gets processed by the parent class then.
*/
void CAScoreView::mousePressEvent(QMouseEvent* e)
{
CAView::mousePressEvent(e);
QPoint coords(e->x() / _zoom + _worldX, e->y() / _zoom + _worldY);
if (selection().size() && selection()[0]->isHScalable() && coords.y() >= selection()[0]->yPos() && coords.y() <= selection()[0]->yPos() + selection()[0]->height()) {
if (coords.x() == selection()[0]->xPos()) {
setResizeDirection(CADrawable::Left);
} else if (coords.x() == selection()[0]->xPos() + selection()[0]->width()) {
setResizeDirection(CADrawable::Right);
}
} else if (selection().size() && selection().at(0)->isVScalable() && coords.x() >= selection()[0]->xPos() && coords.x() <= selection()[0]->xPos() + selection()[0]->width()) {
if (coords.y() == selection()[0]->yPos()) {
setResizeDirection(CADrawable::Top);
} else if (coords.y() == selection()[0]->yPos() + selection()[0]->height()) {
setResizeDirection(CADrawable::Bottom);
}
}
if (!_clickTimer->isActive() || coords != lastMousePressCoords()) {
_clickTimer->start();
}
emit CAMousePressEvent(e, coords);
if (coords != lastMousePressCoords()) {
setLastMousePressCoords(coords);
_numberOfClicks = 1;
} else {
_numberOfClicks++;
}
if (_numberOfClicks == 2) {
emit CADoubleClickEvent(e, coords);
} else if (_numberOfClicks == 3) {
emit CATripleClickEvent(e, coords);
}
}
/*!
Clears number of clicks done so far inside one interval.
This function is usually click timer's slot.
*/
void CAScoreView::on_clickTimer_timeout()
{
_numberOfClicks = 0;
}
/*!
Processes the mouseReleaseEvent().
A new signal is emitted: CAMouseReleaseEvent(), which usually gets processed by the parent class then.
*/
void CAScoreView::mouseReleaseEvent(QMouseEvent* e)
{
emit CAMouseReleaseEvent(e, QPoint(e->x() / _zoom + _worldX, e->y() / _zoom + _worldY));
setResizeDirection(CADrawable::Undefined);
}
/*!
Processes the mouseMoveEvent().
A new signal is emitted: CAMouseMoveEvent(), which usually gets processed by the parent class then.
*/
void CAScoreView::mouseMoveEvent(QMouseEvent* e)
{
QPoint coords(e->x() / _zoom + _worldX, e->y() / _zoom + _worldY);
_xCursor = coords.x();
_yCursor = coords.y();
bool isHScalable = false;
for (int i = 0; i < selection().size() && !isHScalable; i++) {
if (selection()[i]->isHScalable() && (coords.x() == selection()[i]->xPos() || coords.x() == selection()[i]->xPos() + selection()[i]->width()) && coords.y() >= selection()[i]->yPos() && coords.y() <= selection()[i]->yPos() + selection()[i]->height())
isHScalable = true;
}
bool isVScalable = false;
for (int i = 0; i < selection().size() && !isVScalable; i++) {
if (selection()[i]->isVScalable() && (coords.y() == selection()[i]->yPos() || coords.y() == selection()[i]->yPos() + selection()[i]->height()) && coords.x() >= selection()[i]->xPos() && coords.x() <= selection()[i]->xPos() + selection()[i]->width())
isVScalable = true;
}
if (isHScalable)
setCursor(Qt::SizeHorCursor);
else if (isVScalable)
setCursor(Qt::SizeVerCursor);
else
setCursor(Qt::ArrowCursor);
emit CAMouseMoveEvent(e, coords);
}
/*!
Calculates the distance between the start of the mouse drag and the current position
in world coordinates and returns true, if it is larger than SELECTION_REGION_THRESHOLD.
@return True, if the selection region should be activated; False otherwise.
*/
bool CAScoreView::mouseDragActivated()
{
return qMax(qAbs(_xCursor - _lastMousePressCoords.x()), qAbs(_yCursor - _lastMousePressCoords.y())) * _zoom >= SELECTION_REGION_THRESHOLD;
}
/*!
Is click timer still active and waiting for potential double or triple click.
@return True, if click timer is activated; False otherwise.
*/
bool CAScoreView::clickTimerActivated()
{
return _clickTimer->isActive();
}
/*!
Processes the wheelEvent().
A new signal is emitted: CAWheelEvent(), which usually gets processed by the parent class then.
*/
void CAScoreView::wheelEvent(QWheelEvent* e)
{
QPoint coords(static_cast<int>(e->x() / _zoom + _worldX), static_cast<int>(e->y() / _zoom + _worldY));
emit CAWheelEvent(e, coords);
// Note Reinhard 01/20: Casting to int removed, does not make sense to me (actual cast is done above).
// Use faster upper, floor, round etc. if needed in that part (as long as worldX is stored in double)
_xCursor = (e->x() / _zoom) + _worldX; //TODO: _xCursor and _yCursor are still the old one. Somehow, _zoom level and _worldX/Y are not updated when emmiting CAWheel event. -Matevz
_yCursor = (e->y() / _zoom) + _worldY;
}
/*!
Processes the keyPressEvent().
A new signal is emitted: CAKeyPressEvent(), which usually gets processed by the parent class then.
*/
void CAScoreView::keyPressEvent(QKeyEvent* e)
{
emit CAKeyPressEvent(e);
}
void CAScoreView::setScrollBarVisible(CAScrollBarVisibility status)
{
_scrollBarVisible = status;
if ((status == ScrollBarAlwaysVisible) && (!_hScrollBar->isVisible())) {
_hScrollBar->show();
_vScrollBar->show();
return;
}
if ((status == ScrollBarAlwaysHidden) && (_hScrollBar->isVisible())) {
_hScrollBar->hide();
_vScrollBar->hide();
return;
}
checkScrollBars();
}
/*!
Processes the Horizontal scroll bar event.
This method is called when the horizontal scrollbar changes its value, let it be internally or due to user interaction.
*/
void CAScoreView::HScrollBarEvent(int val)
{
if ((_allowManualScroll) && (!_hScrollBarDeadLock)) {
setWorldX(val);
repaint();
}
}
/*!
Processes the Vertical scroll bar event.
This method is called when the horizontal scrollbar changes its value, let it be internally or due to user interaction.
*/
void CAScoreView::VScrollBarEvent(int val)
{
if ((_allowManualScroll) && (!_vScrollBarDeadLock)) {
setWorldY(val);
repaint();
}
}
void CAScoreView::leaveEvent(QEvent*)
{
_shadowNoteVisibleOnLeave = _shadowNoteVisible;
_shadowNoteVisible = false;
repaint();
}
void CAScoreView::enterEvent(QEvent*)
{
_shadowNoteVisible = _shadowNoteVisibleOnLeave;
repaint();
}
void CAScoreView::startAnimationTimer()
{
_animationTimer->stop();
_animationStep = 0;
_animationTimer->start();
on_animationTimer_timeout();
}
/*!
Selects the next music element in the current context (voice, if selectedVoice is set) or appends the next music element
to the selection, if \a append is True.
Returns a pointer to the newly selected drawable music element or nullptr, if such an element doesn't exist or the selection is empty.
This method is usually called when using the right arrow key.
*/
CADrawableMusElement* CAScoreView::selectNextMusElement(bool append)
{
if (_selection.isEmpty())
return nullptr;
CAMusElement* musElement = _selection.back()->musElement();
if (selectedVoice())
musElement = selectedVoice()->next(musElement);
else
musElement = musElement->context()->next(musElement);
if (!musElement)
return nullptr;
if (append)
return addToSelection(musElement);
else
return selectMElement(musElement);
}
/*!
Selects the next music element in the current context (voice, if selectedVoice is set) or appends the next music element
to the selection, if \a append is True.
Returns a pointer to the newly selected drawable music element or nullptr, if such an element doesn't exist or the selection is empty.
This method is usually called when using the left arrow key.
*/
CADrawableMusElement* CAScoreView::selectPrevMusElement(bool append)
{
if (_selection.isEmpty())
return nullptr;
CAMusElement* musElement = _selection.front()->musElement();
if (selectedVoice())
musElement = selectedVoice()->previous(musElement);
else
musElement = musElement->context()->previous(musElement);
if (!musElement)
return nullptr;
if (append)
return addToSelection(musElement);
else
return selectMElement(musElement);
}
/*!
Selects the upper music element in the current context.
Returns a pointer to the newly selected drawable music element or nullptr, if such an element doesn't exist or the selection is empty.
This method is usually called when using the up arrow key.
\todo Still needs to be written. Currently, it only returns the currently selected element.
*/
CADrawableMusElement* CAScoreView::selectUpMusElement()
{
if (_selection.isEmpty())
return nullptr;
return _selection.front();
}
/*!
Selects the lower music element in the current context.
Returns a pointer to the newly selected drawable music element or nullptr, if such an element doesn't exist or the selection is empty.
This method is usually called when using the up arrow key.
\todo Still needs to be written. Currently, it only returns the currently selected element.
*/
CADrawableMusElement* CAScoreView::selectDownMusElement()
{
if (_selection.isEmpty())
return nullptr;
return _selection.front();
}
/*!
Adds the given drawable music element \a elt to the current selection.
*/
void CAScoreView::addToSelection(CADrawableMusElement* elt, bool triggerSignal)
{
int i;
for (i = 0; i < _selection.size() && _selection[i]->xPos() < elt->xPos(); i++)
;
if (elt->isSelectable())
_selection.insert(i, elt);
if (triggerSignal)
emit selectionChanged();
}
/*!
Adds the given list of drawable music elements \a list to the current selection.
*/
void CAScoreView::addToSelection(const QList<CADrawableMusElement*> list, bool selectableOnly)
{
for (int i = 0; i < list.size(); i++) {
if (!selectableOnly || (selectableOnly && list[i]->isSelectable()))
addToSelection(list[i], false);
}
emit selectionChanged();
}
/*!
Adds the drawable music element of the given abstract music element \a elt to the selection.
Returns a pointer to its drawable element or 0, if the music element is not part of this score view.
*/
CADrawableMusElement* CAScoreView::addToSelection(CAMusElement* elt)
{
QList<CADrawable*> l = _mapDrawable.values(elt);
for (int i = 0; i < l.size(); i++) {
addToSelection(static_cast<CADrawableMusElement*>(l[i]));
}
emit selectionChanged();
return _selection.back();
}
/*!
Adds the given list of abstract music elements to the selection.
*/
void CAScoreView::addToSelection(const QList<CAMusElement*> elts)
{
for (int i = 0; i < elts.size(); i++) {
QList<CADrawable*> l = _mapDrawable.values(elts[i]);
for (int j = 0; j < l.size(); j++) {
addToSelection(static_cast<CADrawableMusElement*>(l[j]), false);
}
}
emit selectionChanged();
}
/*!
Select all elements in the view.
This function is usually associated with CTRL+A key.
*/
void CAScoreView::selectAll()
{
clearSelection();
QList<CADrawableMusElement*> elts = _drawableMList.list();
for (int i = 0; i < elts.size(); i++)
addToSelection(elts[i], false);
emit selectionChanged();
}
/*!
Selects all elements in the current bar.
This function is usually called when double clicking on the bar.
*/
void CAScoreView::selectAllCurBar()
{
if (!currentContext() || currentContext()->drawableContextType() != CADrawableContext::DrawableStaff) {
return;
}
clearSelection();
if (selectedVoice()) {
addToSelection(selectedVoice()->getBar(coordsToTime(_lastMousePressCoords.x())));
} else {
QList<CAVoice*> voices = static_cast<CAStaff*>(currentContext()->context())->voiceList();
for (int i = 0; i < voices.size(); i++) {
addToSelection(voices[i]->getBar(coordsToTime(_lastMousePressCoords.x())));
}
}
emit selectionChanged();
}
/*!
Selects all elements in the current context (line).
This function is usually called when triple clicking on the context.
*/
void CAScoreView::selectAllCurContext()
{
if (!currentContext()) {
return;
}
clearSelection();
addToSelection(currentContext()->drawableMusElementList(), false);
emit selectionChanged();
}
/*!
Inverts the current selection.
*/
void CAScoreView::invertSelection()
{
QList<CADrawableMusElement*> oldSelection = selection();
clearSelection();
QList<CADrawableMusElement*> elts = _drawableMList.list();
for (int i = 0; i < elts.size(); i++)
if (!oldSelection.contains(elts[i]))
addToSelection(elts[i], false);
emit selectionChanged();
}
/*!
Finds the first drawable instance of the given abstract music element.
\sa findCElement()
*/
CADrawableMusElement* CAScoreView::findMElement(CAMusElement* elt)
{
if (!elt) {
return nullptr;
}
QList<CADrawable*> hits = _mapDrawable.values(elt);
if (hits.size()) {
return static_cast<CADrawableMusElement*>(hits[0]);
}
return nullptr;
}
/*!
Finds the drawable instance of the given abstract context.
\sa findMElement()
*/
CADrawableContext* CAScoreView::findCElement(CAContext* context)
{
if (!context) {
return nullptr;
}
QList<CADrawable*> hits = _mapDrawable.values(context);
if (hits.size()) {
return static_cast<CADrawableContext*>(hits[0]);
}
return nullptr;
}
/*!
Creates a CATextEdit widget over the existing drawable syllable or chord name \a dMusElt.
Returns the pointer to the created widget.
\sa createTextEdit( QRect geometry )
*/
CATextEdit* CAScoreView::createTextEdit(CADrawableMusElement* dMusElt)
{
if (!dMusElt || !dMusElt->musElement())
return nullptr;
CAMusElement* musElt = dMusElt->musElement();
double xPos = dMusElt->xPos(), yPos = dMusElt->yPos(), width = 100, height = 25;
QString text;
// extend the edit widget width to the right neighbor, if the music element is part of the context.
if (musElt->context()) {
CADrawableMusElement* dRight = findMElement(musElt->context()->next(musElt));
if (dRight)
width = dRight->xPos() - dMusElt->xPos();
}
switch (dMusElt->musElement()->musElementType()) {
case CAMusElement::Syllable: {
CASyllable* syllable = static_cast<CASyllable*>(dMusElt->musElement());
text = syllable->text();
if (syllable->hyphenStart())
text += "-";
else if (syllable->melismaStart())
text += "_";
break;
}
case CAMusElement::Mark: {
CAMark* mark = static_cast<CAMark*>(dMusElt->musElement());
if (mark->markType() == CAMark::Text) {
text = static_cast<CAText*>(mark)->text();
} else if (mark->markType() == CAMark::BookMark) {
text = static_cast<CABookMark*>(mark)->text();
}
break;
}
case CAMusElement::ChordName: {
CAChordName* cn = static_cast<CAChordName*>(dMusElt->musElement());
if (cn->diatonicPitch().noteName() == CADiatonicPitch::Undefined) {
if (!cn->qualityModifier().isEmpty()) {
text = cn->qualityModifier();
}
} else {
text = CADiatonicPitch::diatonicPitchToString(cn->diatonicPitch());
if (!cn->qualityModifier().isEmpty()) {
text += QString(":") + cn->qualityModifier();
}
}
break;
}
default:
qDebug() << "Error: CATextEdit should not be created for music element of type" << dMusElt->musElement()->musElementType();
break;
}
textEdit()->setText(text);
setTextEditVisible(true);
setTextEditGeometry(QRect(static_cast<int>(xPos - 2.0), static_cast<int>(yPos), static_cast<int>(width + 2.0), static_cast<int>(height)));
updateHelpers(); // show it
textEdit()->setFocus();
return textEdit();
}
/*!
Removes and deletes the text edit when quitting text editing mode.
*/
void CAScoreView::removeTextEdit()
{
setTextEditVisible(false); // don't delete it, just hide it!
updateHelpers();
textEdit()->setText("");
this->setFocus();
}
/*!
Returns the maximum X of the viewable World a little bigger to make insertion at the end easy.
*/
template <typename T>
double CAScoreView::getMaxXExtended(CAKDTree<T>& v)
{
return v.getMaxX() + RIGHT_EXTRA_SPACE;
}
/*!
Returns the maximum Y of the viewable World a little bigger to make insertion at the end easy.
*/
template <typename T>
double CAScoreView::getMaxYExtended(CAKDTree<T>& v)
{
return v.getMaxY() + BOTTOM_EXTRA_SPACE;
}
/*!
Returns a list of drawable contexts the current score view includes between
the vertical coordinates \a y1 and \a y2.
The context is in a list already if only part of the context is touched by the region.
That is the first returned context's top border is smaller than \a y1 and the last returned context's
bottom border is larger than \a x2.
*/
QList<CADrawableContext*> CAScoreView::findContextsInRegion(QRect& region)
{
return _drawableCList.findInRange(region);
}
/*!
Returns Canorus time for the given X coordinate \a x.
Returns 0, if no contexts are present.
*/
int CAScoreView::coordsToTime(double x)
{
CADrawableMusElement* d1 = nearestLeftElement(x, 0);
if (selection().contains(d1)) {
CADrawableMusElement* newD1 = nearestLeftElement(d1->xPos(), 0);
d1 = newD1;
}
CADrawableMusElement* d2 = nearestRightElement(x, 0);
if (selection().contains(d2)) {
CADrawableMusElement* newD2 = nearestRightElement(d2->xPos() + d2->width(), 0);
d2 = newD2;
}
if (d1 && d2 && d1->musElement() && d2->musElement()) {
int delta = (d2->xPos() - d1->xPos());
if (!delta)
delta = 1;
return qRound(d1->musElement()->timeStart() + (d2->musElement()->timeStart() - d1->musElement()->timeStart()) * ((x - d1->xPos()) / delta));
} else if (d1 && d1->musElement())
return (d1->musElement()->timeEnd());
else
return 0;
}
/*!
* Helper function for timeToCoords() when doing the binary search over elements.
*
* \sa timeMusElementLessThan
*/
bool CAScoreView::musElementTimeLessThan(const CAMusElement* a, const int b)
{
return (a->timeStart() < b);
}
/*!
* Helper function for timeToCoords() when doing the binary search over elements.
*
* \sa musElementTimeLessThan
*/
bool CAScoreView::timeMusElementLessThan(const int a, const CAMusElement* b)
{
return (a < b->timeStart());
}
/*!
Simple Version of \sa timeToCoords( time ):
Returns the X coordinate for the given Canorus \a time.
Returns -1, if such a time doesn't exist in the score.
*/
double CAScoreView::timeToCoordsSimpleVersion(int time)
{
CADrawableMusElement* leftElt = nullptr;
QList<CAVoice*> voiceList = _sheet->voiceList();
for (int i = 0; i < voiceList.size(); i++) {
// get the element still smaller or equal, but nearest to time
QList<CAMusElement*>::const_iterator it = std::lower_bound(voiceList[i]->musElementList().constBegin(), voiceList[i]->musElementList().constEnd(), time, CAScoreView::musElementTimeLessThan);
if (it != voiceList[i]->musElementList().constEnd()) {
if (_mapDrawable.contains(*it)) {
CADrawableMusElement* dElt = static_cast<CADrawableMusElement*>(_mapDrawable.values(*it).last());
if (leftElt && leftElt->xPos() < dElt->xPos()) {
leftElt = dElt;
}
} else {
std::cerr << "ERROR: Drawable instance of musElement " << (*it) << " doesn't exist in _mapDrawable!" << std::endl;
}
}
}
return leftElt ? (leftElt->xPos()) : (-1);
}
/*!
Returns the X coordinate for the given Canorus \a time.
Returns -1, if such a time doesn't exist in the score.
*/
double CAScoreView::timeToCoords(int time)
{
CADrawableMusElement* leftElt = nullptr;
CADrawableMusElement* rightElt = nullptr;
QList<CAVoice*> voiceList = _sheet->voiceList();
for (int i = 0; i < voiceList.size(); i++) {
// get the element still smaller or equal, but nearest to time
QList<CAMusElement*>::const_iterator it = std::lower_bound(voiceList[i]->musElementList().constBegin(), voiceList[i]->musElementList().constEnd(), time, CAScoreView::musElementTimeLessThan);
if (it != voiceList[i]->musElementList().constEnd()) {
if (_mapDrawable.contains(*it)) {
CADrawableMusElement* dElt = static_cast<CADrawableMusElement*>(_mapDrawable.values(*it).last());
if (!leftElt || leftElt->xPos() < dElt->xPos()) {
leftElt = dElt;
}
} else {
std::cerr << "ERROR: Drawable instance of musElement " << (*it) << " doesn't exist in _mapDrawable!" << std::endl;
}
}
// and for the right element
it = std::upper_bound(voiceList[i]->musElementList().constBegin(), voiceList[i]->musElementList().constEnd(), time, CAScoreView::timeMusElementLessThan);
if (it != voiceList[i]->musElementList().constEnd()) {
if (_mapDrawable.contains(*it)) {
CADrawableMusElement* dElt = static_cast<CADrawableMusElement*>(_mapDrawable.values(*it).first());
if (!rightElt || rightElt->xPos() > dElt->xPos()) {
rightElt = dElt;
}
} else {
std::cerr << "ERROR: Drawable instance of musElement " << (*it) << " doesn't exist in _mapDrawable!" << std::endl;
}
}
}
// get the relative position between the nearest left and the nearest right elements
if (leftElt && rightElt && leftElt->musElement() && rightElt->musElement()) {
int delta = (rightElt->musElement()->timeStart() - leftElt->musElement()->timeStart());
if (!delta)
delta = 1;
// Note Reinhard: Fixed conversion to double
// I assume that division by delta should result in double value
return leftElt->xPos() + (rightElt->xPos() - leftElt->xPos()) * static_cast<double>(time - leftElt->musElement()->timeStart() / static_cast<double>(delta));
} else {
return -1;
}
}
void CAScoreView::setShadowNoteLength(CAPlayableLength l)
{
for (int i = 0; i < _shadowNote.size(); i++) {
_shadowNote[i]->setPlayableLength(l);
}
updateHelpers();
}
/*!
Returns a list of currently selected music elements.
Does the same as selection(), but doesn't return their Drawable instances.
*/
QList<CAMusElement*> CAScoreView::musElementSelection()
{
QList<CAMusElement*> res;
for (int i = 0; i < _selection.size(); i++) {
if (!res.contains(_selection[i]->musElement())) {
res << _selection[i]->musElement();
}
}
return res;
}
/*!
\fn CASheet *CAScoreView::sheet()
Returns the pointer to the view's sheet it represents.
*/
/*!
\fn bool CAScoreView::removeFromSelection(CADrawableMusElement *elt)
Removes the given drawable music element \a elt from the selection, if it exists.
Returns True, if element existed in the selection and was removed, false otherwise.
*/
/*!
\fn void CAScoreView::clearSelection()
Clears the current selection. Its behaviour is the same as calling clearMSelection() and clearCSelection().
*/
/*!
\fn QList<CAMusElement*> CAScoreView::selection()
Returns a list of the currently selected drawable music elements.
*/
/*!
\var bool CAScoreView::_allowManualScroll
This property holds whether a user interaction with the scrollbars actually triggers the scroll of the view.
*/
/*!
\enum CAScoreView::CAScrollBarVisibility
Different behaviour of the scroll bars:
- ScrollBarAlwaysVisible - scrollbars are always visible, no matter if the whole scene can be rendered on canvas or not
- ScrollBarAlwaysHidden - scrollbars are always hidden, no matter if the whole scene can be rendered on canvas or not
- ScrollBarShowIfNeeded - scrollbars are visible, if they are needed (the current view area is too small to render the whole
scene), otherwise hidden. This is default behaviour.
*/
/*!
\fn float CAScoreView::zoom()
Returns the zoom level of the view (1.0 = 100%, 1.5 = 150% etc.).
*/
/*!
\fn void CAScoreView::setRepaintArea(QRect *area)
Sets the area to be repainted, not the whole widget.
\sa clearRepaintArea()
*/
/*!
\fn void CAScoreView::clearRepaintArea()
Disables and deletes the area to be repainted.
\sa setRepaintArea()
*/
/*!
\fn void CAScoreView::CAMousePressEvent(QMouseEvent *e, QPoint p, CAScoreView *v)
This signal is emitted when mousePressEvent() is called. Parent class is usually connected to this event.
It adds another two arguments to the mousePressEvent() function - pointer to this view and coordinates
in world coordinates where user used the mouse.
This is useful when a parent class wants to know which class the signal was emmitted by.
\param e Mouse event which gets processed.
\param p Coordinates of the mouse cursor in absolute world values.
\param v Pointer to this view (the view which emmitted the signal).
*/
/*!
\fn void CAScoreView::CAMouseMoveEvent(QMouseEvent *e, QPoint p, CAScoreView *v)
This signal is emitted when mouseMoveEvent() is called. Parent class is usually connected to this event.
It adds another two arguments to the mouseMoveEvent() function - pointer to this view and coordinates
in world coordinates where user used the mouse.
This is useful when a parent class wants to know which class the signal was emmitted by.
\param e Mouse event which gets processed.
\param p Coordinates of the mouse cursor in absolute world values.
\param v Pointer to this view (the view which emmitted the signal).
*/
/*!
\fn void CAScoreView::CAMouseReleaseEvent(QMouseEvent *e, QPoint p, CAScoreView *v)
This signal is emitted when mouseReleaseEvent() is called. Parent class is usually connected to this event.
It adds another two arguments to the mouseReleaseEvent() function - pointer to this score view and coordinates
in world coordinates where user used the mouse.
This is useful when a parent class wants to know which class the signal was emmitted by.
\param e Mouse event which gets processed.
\param p Coordinates of the mouse cursor in absolute world values.
\param v Pointer to this view (the view which emmitted the signal).
*/
/*!
\fn void CAScoreView::CAWheelEvent(QWheelEvent *e, QPoint p, CAScoreView *v)
This signal is emitted when wheelEvent() is called. Parent class is usually connected to this event.
It adds another two arguments to the wheelEvent() function - pointer to this score view and coordinates
in world coordinates where user used the mouse.
This is useful when a parent class wants to know which class the signal was emmitted by.
\param e Wheel event which gets processed.
\param p Coordinates of the mouse cursor in absolute world values.
\param v Pointer to this view (the view which emmitted the signal).
*/
/*!
\fn void CAScoreView::CAKeyPressEvent(QKeyEvent *e, CAScoreView *v)
This signal is emitted when keyPressEvent() is called. Parent class is usually connected to this event.
It adds another two arguments to the wheelEvent() function - pointer to this score view.
This is useful when a parent class wants to know which class the signal was emmitted by.
\param e Wheel event which gets processed.
\param v Pointer to this view (the view which emmitted the signal).
*/
| 75,148
|
C++
|
.cpp
| 1,803
| 36.36051
| 354
| 0.677322
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,393
|
resourceview.cpp
|
canorusmusic_canorus/src/widgets/resourceview.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "widgets/resourceview.h"
#include "canorus.h"
#include "control/resourcectl.h"
#include "score/document.h"
#include "score/resource.h"
#include <QAction>
#include <QContextMenuEvent>
#include <QFileDialog>
#include <QMenu>
#include <QMessageBox>
#include <QStringList>
/*!
\class CAResourceView
\brief Tree view of all the resources inside the document
This widget shows the resources stored inside the document in a
tree-view style. Pass the document to the constructor and call
rebuildUi() to refresh the GUI.
This widget also allows user to remove or rename the resources.
*/
/*!
Default constructor.
Pass the document \a doc. The view automatically gathers the resources
stored inside the document and shows them.
*/
CAResourceView::CAResourceView(CADocument* doc, QWidget* parent)
: QTreeWidget(parent)
, _document(doc)
{
setColumnCount(2);
setHeaderLabels(QStringList() << tr("Name") << tr("Linked"));
setWindowTitle(tr("Document Resources"));
connect(this, SIGNAL(itemChanged(QTreeWidgetItem*, int)), SLOT(on_itemChanged(QTreeWidgetItem*, int)));
rebuildUi();
}
CAResourceView::~CAResourceView()
{
}
void CAResourceView::rebuildUi()
{
clear();
_items.clear();
QList<std::shared_ptr<CAResource> > sItems;
for (int i = 0; i < selectedItems().size(); i++) {
if (_items[selectedItems()[i]]) {
sItems << _items[selectedItems()[i]];
}
}
if (document()) {
QTreeWidgetItem* doc = new QTreeWidgetItem(QStringList() << tr("Document") << "");
doc->setIcon(0, QIcon("images:document/document.svg"));
addTopLevelItem(doc);
for (int i = 0; i < document()->resourceList().size(); i++) {
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << document()->resourceList()[i]->name() << (document()->resourceList()[i]->isLinked() ? tr("yes") : tr("no")));
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
_items[item] = document()->resourceList()[i];
doc->addChild(item);
}
}
expandAll();
for (int i = 0; i < sItems.size(); i++) {
if (_items.key(sItems[i])) {
_items.key(sItems[i])->setSelected(true);
}
}
}
void CAResourceView::showEvent(QShowEvent*)
{
QList<CAMainWin*> mainWins = CACanorus::findMainWin(document());
for (int i = 0; i < mainWins.size(); i++) {
mainWins[i]->resourceViewAction()->setChecked(true);
}
}
void CAResourceView::closeEvent(QCloseEvent*)
{
QList<CAMainWin*> mainWins = CACanorus::findMainWin(document());
for (int i = 0; i < mainWins.size(); i++) {
mainWins[i]->resourceViewAction()->setChecked(false);
}
}
void CAResourceView::contextMenuEvent(QContextMenuEvent* e)
{
QList<QTreeWidgetItem*> selection = selectedItems();
if (selection.size() && _items[selection[0]]) {
std::shared_ptr<CAResource> resource = _items[selection[0]];
QList<QAction*> actions;
QAction* rename = new QAction(tr("Rename"), this);
actions << rename;
QAction* saveAs = nullptr;
if (!resource->isLinked()) {
saveAs = new QAction(tr("Save as..."), this);
actions << saveAs;
}
QAction* remove = new QAction(tr("Remove"), this);
actions << remove;
QAction* selectedAction = QMenu::exec(actions, e->globalPos());
if (selectedAction) {
if (selectedAction == rename) {
editItem(selection[0], 0);
} else if (selectedAction == remove && QMessageBox::question(this, tr("Confirm deletion"), tr("Do you want to remove resource \"%1\"?\n\nDeletion cannot be undone!").arg(resource->name()), QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) {
CAResourceCtl::deleteResource(resource);
CACanorus::rebuildUI(document());
} else if (selectedAction == saveAs) {
QString path = QFileDialog::getSaveFileName();
if (!path.isEmpty()) {
resource->copy(path);
}
}
}
}
}
void CAResourceView::on_itemChanged(QTreeWidgetItem* i, int)
{
if (_items[i]) {
_items[i]->setName(i->text(0));
}
rebuildUi();
}
| 4,568
|
C++
|
.cpp
| 122
| 31.434426
| 263
| 0.640706
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,394
|
viewcontainer.cpp
|
canorusmusic_canorus/src/widgets/viewcontainer.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Itay Perl, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QGridLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QWheelEvent>
#include "score/note.h"
#include "score/sheet.h"
#include "score/staff.h"
#include "widgets/view.h"
#include "widgets/viewcontainer.h"
/*!
\class CAViewContainer
\brief Holds together resizable views.
This class behaves like dynamic QSplitter and can hold up a number of various views that can be customly resized.
Usually this container serves as a layout class for containers in the tab widget.
View port container should always include at least 1 view port. Otherwise there is no point of having the container at all!
That's why the initial view is required in constructor already.
\sa CAView
*/
/*!
Constructs the initial container having \a v as the initial view and a parent widget \a p.
*/
CAViewContainer::CAViewContainer(QWidget* parent)
: QSplitter(parent)
{
setOrientation(Qt::Vertical); // not side by side
setCurrentView(nullptr);
}
/*!
Removes all the views and finally destroys container.
\warning This destructor also deletes the views!
*/
CAViewContainer::~CAViewContainer()
{
// automatically deletes all the children including the splitters
}
/*!
Splits the given view \a v vertically or the last used view if none given.
Vertical split uses horizontal splitter.
Returns the newly created view.
*/
CAView* CAViewContainer::splitVertically(CAView* v)
{
if (!v && !(v = currentView()))
return nullptr;
QSplitter* splitter = _viewMap[v];
CAView* newView = v->clone(nullptr);
if (splitter->orientation() == Qt::Horizontal) {
addView(newView, splitter);
} else if (splitter->count() == 1) {
splitter->setOrientation(Qt::Horizontal);
addView(newView, splitter);
} else {
QSplitter* newSplitter = new QSplitter(Qt::Horizontal, nullptr);
int idx = splitter->indexOf(v);
addView(v, newSplitter);
addView(newView, newSplitter);
splitter->insertWidget(idx, newSplitter);
}
return newView;
}
/*!
Splits the given view \a v horizontally or the last used view if none given.
Horizontal split uses vertical splitter.
Returns the newly created view.
*/
CAView* CAViewContainer::splitHorizontally(CAView* v)
{
if (!v && !(v = currentView()))
return nullptr;
QSplitter* splitter = _viewMap[v];
CAView* newView = v->clone(nullptr);
if (splitter->orientation() == Qt::Vertical) {
addView(newView, splitter);
} else if (splitter->count() == 1) {
splitter->setOrientation(Qt::Vertical);
addView(newView, splitter);
} else {
QSplitter* newSplitter = new QSplitter(Qt::Vertical, nullptr);
int idx = splitter->indexOf(v);
addView(v, newSplitter);
addView(newView, newSplitter);
splitter->insertWidget(idx, newSplitter);
}
return newView;
}
/*!
Unsplits the views so the given view \a v is removed.
If no view is given, removes the last active one.
\return The pointer to the view which was removed. If none was removed (ie. the given view was not found or there are no views left) returns nullptr.
*/
CAView* CAViewContainer::unsplit(CAView* v)
{
if (!v && !(v = currentView()))
return nullptr;
QSplitter* s = _viewMap[v];
switch (s->count()) {
case 1:
// if (s==this). otherwise it'd never get here.
return nullptr;
case 2: {
QWidget* other = s->widget(1 - s->indexOf(v)); // find the other view
CAView* otherView = dynamic_cast<CAView*>(other);
if (s != this) {
other->setParent(s->parentWidget());
if (otherView)
_viewMap[otherView] = static_cast<QSplitter*>(s->parent());
removeView(v);
delete s; // delete the splitter
return v;
} else if (!otherView) {
// the following is needed to prevent the situation where a splitter is the only child of the view container - it causes some problems. -Itay
QSplitter* sp = static_cast<QSplitter*>(other);
setOrientation(sp->orientation());
while (sp->count()) {
CAView* view = dynamic_cast<CAView*>(sp->widget(0));
sp->widget(0)->setParent(this);
if (view)
_viewMap[view] = this;
}
delete sp; //delete the splitter after moving the view ports.
}
}
// Note Reinhard fallthrough is only a C++17 feature
// Currently we depend on gcc for build
// [[fallthrough]]
// [[clang::fallthrough]]; // falls through only if s == this
default:
removeView(v);
return v;
}
}
/*!
Unsplits all the views except the last active one.
*/
QList<CAView*> CAViewContainer::unsplitAll()
{
QList<CAView*> list;
while (count() > 1)
list << unsplit();
return list;
}
/*!
Adds and registers the given view \a v to the splitter \a s or the top splitter if not specified.
*/
void CAViewContainer::addView(CAView* v, QSplitter* s)
{
if (!s)
s = this;
_viewMap[v] = s;
s->addWidget(v);
setCurrentView(v);
}
/*!
Removes the given view from internal list and reselects the current view if the currentView() points to deleted view.
*/
void CAViewContainer::removeView(CAView* v)
{
_viewMap.remove(v);
delete v;
if (v == currentView())
setCurrentView(_viewMap.keys().last());
}
/*!
\fn CAViewContainer::lastUsedView()
Returns the pointer to the last used active view.
*/
/*!
\var CAViewContainer::_viewMap
Map of View : Splitter widgets. Every view has a splitter which it belongs to.
If a views is the top-most widget, then it belongs to CAViewContainer itself.
*/
| 6,008
|
C++
|
.cpp
| 177
| 28.954802
| 153
| 0.670055
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,395
|
settingsdialog.cpp
|
canorusmusic_canorus/src/ui/settingsdialog.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed punder the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QBoxLayout>
#include <QDir>
#include <QFileDialog>
#include <QSettings>
// Python.h needs to be loaded first!
#include "canorus.h"
#include "core/settings.h"
#include "interface/mididevice.h"
#include "score/clef.h" // needed for preview sheet
#include "score/sheet.h" // needed for preview sheet
#include "score/staff.h" // needed for preview sheet
#include "score/timesignature.h" // needed for preview sheet
#include "score/voice.h" // needed for preview sheet
#include "ui/settingsdialog.h"
#include "widgets/actionseditor.h"
/*!
\class CASettingsDialog
Settings dialog for various options like editor behaviour, loading/saving settings,
colors, playback options etc.
\sa CASettings
*/
CASettingsDialog::CASettingsDialog(CASettingsPage currentPage, CAMainWin* parent)
: QDialog(parent)
, _mainWin(parent)
{
setupUi(this);
buildPreviewSheet();
buildActionsEditorPage();
setupPages(currentPage);
exec();
}
CASettingsDialog::~CASettingsDialog()
{
delete _previewSheet;
}
void CASettingsDialog::setupPages(CASettingsPage currentPage)
{
// Editor Page
uiFinaleLyricsCheckBox->setChecked(CACanorus::settings()->finaleLyricsBehaviour());
uiShadowNotesInOtherStaffs->setChecked(CACanorus::settings()->shadowNotesInOtherStaffs());
uiPlayInsertedNotes->setChecked(CACanorus::settings()->playInsertedNotes());
uiAutoBar->setChecked(CACanorus::settings()->autoBar());
uiUseNoteChecker->setChecked(CACanorus::settings()->useNoteChecker());
// Appearance Page
uiAntiAliasing->setChecked(CACanorus::settings()->antiAliasing());
uiAnimatedScroll->setChecked(CACanorus::settings()->animatedScroll());
uiForegroundColor->setPalette(QPalette(CACanorus::settings()->foregroundColor()));
uiBackgroundColor->setPalette(QPalette(CACanorus::settings()->backgroundColor()));
uiSelectionColor->setPalette(QPalette(CACanorus::settings()->selectionColor()));
uiSelectionAreaColor->setPalette(QPalette(CACanorus::settings()->selectionAreaColor()));
uiSelectedContextColor->setPalette(QPalette(CACanorus::settings()->selectedContextColor()));
uiHiddenElementsColor->setPalette(QPalette(CACanorus::settings()->hiddenElementsColor()));
uiDisabledElementsColor->setPalette(QPalette(CACanorus::settings()->disabledElementsColor()));
uiPreviewScoreView->setSheet(_previewSheet);
uiPreviewScoreView->setGrabTabKey(false);
uiPreviewScoreView->setScrollBarVisible(CAScoreView::ScrollBarAlwaysHidden);
uiPreviewScoreView->rebuild();
uiPreviewScoreView->setZoom(0.6f, 0, 0, false, false);
uiPreviewScoreView->setCurrentContext(uiPreviewScoreView->findCElement(_previewSheet->staffList()[0]));
uiPreviewScoreView->addSelectionRegion(QRect(50, 40, 70, 90));
uiPreviewScoreView->addToSelection(_previewSheet->staffList()[0]->voiceList()[0]->musElementList()[1]);
uiPreviewScoreView->repaint();
// Commands Settings Page
// Loading Saving Page
uiDocumentsDirectory->setText(CACanorus::settings()->documentsDirectory().absolutePath());
uiDefaultSaveComboBox->addItems(_mainWin->saveDialog()->nameFilters());
uiDefaultSaveComboBox->setCurrentIndex(
uiDefaultSaveComboBox->findText(
CAFileFormats::getFilter(CACanorus::settings()->defaultSaveFormat())));
uiAutoRecoverySpinBox->setValue(CACanorus::settings()->autoRecoveryInterval());
// Playback Page
_midiInPorts = CACanorus::midiDevice()->getInputPorts();
_midiOutPorts = CACanorus::midiDevice()->getOutputPorts();
uiMidiInList->addItem(tr("None"));
for (int i = 0; i < _midiInPorts.values().size(); i++) {
uiMidiInList->addItem(_midiInPorts.value(i));
if (CACanorus::settings()->midiInPort() == _midiInPorts.keys().at(i))
uiMidiInList->setCurrentItem(uiMidiInList->item(i + 1)); // select the previous device
}
if (CACanorus::settings()->midiInPort() == -1)
uiMidiInList->setCurrentItem(uiMidiInList->item(0)); // select the previous device
uiMidiOutList->addItem(tr("None"));
for (int i = 0; i < _midiOutPorts.values().size(); i++) {
uiMidiOutList->addItem(_midiOutPorts.value(i));
if (CACanorus::settings()->midiOutPort() == _midiOutPorts.keys().at(i))
uiMidiOutList->setCurrentItem(uiMidiOutList->item(i + 1)); // select the previous device
}
if (CACanorus::settings()->midiOutPort() == -1)
uiMidiOutList->setCurrentItem(uiMidiOutList->item(0)); // select the previous device
uiSettingsList->setCurrentRow((currentPage != UndefinedSettings) ? currentPage : 0);
// Printing Page
uiTypesetter->setCurrentIndex(CACanorus::settings()->typesetter() - 1);
uiTypesetterLocation->setText(CACanorus::settings()->typesetterLocation());
uiTypesetterDefault->setChecked(CACanorus::settings()->useSystemDefaultTypesetter());
uiPdfViewerLocation->setText(CACanorus::settings()->pdfViewerLocation());
uiPdfViewerDefault->setChecked(CACanorus::settings()->useSystemDefaultPdfViewer());
}
void CASettingsDialog::on_uiButtonBox_clicked(QAbstractButton* button)
{
if (uiButtonBox->standardButton(button) == QDialogButtonBox::Ok) {
applySettings();
hide();
} else if (uiButtonBox->standardButton(button) == QDialogButtonBox::Cancel) {
hide();
} else if (uiButtonBox->standardButton(button) == QDialogButtonBox::Apply) {
applySettings();
}
}
void CASettingsDialog::on_uiSettingsList_currentItemChanged(QListWidgetItem* current, QListWidgetItem*)
{
uiPageNameLabel->setText(current->text());
uiStackedWidget->setCurrentIndex(uiSettingsList->row(current));
}
void CASettingsDialog::applySettings()
{
// Editor Page
CACanorus::settings()->setFinaleLyricsBehaviour(uiFinaleLyricsCheckBox->isChecked());
CACanorus::settings()->setShadowNotesInOtherStaffs(uiShadowNotesInOtherStaffs->isChecked());
CACanorus::settings()->setPlayInsertedNotes(uiPlayInsertedNotes->isChecked());
CACanorus::settings()->setAutoBar(uiAutoBar->isChecked());
CACanorus::settings()->setUseNoteChecker(uiUseNoteChecker->isChecked());
// Saving/Loading Page
CACanorus::settings()->setDocumentsDirectory(uiDocumentsDirectory->text());
_mainWin->uiOpenDialog->setDirectory(CACanorus::settings()->documentsDirectory());
_mainWin->uiSaveDialog->setDirectory(CACanorus::settings()->documentsDirectory());
_mainWin->uiImportDialog->setDirectory(CACanorus::settings()->documentsDirectory());
_mainWin->uiExportDialog->setDirectory(CACanorus::settings()->documentsDirectory());
CACanorus::settings()->setDefaultSaveFormat(CAFileFormats::getType(uiDefaultSaveComboBox->currentText()));
_mainWin->uiSaveDialog->selectNameFilter(uiDefaultSaveComboBox->currentText());
CACanorus::settings()->setAutoRecoveryInterval(uiAutoRecoverySpinBox->value());
CACanorus::autoRecovery()->updateTimer();
// Appearance Page
CACanorus::settings()->setAntiAliasing(uiAntiAliasing->isChecked());
CACanorus::settings()->setAnimatedScroll(uiAnimatedScroll->isChecked());
CACanorus::settings()->setBackgroundColor(uiBackgroundColor->palette().color(QPalette::Window));
CACanorus::settings()->setForegroundColor(uiForegroundColor->palette().color(QPalette::Window));
CACanorus::settings()->setSelectionColor(uiSelectionColor->palette().color(QPalette::Window));
CACanorus::settings()->setSelectionAreaColor(uiSelectionAreaColor->palette().color(QPalette::Window));
CACanorus::settings()->setSelectedContextColor(uiSelectedContextColor->palette().color(QPalette::Window));
CACanorus::settings()->setHiddenElementsColor(uiHiddenElementsColor->palette().color(QPalette::Window));
CACanorus::settings()->setDisabledElementsColor(uiDisabledElementsColor->palette().color(QPalette::Window));
// Playback Page
if (uiMidiInList->currentIndex().row() == 0)
CACanorus::settings()->setMidiInPort(-1);
else
CACanorus::settings()->setMidiInPort(_midiInPorts.keys().at(uiMidiInList->currentIndex().row() - 1));
if (uiMidiOutList->currentIndex().row() == 0)
CACanorus::settings()->setMidiOutPort(-1);
else
CACanorus::settings()->setMidiOutPort(_midiOutPorts.keys().at(uiMidiOutList->currentIndex().row() - 1));
// Printing Page
CACanorus::settings()->setTypesetter(static_cast<CATypesetter::CATypesetterType>(uiTypesetter->currentIndex() + 1));
CACanorus::settings()->setTypesetterLocation(uiTypesetterLocation->text());
CACanorus::settings()->setUseSystemDefaultTypesetter(uiTypesetterDefault->isChecked());
CACanorus::settings()->setPdfViewerLocation(uiPdfViewerLocation->text());
CACanorus::settings()->setUseSystemDefaultPdfViewer(uiPdfViewerDefault->isChecked());
CACanorus::settings()->writeSettings();
}
void CASettingsDialog::buildActionsEditorPage()
{
//int i;
//QWidget oSingleActions; // all actions added here
const QList<CASingleAction*>& roSAList = CACanorus::settings()->getActionList();
if (roSAList.size() <= 0) {
qWarning("List of Actions is empty!");
return;
}
_commandsEditor = new CAActionsEditor(nullptr);
_commandsEditor->setObjectName(QString::fromUtf8("commandsEditor"));
commandsSettingsVBoxLayout->addWidget(_commandsEditor);
// Read all elements from single action list (API requirement)
//for(i=0; i< roSAList.size(); ++i)
// oSingleActions.addAction( roSAList[i]->getAction() );
// Add all command actions (loading happens earlier in Canorus)
_commandsEditor->addActions(roSAList);
}
void CASettingsDialog::buildPreviewSheet()
{
_previewSheet = new CASheet("", nullptr);
_previewSheet->addStaff();
_previewSheet->staffList()[0]->voiceList()[0]->append(new CAClef(CAClef::Treble, _previewSheet->staffList()[0], 0));
_previewSheet->staffList()[0]->voiceList()[0]->append(new CATimeSignature(2, 2, _previewSheet->staffList()[0], 0));
_previewSheet->addStaff();
}
void CASettingsDialog::on_uiDocumentsDirectoryBrowse_clicked(bool)
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Choose default documents directory"));
if (dir.size())
uiDocumentsDirectory->setText(dir);
}
void CASettingsDialog::on_uiDocumentsDirectoryRevert_clicked(bool)
{
uiDocumentsDirectory->setText(CASettings::DEFAULT_DOCUMENTS_DIRECTORY.absolutePath());
}
void CASettingsDialog::on_uiBackgroundColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiBackgroundColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiBackgroundColor->setPalette(QPalette(c));
uiPreviewScoreView->setBackgroundColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiBackgroundRevert_clicked(bool)
{
uiBackgroundColor->setPalette(QPalette(CASettings::DEFAULT_BACKGROUND_COLOR));
uiPreviewScoreView->setBackgroundColor(CASettings::DEFAULT_BACKGROUND_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiForegroundColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiForegroundColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiForegroundColor->setPalette(QPalette(c));
uiPreviewScoreView->setForegroundColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiForegroundRevert_clicked(bool)
{
uiForegroundColor->setPalette(QPalette(CASettings::DEFAULT_FOREGROUND_COLOR));
uiPreviewScoreView->setForegroundColor(CASettings::DEFAULT_FOREGROUND_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiSelectionColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiSelectionColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiSelectionColor->setPalette(QPalette(c));
uiPreviewScoreView->setSelectionColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiSelectionRevert_clicked(bool)
{
uiSelectionColor->setPalette(QPalette(CASettings::DEFAULT_SELECTION_COLOR));
uiPreviewScoreView->setSelectionColor(CASettings::DEFAULT_SELECTION_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiSelectionAreaColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiSelectionAreaColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiSelectionAreaColor->setPalette(QPalette(c));
uiPreviewScoreView->setSelectionAreaColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiSelectionAreaRevert_clicked(bool)
{
uiSelectionAreaColor->setPalette(QPalette(CASettings::DEFAULT_SELECTION_AREA_COLOR));
uiPreviewScoreView->setSelectionAreaColor(CASettings::DEFAULT_SELECTION_AREA_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiSelectedContextColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiSelectedContextColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiSelectedContextColor->setPalette(QPalette(c));
uiPreviewScoreView->setSelectedContextColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiSelectedContextRevert_clicked(bool)
{
uiSelectedContextColor->setPalette(QPalette(CASettings::DEFAULT_SELECTED_CONTEXT_COLOR));
uiPreviewScoreView->setSelectedContextColor(CASettings::DEFAULT_SELECTED_CONTEXT_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiHiddenElementsColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiHiddenElementsColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiHiddenElementsColor->setPalette(QPalette(c));
uiPreviewScoreView->setHiddenElementsColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiHiddenElementsRevert_clicked(bool)
{
uiHiddenElementsColor->setPalette(QPalette(CASettings::DEFAULT_HIDDEN_ELEMENTS_COLOR));
uiPreviewScoreView->setHiddenElementsColor(CASettings::DEFAULT_HIDDEN_ELEMENTS_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiDisabledElementsColor_clicked(bool)
{
QColor c = QColorDialog::getColor(uiDisabledElementsColor->palette().color(QPalette::Window), this, QString(), QColorDialog::ShowAlphaChannel);
if (c.isValid()) {
uiDisabledElementsColor->setPalette(QPalette(c));
uiPreviewScoreView->setDisabledElementsColor(c);
uiPreviewScoreView->repaint();
}
}
void CASettingsDialog::on_uiDisabledElementsRevert_clicked(bool)
{
uiDisabledElementsColor->setPalette(QPalette(CASettings::DEFAULT_DISABLED_ELEMENTS_COLOR));
uiPreviewScoreView->setDisabledElementsColor(CASettings::DEFAULT_DISABLED_ELEMENTS_COLOR);
uiPreviewScoreView->repaint();
}
void CASettingsDialog::on_uiTypesetterBrowse_clicked(bool)
{
QString path = QFileDialog::getOpenFileName(static_cast<QWidget*>(parent()), tr("Select typesetter executable"));
if (!path.isNull()) {
uiTypesetterLocation->setText(path);
}
}
void CASettingsDialog::on_uiPdfViewerBrowse_clicked(bool)
{
QString path = QFileDialog::getOpenFileName(static_cast<QWidget*>(parent()), tr("Select PDF viewer executable"));
if (!path.isNull()) {
uiPdfViewerLocation->setText(path);
}
}
void CASettingsDialog::on_uiTypesetterDefault_toggled(bool checked)
{
if (checked) {
uiTypesetterLocation->setEnabled(false);
uiTypesetterBrowse->setEnabled(false);
} else {
uiTypesetterLocation->setEnabled(true);
uiTypesetterBrowse->setEnabled(true);
}
}
void CASettingsDialog::on_uiPdfViewerDefault_toggled(bool checked)
{
if (checked) {
uiPdfViewerLocation->setEnabled(false);
uiPdfViewerBrowse->setEnabled(false);
} else {
uiPdfViewerLocation->setEnabled(true);
uiPdfViewerBrowse->setEnabled(true);
}
}
| 16,369
|
C++
|
.cpp
| 338
| 43.905325
| 147
| 0.752801
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,396
|
transposeview.cpp
|
canorusmusic_canorus/src/ui/transposeview.cpp
|
/*!
Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "ui/transposeview.h"
#include "canorus.h"
#include "core/undo.h"
#include "scoreui/keysignatureui.h"
#include "ui/mainwin.h"
#include "core/transpose.h"
#include "layout/drawablekeysignature.h"
#include "layout/drawablemuselement.h"
#include "score/keysignature.h"
#include "score/sheet.h"
CATransposeView::CATransposeView(CAMainWin* p)
: QDockWidget(p)
{
setupUi(this);
setupCustomUi();
}
CATransposeView::~CATransposeView()
{
}
void CATransposeView::setupCustomUi()
{
// populate Key signatures
CAKeySignatureUI::populateComboBox(uiKeySigFrom);
CAKeySignatureUI::populateComboBox(uiKeySigTo);
CAKeySignatureUI::populateComboBoxDirection(uiKeySigDir);
// populate Intervals
for (int i = 1; i < 9; i++) {
// also triggers currentIndexChanged() and populates uiIntervalQuality
uiIntervalQuantity->addItem(CAInterval::quantityToReadable(i));
}
CAKeySignatureUI::populateComboBoxDirection(uiIntervalDir);
connect(uiByKeySig, SIGNAL(toggled(bool)), this, SLOT(updateUi(bool)));
connect(uiByInterval, SIGNAL(toggled(bool)), this, SLOT(updateUi(bool)));
connect(uiBySemitones, SIGNAL(toggled(bool)), this, SLOT(updateUi(bool)));
connect(uiReinterpretAccidentals, SIGNAL(toggled(bool)), this, SLOT(updateUi(bool)));
}
/*!
Sets the KeySig1 key signature to the key signature of the first selected note.
*/
void CATransposeView::show()
{
CAScoreView* v = static_cast<CAMainWin*>(parent())->currentScoreView();
if (v) {
CAKeySignature* k = nullptr;
if (v->selection().size()) {
for (int i = 0; !k && i < v->selection().size(); i++) {
if (v->selection()[i]->musElement() && v->selection()[i]->musElement()->isPlayable()) {
k = static_cast<CAPlayable*>(v->selection()[i]->musElement())->voice()->getKeySig(v->selection()[i]->musElement());
}
}
}
// the key signature wasn't found yet - find the first key sig in the score
for (int i = 0; !k && i < v->sheet()->staffList().size(); i++) {
if (v->sheet()->staffList()[i]->voiceList().size()) {
k = v->sheet()->staffList()[i]->voiceList()[0]->getKeySig(nullptr);
}
}
if (k) { // key signature is placed
int idx = uiKeySigFrom->findData(CADiatonicKey::diatonicKeyToString(k->diatonicKey()));
uiKeySigFrom->setCurrentIndex(idx);
uiKeySigTo->setCurrentIndex(idx);
} else { // set the key signature to empty (C-Major by default)
int idx = uiKeySigFrom->findData(CADiatonicKey::diatonicKeyToString(CADiatonicKey()));
uiKeySigFrom->setCurrentIndex(idx);
uiKeySigTo->setCurrentIndex(idx);
}
}
QDockWidget::show();
uiByInterval->toggle(); // select Transpose by interval by default
}
void CATransposeView::updateUi(bool)
{
uiKeySigFrom->setEnabled(uiByKeySig->isChecked());
uiTo->setEnabled(uiByKeySig->isChecked());
uiKeySigTo->setEnabled(uiByKeySig->isChecked());
uiKeySigDir->setEnabled(uiByKeySig->isChecked());
uiIntervalQuality->setEnabled(uiByInterval->isChecked());
uiIntervalQuantity->setEnabled(uiByInterval->isChecked());
uiIntervalDir->setEnabled(uiByInterval->isChecked());
uiSemitones->setEnabled(uiBySemitones->isChecked());
uiReinterpretType->setEnabled(uiReinterpretAccidentals->isChecked());
}
/*!
Updates the quality options when quantity is changed.
This function hides minor and major quality for prime, fourth, fifth and octave
and hides perfect quality for second, third, sixth and seventh.
*/
void CATransposeView::on_uiIntervalQuantity_currentIndexChanged(int newIndex)
{
uiIntervalQuality->clear();
switch (newIndex) {
case 0: // prime
case 3: // fourth
case 4: // fifth
case 7: { // octave
uiIntervalQuality->addItem(CAInterval::qualityToReadable(-2));
uiIntervalQuality->addItem(CAInterval::qualityToReadable(0));
uiIntervalQuality->addItem(CAInterval::qualityToReadable(2));
uiIntervalQuality->setCurrentIndex(1); // select Perfect
break;
}
default: // other intervals (no perfect)
uiIntervalQuality->addItem(CAInterval::qualityToReadable(-2));
uiIntervalQuality->addItem(CAInterval::qualityToReadable(-1));
uiIntervalQuality->addItem(CAInterval::qualityToReadable(1));
uiIntervalQuality->addItem(CAInterval::qualityToReadable(2));
uiIntervalQuality->setCurrentIndex(2); // select Perfect
break;
}
}
void CATransposeView::on_uiApply_clicked(QAbstractButton*)
{
if (dynamic_cast<CAMainWin*>(parent()) && static_cast<CAMainWin*>(parent())->currentScoreView()) {
CACanorus::undo()->createUndoCommand(static_cast<CAMainWin*>(parent())->document(), tr("transposition", "undo"));
CAScoreView* v = static_cast<CAMainWin*>(parent())->currentScoreView();
CATranspose t;
// get the music elements to transpose
if (v->selection().size()) {
for (int i = 0; i < v->selection().size(); i++) {
t.addMusElement(v->selection()[i]->musElement());
}
} else if (v->currentContext()) {
t.addContext(v->currentContext()->context());
} else {
t.addSheet(v->sheet());
}
// do the transpose dependent on the current transpose mode
if (uiByKeySig->isChecked()) {
t.transposeByKeySig(CADiatonicKey(uiKeySigFrom->currentData().toString()),
CADiatonicKey(uiKeySigTo->currentData().toString()),
uiKeySigDir->currentIndex() ? (-1) : 1);
} else if (uiByInterval->isChecked()) {
CAInterval i;
if (uiIntervalQuality->count() == 3) { // prime, fourth, fifth, octave
i = CAInterval((uiIntervalQuality->currentIndex() - 1) * 2,
(uiIntervalQuantity->currentIndex() + 1) * (uiIntervalDir->currentIndex() ? (-1) : 1));
} else { // second, third, sixth, seventh
i = CAInterval(qRound((uiIntervalQuality->currentIndex() - 1.5) * (4 / 3.0)), //simple formula to distribute 0..3 -> -2..2
(uiIntervalQuantity->currentIndex() + 1) * (uiIntervalDir->currentIndex() ? (-1) : 1));
}
t.transposeByInterval(i);
} else if (uiBySemitones->isChecked()) {
t.transposeBySemitones(uiSemitones->value());
} else if (uiReinterpretAccidentals->isChecked()) {
if (uiReinterpretType->currentIndex() == 0) {
// sharps to flats
t.reinterpretAccidentals(1);
} else if (uiReinterpretType->currentIndex() == 1) {
// flats to sharps
t.reinterpretAccidentals(-1);
} else if (uiReinterpretType->currentIndex() == 2) {
// invert
t.reinterpretAccidentals(0);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(static_cast<CAMainWin*>(parent())->document(), v->sheet());
}
}
| 7,373
|
C++
|
.cpp
| 164
| 37.347561
| 138
| 0.64787
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,397
|
mainwin.cpp
|
canorusmusic_canorus/src/ui/mainwin.cpp
|
/*!
Copyright (c) 2006-2022, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
//#include <Python.h> must be called before standard headers inclusion. See http://docs.python.org/api/includes.html
#ifdef USE_PYTHON
#include <Python.h>
#endif
#include <QCheckBox>
#include <QComboBox>
#include <QKeyEvent>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPoint>
#include <QSlider>
#include <QString>
#include <QTextStream>
#include <QThread>
#include <QToolBar>
#include <QWheelEvent>
#include <QXmlInputSource>
#include <QtGui>
#include <iostream>
#include <limits>
#include "ui/actionstorage.h"
#include "ui/jumptoview.h"
#include "ui/mainwin.h"
#include "ui/propertiesdialog.h"
#include "ui/settingsdialog.h"
#include "ui/transposeview.h"
#include "scoreui/keysignatureui.h"
#include "scorectl/keysignaturectl.h"
#include "control/helpctl.h"
#include "control/previewctl.h"
#include "control/printctl.h"
#include "control/resourcectl.h"
#include "interface/keybdinput.h"
#include "interface/mididevice.h"
#include "interface/playback.h"
#include "interface/pluginmanager.h"
#include "interface/rtmididevice.h"
#include "widgets/lcdnumber.h"
#include "widgets/menutoolbutton.h"
#include "widgets/midirecorderview.h"
#include "widgets/undotoolbutton.h"
#ifdef QT_WEBENGINEWIDGETS_LIB
#include "widgets/helpbrowser.h"
#endif
#include "widgets/pyconsole.h"
#include "widgets/scoreview.h"
#include "widgets/sourceview.h"
#include "widgets/view.h"
#include "widgets/viewcontainer.h"
#include "layout/drawablecontext.h"
#include "layout/drawablefiguredbassnumber.h"
#include "layout/drawablekeysignature.h"
#include "layout/drawablelyricscontext.h"
#include "layout/drawablemuselement.h"
#include "layout/drawablenote.h"
#include "layout/drawablestaff.h"
#include "layout/layoutengine.h"
#include "canorus.h"
#include "core/midirecorder.h"
#include "core/mimedata.h"
#include "core/muselementfactory.h"
#include "core/settings.h"
#include "core/undo.h"
#include "score/articulation.h"
#include "score/barline.h"
#include "score/bookmark.h"
#include "score/chordname.h"
#include "score/chordnamecontext.h"
#include "score/clef.h"
#include "score/dynamic.h"
#include "score/figuredbasscontext.h"
#include "score/figuredbassmark.h"
#include "score/fingering.h"
#include "score/functionmark.h"
#include "score/functionmarkcontext.h"
#include "score/instrumentchange.h"
#include "score/keysignature.h"
#include "score/lyricscontext.h"
#include "score/note.h"
#include "score/repeatmark.h"
#include "score/rest.h"
#include "score/ritardando.h"
#include "score/sheet.h"
#include "score/slur.h"
#include "score/staff.h"
#include "score/syllable.h"
#include "score/text.h"
#include "score/timesignature.h"
#include "score/voice.h"
#include "scripting/swigpython.h"
#include "scripting/swigruby.h"
#include "core/notechecker.h"
#include "export/canexport.h"
#include "export/canorusmlexport.h"
#include "export/export.h"
#include "export/lilypondexport.h"
#include "export/midiexport.h"
#include "export/musicxmlexport.h"
#include "export/pdfexport.h"
#include "export/svgexport.h"
#include "import/canimport.h"
#include "import/canorusmlimport.h"
#include "import/lilypondimport.h"
#include "import/midiimport.h"
#include "import/musicxmlimport.h"
#include "import/mxlimport.h"
/*!
\class CAMainWin
\brief Canorus main window
Class CAMainWin represents Canorus main window.
The core layout is generated using the Qt designer's ui/mainwin.ui file.
Other widgets (specific toolbars, Views, plugin menus) are generated manually in-code.
Canorus supports multiple main windows pointing to the same document or separated document.
Canorus uses multiple inheritance approach. See
http://doc.trolltech.com/4.2/designer-using-a-component.html#the-multiple-inheritance-approach
Class members having _ prefix are general private properties.
Private attributes with ui prefix are GUI-only widgets objects created in Qt designer or manually.
\sa CAView, CACanorus
*/
/*!
Default constructor.
Creates Canorus main window with parent \a oParent. Parent is usually null.
*/
CAMainWin::CAMainWin(QMainWindow* oParent)
: QMainWindow(oParent)
, _mode(NoDocumentMode)
, _mainWinProgressCtl(this)
, _playbackView(nullptr)
, _repaintTimer(nullptr)
, _playback(nullptr)
{
setAttribute(Qt::WA_DeleteOnClose);
_iNumAllowed = 1;
// Create the GUI (actions, toolbars, menus etc.)
createCustomActions();
setupUi(this); // initialize elements created by Qt Designer
actionStorage = new CAActionStorage(); // Shortcut System
setupCustomUi();
// Explicitly initialize this so it isn't true sometimes
setRebuildUILock(false);
// Initialize internal UI properties
uiLockScrollPlayback->setChecked(CACanorus::settings()->lockScrollPlayback());
// Create plugins menus and toolbars in this main window
CAPluginManager::enablePlugins(this);
// Connects MIDI IN callback function to a local slot. Not implemented yet.
connect(CACanorus::midiDevice(), SIGNAL(midiInEvent(QVector<unsigned char>)), this, SLOT(onMidiInEvent(QVector<unsigned char>)));
// Connect QTimer so it increases the local document edited time every second
restartTimeEditedTime();
connect(&_timeEditedTimer, SIGNAL(timeout()), this, SLOT(onTimeEditedTimerTimeout()));
_timeEditedTimer.start(1000);
// Setup the midi keyboad input processing object
_keybdInput = new CAKeybdInput(this);
_resourceView = new CAResourceView(nullptr, nullptr);
_resourceView->hide();
// Tools
_midiRecorderView = nullptr;
_transposeView = new CATransposeView(this);
addDockWidget(Qt::RightDockWidgetArea, _transposeView);
_transposeView->hide();
_jumpToView = new CAJumpToView(this);
_permanentStatusBar = statusBar();
setDocument(nullptr);
_poExp = nullptr;
CACanorus::addMainWin(this);
}
CAMainWin::~CAMainWin()
{
delete _musElementFactory;
if (document() && CACanorus::mainWinCount(document()) == 1) {
CACanorus::undo()->deleteUndoStack(document()); // delete undo stack when the last document deleted
delete document();
}
CACanorus::removeMainWin(this); // must be called *after* CACanorus::deleteUndoStack()
if (_playback)
delete _playback;
delete _poPrintCtl;
delete _poPrintPreviewCtl;
// clear UI
delete uiInsertToolBar; // also deletes content of the toolbars
delete uiInsertGroup;
delete uiVoiceToolBar;
delete uiPlayableToolBar;
delete uiTimeSigToolBar;
delete uiClefToolBar;
delete uiFBMToolBar;
delete uiFMToolBar;
delete uiDynamicToolBar;
delete uiInstrumentToolBar;
delete uiTempoToolBar;
delete uiFermataToolBar;
delete uiRepeatMarkToolBar;
delete _resourceView;
delete _transposeView;
if (_poExp)
delete _poExp;
if (_midiRecorderView)
delete _midiRecorderView;
if (!CACanorus::mainWinList().size()) // closing down
CACanorus::cleanUp();
}
void CAMainWin::createCustomActions()
{
// Toolbars
uiUndo = new CAUndoToolButton(QIcon("images:general/editundo.png"), CAUndoToolButton::Undo, this);
uiUndo->setObjectName("uiUndo");
uiRedo = new CAUndoToolButton(QIcon("images:general/editredo.png"), CAUndoToolButton::Redo, this);
uiRedo->setObjectName("uiRedo");
uiInsertToolBar = new QToolBar(tr("Insert ToolBar"), this);
uiContextType = new CAMenuToolButton(tr("Select Context"), 2, this);
uiContextType->setObjectName("uiContextType");
uiContextType->addButton(QIcon("images:document/staffnew.svg"), CAContext::Staff, tr("New Staff"));
uiContextType->addButton(QIcon("images:document/lyricscontextnew.svg"), CAContext::LyricsContext, tr("New Lyrics context"));
uiContextType->addButton(QIcon("images:document/chordnamecontextnew.svg"), CAContext::ChordNameContext, tr("New Chord Name context"));
uiContextType->addButton(QIcon("images:document/fbcontextnew.svg"), CAContext::FiguredBassContext, tr("New Figured Bass context"));
uiContextType->addButton(QIcon("images:document/fmcontextnew.svg"), CAContext::FunctionMarkContext, tr("New Function Mark context"));
uiSlurType = new CAMenuToolButton(tr("Select Slur Type"), 3, this);
uiSlurType->setObjectName("uiSlurType");
uiSlurType->addButton(QIcon("images:slur/tie.svg"), CASlur::TieType, tr("Tie"));
uiSlurType->addButton(QIcon("images:slur/slur.svg"), CASlur::SlurType, tr("Slur"));
uiSlurType->addButton(QIcon("images:slur/phrasingslur.svg"), CASlur::PhrasingSlurType, tr("Phrasing Slur"));
uiClefType = new CAMenuToolButton(tr("Select Clef"), 5, this);
uiClefType->setObjectName("uiClefType");
uiClefType->addButton(QIcon("images:clef/clefg.svg"), CAClef::Treble, tr("Treble Clef"));
uiClefType->addButton(QIcon("images:clef/clefg.svg"), CAClef::French, tr("French Clef"));
uiClefType->addButton(QIcon("images:clef/cleff.svg"), CAClef::Bass, tr("Bass Clef"));
uiClefType->addButton(QIcon("images:clef/cleff.svg"), CAClef::Varbaritone, tr("Varbaritone Clef"));
uiClefType->addButton(QIcon("images:clef/cleff.svg"), CAClef::Subbass, tr("Subbass Clef"));
uiClefType->addButton(QIcon("images:clef/clefc.svg"), CAClef::Soprano, tr("Soprano Clef"));
uiClefType->addButton(QIcon("images:clef/clefc.svg"), CAClef::Mezzosoprano, tr("Mezzosoprano Clef"));
uiClefType->addButton(QIcon("images:clef/clefc.svg"), CAClef::Alto, tr("Alto Clef"));
uiClefType->addButton(QIcon("images:clef/clefc.svg"), CAClef::Tenor, tr("Tenor Clef"));
uiClefType->addButton(QIcon("images:clef/clefc.svg"), CAClef::Baritone, tr("Baritone Clef"));
uiTimeSigType = new CAMenuToolButton(tr("Select Time Signature"), 3, this);
uiTimeSigType->setObjectName("uiTimeSigType");
uiTimeSigType->addButton(QIcon("images:timesig/tsc.svg"), 44);
uiTimeSigType->addButton(QIcon("images:timesig/tsab.svg"), 22);
uiTimeSigType->addButton(QIcon("images:timesig/ts34.svg"), 34);
uiTimeSigType->addButton(QIcon("images:timesig/ts24.svg"), 24);
uiTimeSigType->addButton(QIcon("images:timesig/ts38.svg"), 38);
uiTimeSigType->addButton(QIcon("images:timesig/ts68.svg"), 68);
uiTimeSigType->addButton(QIcon("images:timesig/tscustom.svg"), 0);
uiBarlineType = new CAMenuToolButton(tr("Select Barline"), 4, this);
uiBarlineType->setObjectName("uiBarlineType");
uiBarlineType->addButton(QIcon("images:barline/barlinesingle.svg"), CABarline::Single, tr("Single Barline"));
uiBarlineType->addButton(QIcon("images:barline/barlinedouble.svg"), CABarline::Double, tr("Double Barline"));
uiBarlineType->addButton(QIcon("images:barline/barlineend.svg"), CABarline::End, tr("End Barline"));
uiBarlineType->addButton(QIcon("images:barline/barlinedotted.svg"), CABarline::Dotted, tr("Dotted Barline"));
uiBarlineType->addButton(QIcon("images:barline/barlinerepeatopen.svg"), CABarline::RepeatOpen, tr("Repeat Open"));
uiBarlineType->addButton(QIcon("images:barline/barlinerepeatclose.svg"), CABarline::RepeatClose, tr("Repeat Closed"));
uiBarlineType->addButton(QIcon("images:barline/barlinerepeatcloseopen.svg"), CABarline::RepeatCloseOpen, tr("Repeat Closed-Open"));
uiMarkType = new CAMenuToolButton(tr("Select Mark"), 3, this);
uiMarkType->setObjectName("uiMarkType");
uiMarkType->addButton(QIcon("images:mark/tempo/tempo.svg"), CAMark::Tempo, tr("Tempo"));
uiMarkType->addButton(QIcon("images:mark/tempo/rit.svg"), CAMark::Ritardando, tr("Ritardando"));
uiMarkType->addButton(QIcon("images:mark/tempo/accel.svg"), CAMark::Ritardando * (-1), tr("Accellerando"));
uiMarkType->addButton(QIcon("images:mark/dynamic/mf.svg"), CAMark::Dynamic, tr("Dynamic"));
uiMarkType->addButton(QIcon("images:mark/dynamic/crescendo.svg"), CAMark::Crescendo, tr("Crescendo"));
uiMarkType->addButton(QIcon("images:mark/dynamic/decrescendo.svg"), CAMark::Crescendo * (-1), tr("Decrescendo"));
uiMarkType->addButton(QIcon("images:mark/fermata/normal.svg"), CAMark::Fermata, tr("Fermata"));
uiMarkType->addButton(QIcon("images:mark/text.svg"), CAMark::Text, tr("Arbitrary Text"));
uiMarkType->addButton(QIcon("images:mark/repeatmark/volta1.svg"), CAMark::RepeatMark, tr("Repeat Mark"));
uiMarkType->addButton(QIcon("images:mark/pedal.svg"), CAMark::Pedal, tr("Pedal Mark"));
uiMarkType->addButton(QIcon("images:mark/bookmark.svg"), CAMark::BookMark, tr("Bookmark"));
uiMarkType->addButton(QIcon("images:mark/rehersalmark.svg"), CAMark::RehersalMark, tr("Rehersal Mark"));
uiMarkType->addButton(QIcon("images:mark/fingering/fingering.svg"), CAMark::Fingering, tr("Fingering"));
uiMarkType->addButton(QIcon("images:mark/instrumentchange.svg"), CAMark::InstrumentChange, tr("Instrument Change"));
uiArticulationType = new CAMenuToolButton(tr("Articulation Mark"), 6, this);
uiArticulationType->setObjectName("uiArticulationType");
uiArticulationType->addButton(QIcon("images:mark/articulation/accent.svg"), CAArticulation::Accent, tr("Accent"));
uiArticulationType->addButton(QIcon("images:mark/articulation/marcato.svg"), CAArticulation::Marcato, tr("Marcato"));
uiArticulationType->addButton(QIcon("images:mark/articulation/staccatissimo.svg"), CAArticulation::Staccatissimo, tr("Stacatissimo"));
uiArticulationType->addButton(QIcon("images:mark/articulation/espressivo.svg"), CAArticulation::Espressivo, tr("Espressivo"));
uiArticulationType->addButton(QIcon("images:mark/articulation/staccato.svg"), CAArticulation::Staccato, tr("Staccato"));
uiArticulationType->addButton(QIcon("images:mark/articulation/tenuto.svg"), CAArticulation::Tenuto, tr("Tenuto"));
uiArticulationType->addButton(QIcon("images:mark/articulation/portato.svg"), CAArticulation::Portato, tr("Portato"));
uiArticulationType->addButton(QIcon("images:mark/articulation/breath.svg"), CAArticulation::Breath, tr("Breath"));
uiArticulationType->addButton(QIcon("images:mark/articulation/upbow.svg"), CAArticulation::UpBow, tr("UpBow"));
uiArticulationType->addButton(QIcon("images:mark/articulation/downbow.svg"), CAArticulation::DownBow, tr("DownBow"));
uiArticulationType->addButton(QIcon("images:mark/articulation/flageolet.svg"), CAArticulation::Flageolet, tr("Flageloet"));
uiArticulationType->addButton(QIcon("images:mark/articulation/open.svg"), CAArticulation::Open, tr("Open"));
uiArticulationType->addButton(QIcon("images:mark/articulation/stopped.svg"), CAArticulation::Stopped, tr("Stopped"));
uiArticulationType->addButton(QIcon("images:mark/articulation/turn.svg"), CAArticulation::Turn, tr("Turn"));
uiArticulationType->addButton(QIcon("images:mark/articulation/reverseturn.svg"), CAArticulation::ReverseTurn, tr("ReverseTurn"));
uiArticulationType->addButton(QIcon("images:mark/articulation/trill.svg"), CAArticulation::Trill, tr("Trill"));
uiArticulationType->addButton(QIcon("images:mark/articulation/prall.svg"), CAArticulation::Prall, tr("Prall"));
uiArticulationType->addButton(QIcon("images:mark/articulation/mordent.svg"), CAArticulation::Mordent, tr("Mordent"));
uiArticulationType->addButton(QIcon("images:mark/articulation/prallprall.svg"), CAArticulation::PrallPrall, tr("Prall-Prall"));
uiArticulationType->addButton(QIcon("images:mark/articulation/prallmordent.svg"), CAArticulation::PrallMordent, tr("Prall-Mordent"));
uiArticulationType->addButton(QIcon("images:mark/articulation/upprall.svg"), CAArticulation::UpPrall, tr("Up-Prall"));
uiArticulationType->addButton(QIcon("images:mark/articulation/downprall.svg"), CAArticulation::DownPrall, tr("Down-Prall"));
uiArticulationType->addButton(QIcon("images:mark/articulation/upmordent.svg"), CAArticulation::UpMordent, tr("Up-Mordent"));
uiArticulationType->addButton(QIcon("images:mark/articulation/downmordent.svg"), CAArticulation::DownMordent, tr("Down-Mordent"));
uiArticulationType->addButton(QIcon("images:mark/articulation/pralldown.svg"), CAArticulation::PrallDown, tr("Prall-Down"));
uiArticulationType->addButton(QIcon("images:mark/articulation/prallup.svg"), CAArticulation::PrallUp, tr("Prall-Up"));
uiArticulationType->addButton(QIcon("images:mark/articulation/lineprall.svg"), CAArticulation::LinePrall, tr("Line-Prall"));
uiSheetToolBar = new QToolBar(tr("Sheet ToolBar"), this);
uiSheetName = new QLineEdit(this);
uiSheetName->setObjectName("uiSheetName");
uiContextToolBar = new QToolBar(tr("Context ToolBar"), this);
uiContextName = new QLineEdit(this);
uiContextName->setObjectName("uiContextName");
uiContextName->setToolTip(tr("Context name"));
uiStanzaNumber = new QSpinBox(this);
uiStanzaNumber->setObjectName("uiStanzaNumber");
uiStanzaNumber->setToolTip(tr("Stanza number"));
uiStanzaNumber->setSpecialValueText(tr("none", "stanza number"));
uiStanzaNumber->hide();
uiAssociatedVoice = new QComboBox(this);
// Warning! disconnect and reconnect is also done in updateContextToolBar()!
uiAssociatedVoice->setObjectName("uiAssociatedVoice");
uiAssociatedVoice->setToolTip(tr("Associated voice"));
uiAssociatedVoice->hide();
uiVoiceToolBar = new QToolBar(tr("Voice ToolBar"), this);
uiVoiceNum = new CALCDNumber(0, 20, this, "Voice number");
uiVoiceNum->setObjectName("uiVoiceNum");
uiVoiceNum->setToolTip(tr("Current Voice number"));
uiVoiceInstrument = new QComboBox(this);
uiVoiceInstrument->setObjectName("uiVoiceInstrument");
uiVoiceInstrument->setToolTip(tr("Voice instrument"));
uiVoiceInstrument->addItems(CAMidiDevice::instrumentNames());
uiVoiceName = new QLineEdit(this);
uiVoiceName->setObjectName("uiVoiceName");
uiVoiceName->setToolTip(tr("Voice name"));
uiVoiceStemDirection = new CAMenuToolButton(tr("Select Voice Stem Direction"), 3, this);
uiVoiceStemDirection->setObjectName("uiVoiceStemDirection");
uiVoiceStemDirection->addButton(QIcon("images:playable/notestemneutral.svg"), CANote::StemNeutral, tr("Voice Stems Neutral"));
uiVoiceStemDirection->addButton(QIcon("images:playable/notestemup.svg"), CANote::StemUp, tr("Voice Stems Up"));
uiVoiceStemDirection->addButton(QIcon("images:playable/notestemdown.svg"), CANote::StemDown, tr("Voice Stems Down"));
uiPlayableToolBar = new QToolBar(tr("Playable ToolBar"), this);
uiPlayableLength = new CAMenuToolButton(tr("Select Length"), 3, this);
uiPlayableLength->setObjectName("uiPlayableLength");
uiPlayableLength->addButton(QIcon("images:playable/n0.svg"), CAPlayableLength::Breve, tr("Breve", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n1.svg"), CAPlayableLength::Whole, tr("Whole", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n2.svg"), CAPlayableLength::Half, tr("Half", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n4.svg"), CAPlayableLength::Quarter, tr("Quarter", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n8.svg"), CAPlayableLength::Eighth, tr("Eighth", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n16.svg"), CAPlayableLength::Sixteenth, tr("Sixteenth", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n32.svg"), CAPlayableLength::ThirtySecond, tr("ThirtySecond", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n64.svg"), CAPlayableLength::SixtyFourth, tr("SixtyFourth", "note"));
uiPlayableLength->addButton(QIcon("images:playable/n128.svg"), CAPlayableLength::HundredTwentyEighth, tr("HundredTwentyEighth", "note"));
uiNoteStemDirection = new CAMenuToolButton(tr("Select Note Stem Direction"), 4, this);
uiNoteStemDirection->setObjectName("uiNoteStemDirection");
uiNoteStemDirection->addButton(QIcon("images:playable/notestemneutral.svg"), CANote::StemNeutral, tr("Note Stem Neutral"));
uiNoteStemDirection->addButton(QIcon("images:playable/notestemup.svg"), CANote::StemUp, tr("Note Stem Up"));
uiNoteStemDirection->addButton(QIcon("images:playable/notestemdown.svg"), CANote::StemDown, tr("Note Stem Down"));
uiNoteStemDirection->addButton(QIcon("images:playable/notestemvoice.svg"), CANote::StemPreferred, tr("Note Stem Preferred"));
uiTupletType = new CAMenuToolButton(tr("Select Tuplet Type"), 2, this);
uiTupletType->setObjectName("uiTupletType");
uiTupletType->addButton(QIcon("images:tuplet/triplet.svg"), 0, tr("Triplet"));
uiTupletType->addButton(QIcon("images:tuplet/tuplet.svg"), 1, tr("Tuplet"));
uiTupletNumber = new QSpinBox(this);
uiTupletNumber->setObjectName("uiTupletNumber");
uiTupletNumber->setMinimum(1);
uiTupletNumber->setValue(3);
uiTupletNumber->setToolTip(tr("Number of notes"));
uiTupletInsteadOf = new QLabel(tr("instead of"), this);
uiTupletInsteadOf->setObjectName("uiTupletInsteadOf");
uiTupletActualNumber = new QSpinBox(this);
uiTupletActualNumber->setObjectName("uiTupletActualNumber");
uiTupletActualNumber->setMinimum(1);
uiTupletActualNumber->setValue(2);
uiTupletActualNumber->setToolTip(tr("Actual number of notes"));
uiTimeSigToolBar = new QToolBar(tr("Time Signature ToolBar"), this);
uiTimeSigBeats = new QSpinBox(this);
uiTimeSigBeats->setObjectName("uiTimeSigBeats");
uiTimeSigBeats->setMinimum(1);
uiTimeSigBeats->setValue(4);
uiTimeSigBeats->setToolTip(tr("Number of beats"));
uiTimeSigSlash = new QLabel("/", this);
uiTimeSigSlash->setObjectName("uiTimeSigSlash");
uiTimeSigBeat = new QSpinBox(this);
uiTimeSigBeat->setObjectName("uiTimeSigBeat");
uiTimeSigBeat->setMinimum(1);
uiTimeSigBeat->setValue(4);
uiTimeSigBeat->setToolTip(tr("Beat"));
uiClefToolBar = new QToolBar(tr("Clef ToolBar"), this);
oldUiClefOffsetValue = 0;
uiClefOffset = new QSpinBox(this);
uiClefOffset->setObjectName("uiClefOffset");
uiClefOffset->setMinimum(-22);
uiClefOffset->setMaximum(22);
uiClefOffset->setValue(0);
uiClefOffset->setToolTip(tr("Clef offset"));
uiFBMToolBar = new QToolBar(tr("Figured bass ToolBar"), this);
uiFBMNumber = new CAMenuToolButton(tr("Set/Unset Figured bass number"), 8, this);
uiFBMNumber->setObjectName("uiFBMNumber");
for (int i = 1; i <= 15; i++) {
uiFBMNumber->addButton(QIcon(QString("images:numbers/") + QString::number(i) + ".svg"), i, "");
}
uiFBMAccs = new CAMenuToolButton(tr("Set/Unset Figured bass accidentals"), 5, this);
uiFBMAccs->setObjectName("uiFBMAccs");
uiFBMAccs->addButton(QIcon("images:accidental/doubleflat.svg"), 0, tr("Double flat"));
uiFBMAccs->addButton(QIcon("images:accidental/flat.svg"), 1, tr("Flat"));
uiFBMAccs->addButton(QIcon("images:accidental/neutral.svg"), 2, tr("Neutral"));
uiFBMAccs->addButton(QIcon("images:accidental/sharp.svg"), 3, tr("Sharp"));
uiFBMAccs->addButton(QIcon("images:accidental/doublesharp.svg"), 4, tr("Double sharp"));
uiFMToolBar = new QToolBar(tr("Function mark ToolBar"), this);
uiFMFunction = new CAMenuToolButton(tr("Select Function Name"), 8, this);
uiFMFunction->setObjectName("uiFMFunction");
uiFMFunction->addButton(QIcon("images:functionmark/fmt.svg"), CAFunctionMark::T, tr("Tonic"));
uiFMFunction->addButton(QIcon("images:functionmark/fms.svg"), CAFunctionMark::S, tr("Subdominant"));
uiFMFunction->addButton(QIcon("images:functionmark/fmd.svg"), CAFunctionMark::D, tr("Dominant"));
uiFMFunction->addButton(QIcon("images:functionmark/fmii.svg"), CAFunctionMark::II, tr("II"));
uiFMFunction->addButton(QIcon("images:functionmark/fmiii.svg"), CAFunctionMark::III, tr("III"));
uiFMFunction->addButton(QIcon("images:functionmark/fmvi.svg"), CAFunctionMark::VI, tr("VI"));
uiFMFunction->addButton(QIcon("images:functionmark/fmvii.svg"), CAFunctionMark::VII, tr("VII"));
uiFMFunction->addButton(QIcon("images:functionmark/fmk.svg"), CAFunctionMark::K, tr("Cadenze"));
uiFMFunction->addButton(QIcon("images:functionmark/fmot.svg"), CAFunctionMark::T * (-1), tr("minor Tonic"));
uiFMFunction->addButton(QIcon("images:functionmark/fmos.svg"), CAFunctionMark::S * (-1), tr("minor Subdominant"));
uiFMFunction->addButton(QIcon("images:functionmark/fmn.svg"), CAFunctionMark::N, tr("Napolitan"));
uiFMFunction->addButton(QIcon("images:functionmark/fmf.svg"), CAFunctionMark::F, tr("Phrygian"));
uiFMFunction->addButton(QIcon("images:functionmark/fml.svg"), CAFunctionMark::L, tr("Lydian"));
uiFMFunction->addButton(QIcon("images:functionmark/fmiv.svg"), CAFunctionMark::IV, tr("IV"));
uiFMFunction->addButton(QIcon("images:functionmark/fmv.svg"), CAFunctionMark::V, tr("V"));
uiFMFunction->addButton(QIcon("images:general/none.svg"), CAFunctionMark::Undefined, tr("None"));
uiFMChordArea = new CAMenuToolButton(tr("Select Chord Area"), 3, this);
uiFMChordArea->setObjectName("uiFMChordArea");
uiFMChordArea->addButton(QIcon("images:functionmark/fmpt.svg"), CAFunctionMark::T, tr("Tonic"));
uiFMChordArea->addButton(QIcon("images:functionmark/fmps.svg"), CAFunctionMark::S, tr("Subdominant"));
uiFMChordArea->addButton(QIcon("images:functionmark/fmpd.svg"), CAFunctionMark::D, tr("Dominant"));
uiFMChordArea->addButton(QIcon("images:functionmark/fmpot.svg"), CAFunctionMark::T * (-1), tr("minor Tonic"));
uiFMChordArea->addButton(QIcon("images:functionmark/fmpos.svg"), CAFunctionMark::S * (-1), tr("minor Subdominant"));
uiFMChordArea->addButton(QIcon("images:general/none.svg"), CAFunctionMark::Undefined, tr("None"));
uiFMTonicDegree = new CAMenuToolButton(tr("Select Tonic Degree"), 5, this);
uiFMTonicDegree->setObjectName("uiFMTonicDegree");
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmt.svg"), CAFunctionMark::T, tr("Tonic"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmot.svg"), CAFunctionMark::T * (-1), tr("minor Tonic"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fms.svg"), CAFunctionMark::S, tr("Subdominant"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmos.svg"), CAFunctionMark::S * (-1), tr("minor Subdominant"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmd.svg"), CAFunctionMark::D, tr("Dominant"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmii.svg"), CAFunctionMark::II, tr("II"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmiii.svg"), CAFunctionMark::III, tr("III"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmvi.svg"), CAFunctionMark::VI, tr("VI"));
uiFMTonicDegree->addButton(QIcon("images:functionmark/fmvii.svg"), CAFunctionMark::VII, tr("VII"));
uiFMKeySig = new QComboBox(this);
uiFMKeySig->setObjectName("uiFMKeySig");
CAKeySignatureUI::populateComboBox(uiFMKeySig);
uiDynamicToolBar = new QToolBar(tr("Dynamic marks ToolBar"), this);
uiDynamicText = new CAMenuToolButton(tr("Select Dynamic"), 5, this);
uiDynamicText->setObjectName("uiDynamicText");
uiDynamicText->addButton(QIcon("images:mark/dynamic/p.svg"), CADynamic::p, tr("Piano", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/pp.svg"), CADynamic::pp, tr("Pianissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/ppp.svg"), CADynamic::ppp, tr("Pianissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/pppp.svg"), CADynamic::pppp, tr("Pianissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/ppppp.svg"), CADynamic::ppppp, tr("Pianissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/f.svg"), CADynamic::f, tr("Forte", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/ff.svg"), CADynamic::ff, tr("Fortissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/fff.svg"), CADynamic::fff, tr("Fortissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/ffff.svg"), CADynamic::ffff, tr("Fortissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/fffff.svg"), CADynamic::fffff, tr("Fortissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/mf.svg"), CADynamic::mf, tr("Mezzo Forte", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/mp.svg"), CADynamic::mp, tr("Mezzo Piano", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/fp.svg"), CADynamic::fp, tr("Forte Piano", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/sf.svg"), CADynamic::sf, tr("Sforzando Forte", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/sp.svg"), CADynamic::sp, tr("Sforzando Piano", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/sfz.svg"), CADynamic::sfz, tr("Sforzando", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/rfz.svg"), CADynamic::rfz, tr("Rinforzando", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/spp.svg"), CADynamic::spp, tr("Sforzando Pianissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:mark/dynamic/sff.svg"), CADynamic::sff, tr("Sforzando Fortissimo", "dynamics"));
uiDynamicText->addButton(QIcon("images:general/custom.svg"), CADynamic::Custom, tr("Custom", "dynamics"));
uiDynamicVolume = new QSpinBox(this);
uiDynamicVolume->setObjectName("uiDynamicVolume");
uiDynamicVolume->setToolTip(tr("Playback Volume"));
uiDynamicVolume->setMinimum(0);
uiDynamicVolume->setMaximum(100);
uiDynamicVolume->setSuffix(" %");
uiDynamicCustomText = new QLineEdit(this);
uiDynamicCustomText->setObjectName("uiDynamicCustomText");
uiDynamicCustomText->setToolTip(tr("Dynamic mark text"));
uiInstrumentToolBar = new QToolBar(tr("Instrument ToolBar"), this);
uiInstrumentChange = new QComboBox(this);
uiInstrumentChange->setObjectName("uiInstrumentChange");
uiInstrumentChange->setToolTip(tr("Instrument Change"));
uiInstrumentChange->addItems(CAMidiDevice::instrumentNames());
uiTempoToolBar = new QToolBar(tr("Tempo ToolBar"), this);
uiTempoBeat = new CAMenuToolButton(tr("Select Beat"), 3, this);
uiTempoBeat->setObjectName("uiTempoBeat");
uiTempoBeat->addButton(QIcon("images:playable/n4.svg"), CAPlayableLength::Quarter, tr("Quarter", "note"));
uiTempoBeat->addButton(QIcon("images:playable/n2.svg"), CAPlayableLength::Half, tr("Half", "note"));
uiTempoBeat->addButton(QIcon("images:playable/n8.svg"), CAPlayableLength::Eighth, tr("Eighth", "note"));
uiTempoBeat->addButton(QIcon("images:playable/n4d.svg"), CAPlayableLength::Quarter * (-1), tr("Dotted Quarter", "note"));
uiTempoBeat->addButton(QIcon("images:playable/n2d.svg"), CAPlayableLength::Half * (-1), tr("Dotted Half", "note"));
uiTempoBeat->addButton(QIcon("images:playable/n8d.svg"), CAPlayableLength::Eighth * (-1), tr("Dotted Eighth", "note"));
uiTempoEquals = new QLabel("=", this);
uiTempoEquals->setObjectName("uiTempoEquals");
uiTempoBpm = new QLineEdit(this);
uiTempoBpm->setObjectName("uiTempoBpm");
uiTempoBpm->setToolTip(tr("Beats per minute", "tempo"));
uiFermataToolBar = new QToolBar(tr("Fermata ToolBar"), this);
uiFermataType = new CAMenuToolButton(tr("Fermata Type"), 4, this);
uiFermataType->setObjectName("uiFermataType");
uiFermataType->addButton(QIcon("images:mark/fermata/short.svg"), CAFermata::ShortFermata, tr("Short", "fermata"));
uiFermataType->addButton(QIcon("images:mark/fermata/normal.svg"), CAFermata::NormalFermata, tr("Normal", "fermata"));
uiFermataType->addButton(QIcon("images:mark/fermata/long.svg"), CAFermata::LongFermata, tr("Long", "fermata"));
uiFermataType->addButton(QIcon("images:mark/fermata/verylong.svg"), CAFermata::VeryLongFermata, tr("Very Long", "fermata"));
uiRepeatMarkToolBar = new QToolBar(tr("Repeat Mark ToolBar"), this);
uiRepeatMarkType = new CAMenuToolButton(tr("Repeat Mark Type"), 3, this);
uiRepeatMarkType->setObjectName("uiRepeatMarkType");
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/volta1.svg"), -2, tr("Volta 1st", "repeat mark")); // -1 can't be used?!
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/volta2.svg"), -3, tr("Volta 2nd", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/volta3.svg"), -4, tr("Volta 3rd", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/segno.svg"), CARepeatMark::Segno, tr("Segno", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/coda.svg"), CARepeatMark::Coda, tr("Coda", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/varcoda.svg"), CARepeatMark::VarCoda, tr("VarCoda", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/dalsegno.svg"), CARepeatMark::DalSegno, tr("Dal Segno", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/dalcoda.svg"), CARepeatMark::DalCoda, tr("Dal Coda", "repeat mark"));
uiRepeatMarkType->addButton(QIcon("images:mark/repeatmark/dalvarcoda.svg"), CARepeatMark::DalVarCoda, tr("Dal VarCoda", "repeat mark"));
uiFingeringToolBar = new QToolBar(tr("Fingering ToolBar"), this);
uiFinger = new CAMenuToolButton(tr("Finger"), 5, this);
uiFinger->setObjectName("uiFinger");
uiFinger->addButton(QIcon("images:mark/fingering/1.svg"), CAFingering::First, tr("First", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/2.svg"), CAFingering::Second, tr("Second", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/3.svg"), CAFingering::Third, tr("Third", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/4.svg"), CAFingering::Fourth, tr("Fourth", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/5.svg"), CAFingering::Fifth, tr("Fifth", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/0.svg"), CAFingering::Thumb, tr("Thumb", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/lheel.svg"), CAFingering::LHeel, tr("Left Heel", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/rheel.svg"), CAFingering::RHeel, tr("Right Heel", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/ltoe.svg"), CAFingering::LToe, tr("Left Toe", "fingering"));
uiFinger->addButton(QIcon("images:mark/fingering/rtoe.svg"), CAFingering::RToe, tr("Right Toe", "fingering"));
uiFingeringOriginal = new QCheckBox(tr("Original"), this);
uiFingeringOriginal->setObjectName("uiFingeringOriginal");
uiFingeringOriginal->setToolTip(tr("Is the fingering original by a composer (usually written italic)", "fingering original checkbox"));
// User's guide and other Help
uiHelpDock = new QDockWidget(tr("Help"), this);
uiHelpDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
uiHelpDock->setMaximumWidth(400);
#ifdef QT_WEBENGINEWIDGETS_LIB
uiHelpWidget = new CAHelpBrowser(uiHelpDock);
uiHelpDock->setWidget(uiHelpWidget);
#endif
#ifdef USE_PYTHON
uiPyConsoleDock = new QDockWidget(tr("Canorus console"), this);
uiPyConsoleDock->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
pyConsole = new CAPyConsole(document(), uiPyConsoleDock);
pyConsoleIface = new CAPyConsoleInterface(pyConsole);
uiPyConsoleDock->setWidget(pyConsole);
#endif
}
/*!
Creates more complex widgets and layouts that cannot be created using Qt Designer (like adding
custom toolbars to main window, button boxes etc.).
*/
void CAMainWin::setupCustomUi()
{
_musElementFactory = new CAMusElementFactory();
_poPrintPreviewCtl = new CAPreviewCtl(this);
connect(uiPrintPreview, SIGNAL(triggered()), _poPrintPreviewCtl, SLOT(on_uiPrintPreview_triggered()));
_poPrintCtl = new CAPrintCtl(this);
//uiPrint->setEnabled( false );
// Standard Toolbar
uiUndo->setDefaultAction(uiStandardToolBar->insertWidget(uiCut, uiUndo));
uiUndo->defaultAction()->setText(tr("Undo"));
uiUndo->defaultAction()->setShortcut(QApplication::translate("uiMainWindow", "Ctrl+Z", nullptr /*, QApplication::UnicodeUTF8*/));
uiMenuEdit->insertAction(uiCut, uiUndo->defaultAction());
QList<QKeySequence> redoShortcuts;
redoShortcuts << QApplication::translate("uiMainWindow", "Ctrl+Y", nullptr /*, QApplication::UnicodeUTF8*/);
redoShortcuts << QApplication::translate("uiMainWindow", "Ctrl+Shift+Z", nullptr /*, QApplication::UnicodeUTF8*/);
uiRedo->setDefaultAction(uiStandardToolBar->insertWidget(uiCut, uiRedo));
uiRedo->defaultAction()->setText(tr("Redo"));
uiRedo->defaultAction()->setShortcuts(redoShortcuts);
uiMenuEdit->insertAction(uiCut, uiRedo->defaultAction());
// Hide the specialized pre-created toolbars in Qt designer.
/// \todo When Qt Designer have support for setting the visibility property, do this in Qt Designer already! -Matevz
uiPrintToolBar->hide();
uiFileToolBar->hide();
uiStandardToolBar->setMinimumHeight(48); // Hack to prevent score view shifting when there is QTextEdit in the top toolbar or not.
uiStandardToolBar->updateGeometry();
// Insert Toolbar
uiInsertToolBar->addAction(uiEditMode);
uiInsertToolBar->addSeparator();
uiContextType->setDefaultAction(uiInsertToolBar->addWidget(uiContextType));
uiContextType->defaultAction()->setToolTip(tr("Insert context"));
uiContextType->setCurrentId(CAContext::Staff);
connect(uiNewContext, SIGNAL(triggered()), uiContextType, SLOT(click()));
uiInsertToolBar->addSeparator();
uiInsertToolBar->addAction(uiInsertPlayable);
uiSlurType->setDefaultAction(uiInsertToolBar->addWidget(uiSlurType));
uiSlurType->defaultAction()->setToolTip(tr("Insert slur"));
uiSlurType->setCurrentId(CASlur::TieType);
uiSlurType->defaultAction()->setCheckable(false);
uiClefType->setDefaultAction(uiInsertToolBar->addWidget(uiClefType));
uiClefType->defaultAction()->setToolTip(tr("Insert clef"));
uiClefType->setCurrentId(CAClef::Treble);
connect(uiInsertClef, SIGNAL(triggered()), uiClefType, SLOT(click()));
uiInsertToolBar->addAction(uiInsertKeySig);
uiTimeSigType->setDefaultAction(uiInsertToolBar->addWidget(uiTimeSigType));
uiTimeSigType->defaultAction()->setToolTip(tr("Insert time signature"));
uiTimeSigType->setCurrentId(44);
connect(uiInsertTimeSig, SIGNAL(triggered()), uiTimeSigType, SLOT(click()));
uiBarlineType->setDefaultAction(uiInsertToolBar->addWidget(uiBarlineType));
uiBarlineType->defaultAction()->setToolTip(tr("Insert barline"));
uiBarlineType->setCurrentId(CABarline::End);
connect(uiInsertBarline, SIGNAL(triggered()), uiBarlineType, SLOT(click()));
uiMarkType->setDefaultAction(uiInsertToolBar->addWidget(uiMarkType));
uiMarkType->defaultAction()->setToolTip(tr("Insert mark"));
uiMarkType->setCurrentId(CAMark::Dynamic);
connect(uiInsertMark, SIGNAL(triggered()), uiMarkType, SLOT(click()));
uiArticulationType->setDefaultAction(uiInsertToolBar->addWidget(uiArticulationType));
uiArticulationType->defaultAction()->setToolTip(tr("Insert articulation mark"));
uiArticulationType->setCurrentId(CAArticulation::Accent);
connect(uiInsertArticulation, SIGNAL(triggered()), uiArticulationType, SLOT(click()));
uiInsertToolBar->addAction(uiInsertSyllable);
uiInsertToolBar->addAction(uiInsertFBM);
uiInsertToolBar->addAction(uiInsertFM);
uiInsertToolBar->addAction(uiInsertChordName);
if (qApp->isRightToLeft())
addToolBar(Qt::RightToolBarArea, uiInsertToolBar);
else
addToolBar(Qt::LeftToolBarArea, uiInsertToolBar);
// Sheet Toolbar
uiSheetToolBar->addAction(uiNewSheet);
uiSheetToolBar->addWidget(uiSheetName);
uiSheetToolBar->addAction(uiRemoveSheet);
uiSheetToolBar->addAction(uiSheetProperties);
addToolBar(Qt::TopToolBarArea, uiSheetToolBar);
// Context Toolbar
uiContextToolBar->addWidget(uiContextName);
uiStanzaNumberAction = uiContextToolBar->addWidget(uiStanzaNumber);
uiAssociatedVoiceAction = uiContextToolBar->addWidget(uiAssociatedVoice);
uiContextToolBar->addAction(uiRemoveContext);
uiContextToolBar->addAction(uiContextProperties);
addToolBar(Qt::TopToolBarArea, uiContextToolBar);
// Playable Toolbar
uiPlayableLength->setDefaultAction(uiPlayableToolBar->addWidget(uiPlayableLength));
uiPlayableLength->defaultAction()->setToolTip(tr("Playable length"));
uiPlayableLength->defaultAction()->setCheckable(false);
uiPlayableLength->setCurrentId(CAPlayableLength::Quarter);
uiPlayableToolBar->addAction(uiAccsVisible);
uiTupletType->setDefaultAction(uiPlayableToolBar->addWidget(uiTupletType));
uiTupletType->defaultAction()->setToolTip(tr("Insert tuplet"));
uiTupletType->setCurrentId(0);
uiTupletNumberAction = uiPlayableToolBar->addWidget(uiTupletNumber);
uiTupletInsteadOfAction = uiPlayableToolBar->addWidget(uiTupletInsteadOf);
uiTupletActualNumberAction = uiPlayableToolBar->addWidget(uiTupletActualNumber);
uiNoteStemDirection->setDefaultAction(uiPlayableToolBar->addWidget(uiNoteStemDirection));
uiNoteStemDirection->defaultAction()->setToolTip(tr("Note stem direction"));
uiNoteStemDirection->defaultAction()->setCheckable(false);
uiNoteStemDirection->setCurrentId(CANote::StemPreferred);
uiPlayableToolBar->addAction(uiHiddenRest);
addToolBar(Qt::TopToolBarArea, uiPlayableToolBar);
// Clef Toolbar
uiClefToolBar->addWidget(uiClefOffset);
addToolBar(Qt::TopToolBarArea, uiClefToolBar);
// TimeSig Toolbar
uiTimeSigToolBar->addWidget(uiTimeSigBeats);
uiTimeSigToolBar->addWidget(uiTimeSigSlash);
uiTimeSigToolBar->addWidget(uiTimeSigBeat);
addToolBar(Qt::TopToolBarArea, uiTimeSigToolBar);
// Voice Toolbar
uiVoiceToolBar->addAction(uiNewVoice);
uiVoiceToolBar->addWidget(uiVoiceNum);
uiVoiceToolBar->addWidget(uiVoiceName);
uiVoiceToolBar->addWidget(uiVoiceInstrument);
uiVoiceToolBar->addAction(uiRemoveVoice);
uiVoiceStemDirection->setDefaultAction(uiVoiceToolBar->addWidget(uiVoiceStemDirection));
uiVoiceStemDirection->defaultAction()->setToolTip(tr("Voice stem direction"));
uiVoiceStemDirection->defaultAction()->setCheckable(false);
uiVoiceToolBar->addAction(uiVoiceProperties);
addToolBar(Qt::TopToolBarArea, uiVoiceToolBar);
// Figured bass Toolbar
uiFBMNumber->setDefaultAction(uiFBMToolBar->addWidget(uiFBMNumber));
uiFBMNumber->defaultAction()->setToolTip(tr("Figured bass number"));
uiFBMNumber->setCurrentId(6);
uiFBMNumber->defaultAction()->setCheckable(true);
uiFBMNumber->defaultAction()->setChecked(true);
uiFBMAccs->setDefaultAction(uiFBMToolBar->addWidget(uiFBMAccs));
uiFBMAccs->defaultAction()->setToolTip(tr("Figured bass accidentals"));
uiFBMAccs->setCurrentId(2);
uiFBMAccs->defaultAction()->setCheckable(true);
uiFBMAccs->defaultAction()->setChecked(false);
addToolBar(Qt::TopToolBarArea, uiFBMToolBar);
// Function mark Toolbar
uiFMFunction->setDefaultAction(uiFMToolBar->addWidget(uiFMFunction));
uiFMFunction->defaultAction()->setToolTip(tr("Function mark"));
uiFMFunction->setCurrentId(CAFunctionMark::T);
uiFMFunction->defaultAction()->setCheckable(false);
uiFMChordArea->setDefaultAction(uiFMToolBar->addWidget(uiFMChordArea));
uiFMChordArea->defaultAction()->setToolTip(tr("Function mark chord area"));
uiFMChordArea->setCurrentId(CAFunctionMark::T);
uiFMChordArea->defaultAction()->setCheckable(false);
uiFMTonicDegree->setDefaultAction(uiFMToolBar->addWidget(uiFMTonicDegree));
uiFMTonicDegree->defaultAction()->setCheckable(false);
uiFMTonicDegree->defaultAction()->setToolTip(tr("Function mark tonic degree"));
uiFMTonicDegree->setCurrentId(CAFunctionMark::T);
uiFMToolBar->addAction(uiFMEllipse);
uiFMToolBar->addWidget(uiFMKeySig);
addToolBar(Qt::TopToolBarArea, uiFMToolBar);
// Dynamic marks toolbar
uiDynamicText->setDefaultAction(uiDynamicToolBar->addWidget(uiDynamicText));
uiDynamicText->defaultAction()->setToolTip(tr("Predefined dynamic mark"));
uiDynamicText->setCurrentId(CADynamic::mf);
uiDynamicText->defaultAction()->setCheckable(false);
uiDynamicToolBar->addWidget(uiDynamicVolume);
uiDynamicToolBar->addWidget(uiDynamicCustomText);
addToolBar(Qt::TopToolBarArea, uiDynamicToolBar);
// Instrument tool bar
uiInstrumentToolBar->addWidget(uiInstrumentChange);
addToolBar(Qt::TopToolBarArea, uiInstrumentToolBar);
// Tempo tool bar
uiTempoBeat->setDefaultAction(uiTempoToolBar->addWidget(uiTempoBeat));
uiTempoBeat->defaultAction()->setCheckable(false);
uiTempoBeat->defaultAction()->setToolTip(tr("Beat", "tempo"));
uiTempoToolBar->addWidget(uiTempoEquals);
uiTempoToolBar->addWidget(uiTempoBpm);
addToolBar(Qt::TopToolBarArea, uiTempoToolBar);
// Fermata tool bar
uiFermataType->setDefaultAction(uiFermataToolBar->addWidget(uiFermataType));
uiFermataType->defaultAction()->setCheckable(false);
uiFermataType->defaultAction()->setToolTip(tr("Fermata Type", "fermata"));
addToolBar(Qt::TopToolBarArea, uiFermataToolBar);
// Repeat Mark tool bar
uiRepeatMarkType->setDefaultAction(uiRepeatMarkToolBar->addWidget(uiRepeatMarkType));
uiRepeatMarkType->defaultAction()->setCheckable(false);
uiRepeatMarkType->defaultAction()->setToolTip(tr("Repeat Mark Type", "repeat mark"));
addToolBar(Qt::TopToolBarArea, uiRepeatMarkToolBar);
// Fingering tool bar
uiFinger->setDefaultAction(uiFingeringToolBar->addWidget(uiFinger));
uiFinger->defaultAction()->setCheckable(false);
uiFinger->defaultAction()->setToolTip(tr("Finger", "fingering"));
uiFingeringOriginal->setChecked(false);
uiFingeringToolBar->addWidget(uiFingeringOriginal);
addToolBar(Qt::TopToolBarArea, uiFingeringToolBar);
#ifdef USE_PYTHON
// Python console dock widget
addDockWidget(Qt::BottomDockWidgetArea, uiPyConsoleDock);
#endif
// View
uiShowRuler->setChecked(CACanorus::settings()->showRuler());
// Help
addDockWidget((qApp->isLeftToRight()) ? Qt::RightDockWidgetArea : Qt::LeftDockWidgetArea, uiHelpDock);
uiHelpDock->hide();
// Score UI Interface
_poKeySignatureUI = new CAKeySignatureUI(this, createModeHash()); // Control object is created here!
connect(uiFMKeySig, SIGNAL(activated(int)), &_poKeySignatureUI->ctl(), SLOT(on_uiKeySig_activated(int)));
// Mutual exclusive groups
uiInsertGroup = new QActionGroup(this);
uiInsertGroup->addAction(uiEditMode);
uiInsertGroup->addAction(uiNewContext);
uiInsertGroup->addAction(uiContextType->defaultAction());
uiInsertGroup->addAction(uiInsertPlayable);
uiInsertGroup->addAction(uiSlurType->defaultAction());
uiInsertGroup->addAction(uiInsertClef);
uiInsertGroup->addAction(uiClefType->defaultAction());
uiInsertGroup->addAction(uiInsertTimeSig);
uiInsertGroup->addAction(uiTimeSigType->defaultAction());
uiInsertGroup->addAction(uiInsertKeySig);
uiInsertGroup->addAction(uiInsertBarline);
uiInsertGroup->addAction(uiBarlineType->defaultAction());
uiInsertGroup->addAction(uiMarkType->defaultAction());
uiInsertGroup->addAction(uiInsertMark);
uiInsertGroup->addAction(uiArticulationType->defaultAction());
uiInsertGroup->addAction(uiInsertArticulation);
uiInsertGroup->addAction(uiInsertSyllable);
uiInsertGroup->addAction(uiInsertFBM);
uiInsertGroup->addAction(uiInsertFM);
uiInsertGroup->addAction(uiInsertChordName);
uiInsertGroup->setExclusive(true);
uiInsertToolBar->hide();
uiSheetToolBar->hide();
uiContextToolBar->hide();
uiPlayableToolBar->hide();
uiTimeSigToolBar->hide();
uiClefToolBar->hide();
uiFBMToolBar->hide();
uiFMToolBar->hide();
uiDynamicToolBar->hide();
uiInstrumentToolBar->hide();
uiTempoToolBar->hide();
uiFermataToolBar->hide();
uiRepeatMarkToolBar->hide();
uiFingeringToolBar->hide();
actionStorage->storeActionsFromMainWindow(*this);
actionStorage->addWinActions();
}
void CAMainWin::newDocument()
{
stopPlayback();
if (!handleUnsavedChanges()) {
return;
}
// clear GUI before clearing the data part!
clearUI();
// clear the data part
if (document() && (CACanorus::mainWinCount(document()) == 1)) {
CACanorus::undo()->deleteUndoStack(document());
delete document();
}
setDocument(new CADocument());
setMode(EditMode);
uiCloseDocument->setEnabled(true);
CACanorus::undo()->createUndoStack(document());
restartTimeEditedTime();
#ifdef USE_PYTHON
QList<PyObject*> argsPython;
PyEval_RestoreThread(CASwigPython::mainThreadState);
argsPython << CASwigPython::toPythonObject(document(), CASwigPython::Document);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
CASwigPython::callFunction(QFileInfo("scripts:newdocument.py").absoluteFilePath(), "newDefaultDocument", argsPython);
#else
// fallback: add basic sheet with two staffs
CASheet* sheet1 = document()->addSheet();
CAStaff* staff1 = sheet1->addStaff();
staff1->addVoice();
staff1->voiceList()[0]->setStemDirection(CANote::StemUp);
staff1->voiceList()[1]->setStemDirection(CANote::StemDown);
staff1->voiceList()[0]->append(new CAClef(CAClef::Treble, staff1, 0));
staff1->voiceList()[0]->append(new CATimeSignature(4, 4, staff1, 0));
CAStaff* staff2 = sheet1->addStaff();
staff2->addVoice();
staff2->voiceList()[0]->setStemDirection(CANote::StemUp);
staff2->voiceList()[1]->setStemDirection(CANote::StemDown);
staff2->voiceList()[0]->append(new CAClef(CAClef::Bass, staff2, 0));
staff2->voiceList()[0]->append(new CATimeSignature(4, 4, staff2, 0));
staff1->synchronizeVoices();
staff2->synchronizeVoices();
#endif
// call local rebuild only because no other main windows share the new document
rebuildUI();
// select the first context automatically
if (document()->sheetList().size() && document()->sheetList()[0]->contextList().size()) {
currentScoreView()->selectContext(document()->sheetList()[0]->contextList()[0]);
}
setMode(EditMode);
}
/*!
Checks for any unsaved modifications and returns True, to continue with closing the current document.
Returns False only, if user clicks Cancel button.
This method looks at CADocument::_modified property.
The property is changed in undo/redo code.
*/
bool CAMainWin::handleUnsavedChanges()
{
if (document()) {
if (document()->isModified()) {
QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Unsaved changes"), tr("Document \"%1\" was modified. Do you want to save the changes?").arg(document()->title().isEmpty() ? tr("Untitled") : document()->title()), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes);
if (ret == QMessageBox::Yes) {
return on_uiSaveDocument_triggered();
} else if (ret == QMessageBox::No) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return true;
}
}
/*!
This adds a tab to tabWidget and creates a single score View of the sheet.
It does not add the sheet to the document.
*/
void CAMainWin::addSheet(CASheet* s)
{
CAScoreView* v = new CAScoreView(s, nullptr);
initView(v);
CAViewContainer* vpc = new CAViewContainer(nullptr);
vpc->addView(v);
_viewContainerList << vpc;
_sheetMap[vpc] = s;
uiTabWidget->addTab(vpc, s->name());
uiTabWidget->setCurrentIndex(uiTabWidget->count() - 1);
setCurrentViewContainer(vpc);
updateToolBars();
}
/*!
Deletes all Views (and their drawable content), disconnects all signals and resets all
buttons and modes.
This function deletes the current main window's GUI only (drawable elements). All the data
classes (staffs, notes, rests) should stay intact. Use delete document() to free the data
part of Canorus as well.
First call clearUI() and then delete model when clearing the document, because cleraUI()
still needs the model alive.
*/
void CAMainWin::clearUI()
{
setCurrentView(nullptr);
// Delete all view port containers and view ports.
while (uiTabWidget->count()) {
CAViewContainer* vpc = static_cast<CAViewContainer*>(uiTabWidget->currentWidget());
uiTabWidget->removeTab(uiTabWidget->currentIndex());
delete vpc;
}
//delete floating Views
while (!_viewList.isEmpty())
delete _viewList.takeFirst();
_sheetMap.clear();
if (_midiRecorderView) {
delete _midiRecorderView;
}
uiEditMode->trigger(); // select mode
}
/*!
Called when the current sheet is switched in the tab widget.
\warning This method is only called when the index of the selected tab changes. If you remove the current tab and the next selected tab gets the same index, this slot isn't called!
*/
void CAMainWin::on_uiTabWidget_currentChanged(int)
{
setCurrentViewContainer(static_cast<CAViewContainer*>(uiTabWidget->currentWidget()));
if (currentViewContainer())
setCurrentView(currentViewContainer()->currentView());
updateToolBars();
}
/*!
Appends a new sheet to the document.
This function is usually called when the user double clicks outside the tabs space.
*/
void CAMainWin::on_uiTabWidget_CANewTab()
{
if (document()) {
on_uiNewSheet_triggered();
}
}
/*!
Changes the sheet order in the document.
This function is usually called when the user double clicks outside the tabs space.
*/
void CAMainWin::on_uiTabWidget_CAMoveTab(int from, int to)
{
if (document() && document()->sheetList().count() >= 2) {
CACanorus::undo()->createUndoCommand(document(), tr("change sheet order", "undo"));
CASheet* s = document()->sheetList()[from];
const_cast<QList<CASheet*>&>(document()->sheetList()).removeAt(from);
const_cast<QList<CASheet*>&>(document()->sheetList()).insert(to, s);
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFullscreen_toggled(bool checked)
{
if (checked)
this->showFullScreen();
else
this->showNormal();
}
void CAMainWin::on_uiHiddenRest_toggled(bool checked)
{
if (mode() == InsertMode) {
musElementFactory()->setRestType(checked ? CARest::Hidden : CARest::Normal);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change hidden rest", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CARest* r = dynamic_cast<CARest*>(v->selection().at(i)->musElement());
if (r) {
r->setRestType(checked ? CARest::Hidden : CARest::Normal);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiSplitHorizontally_triggered()
{
CAView* v = currentViewContainer()->splitHorizontally();
if (!v)
return;
initView(v);
uiUnsplitAll->setEnabled(true);
uiCloseCurrentView->setEnabled(true);
}
void CAMainWin::on_uiSplitVertically_triggered()
{
CAView* v = currentViewContainer()->splitVertically();
if (!v)
return;
initView(v);
uiUnsplitAll->setEnabled(true);
uiCloseCurrentView->setEnabled(true);
}
void CAMainWin::on_uiUnsplitAll_triggered()
{
QList<CAView*> list = currentViewContainer()->unsplitAll();
for (CAView* vp : list)
_viewList.removeAll(vp);
uiCloseCurrentView->setEnabled(false);
uiUnsplitAll->setEnabled(false);
setCurrentView(currentViewContainer()->currentView());
}
void CAMainWin::on_uiCloseCurrentView_triggered()
{
CAView* v = currentViewContainer()->unsplit();
_viewList.removeAll(v);
if (currentViewContainer()->viewList().size() == 1) {
uiCloseCurrentView->setEnabled(false);
uiUnsplitAll->setEnabled(false);
}
setCurrentView(currentViewContainer()->currentView());
}
void CAMainWin::on_uiCloseDocument_triggered()
{
if (CACanorus::mainWinCount(document()) == 1) {
if (!handleUnsavedChanges()) {
return;
}
CACanorus::undo()->deleteUndoStack(document());
clearUI();
delete document();
}
setDocument(nullptr);
uiCloseDocument->setEnabled(false);
rebuildUI();
}
/*!
Shows the current score in CanorusML syntax in a new or the current View.
*/
void CAMainWin::on_uiCanorusMLSource_triggered()
{
CASourceView* v = new CASourceView(document(), nullptr);
initView(v);
currentViewContainer()->addView(v);
uiUnsplitAll->setEnabled(true);
uiCloseCurrentView->setEnabled(true);
}
/*!
Toggles the visibility of the resource view window.
*/
void CAMainWin::on_uiResourceView_toggled(bool checked)
{
if (checked) {
_resourceView->show();
} else {
_resourceView->hide();
}
}
/*!
Toggles the visibility of the ruler.
*/
void CAMainWin::on_uiShowRuler_toggled(bool checked)
{
if (checked) {
CACanorus::settings()->setShowRuler(true);
} else {
CACanorus::settings()->setShowRuler(false);
}
CACanorus::settings()->writeSettings();
}
/*!
Called when a floating view port is closed
*/
void CAMainWin::floatViewClosed(CAView* v)
{
delete v;
if (currentView() == v)
setCurrentView(currentViewContainer()->currentView());
}
void CAMainWin::on_uiNewView_triggered()
{
CAView* v = currentView()->clone(nullptr);
initView(v);
connect(v, SIGNAL(closed(CAView*)), this, SLOT(floatViewClosed(CAView*)));
v->show();
v->setGeometry(this->geometry().x(), this->geometry().y(), CAView::DEFAULT_VIEW_WIDTH, CAView::DEFAULT_VIEW_HEIGHT);
}
/*!
Links the newly created View with the main window:
- Adds the View to the View list
- Connects its signals to main windows' slots.
- Sets the icon, focus policy and sets the focus.
- Sets the currentView but not currentViewContainer
*/
void CAMainWin::initView(CAView* v)
{
_viewList << v;
v->setWindowIcon(QIcon("images:clogosm.png"));
connect(v, SIGNAL(clicked()), this, SLOT(viewClicked()));
switch (v->viewType()) {
case CAView::ScoreView: {
connect(v, SIGNAL(CAMousePressEvent(QMouseEvent*, QPoint)),
this, SLOT(scoreViewMousePress(QMouseEvent*, QPoint)));
connect(v, SIGNAL(CAMouseMoveEvent(QMouseEvent*, QPoint)),
this, SLOT(scoreViewMouseMove(QMouseEvent*, QPoint)));
connect(v, SIGNAL(CAMouseReleaseEvent(QMouseEvent*, QPoint)),
this, SLOT(scoreViewMouseRelease(QMouseEvent*, QPoint)));
connect(v, SIGNAL(CADoubleClickEvent(QMouseEvent*, QPoint)),
this, SLOT(scoreViewDoubleClick(QMouseEvent*, QPoint)));
connect(v, SIGNAL(CATripleClickEvent(QMouseEvent*, QPoint)),
this, SLOT(scoreViewTripleClick(QMouseEvent*, QPoint)));
connect(v, SIGNAL(CAWheelEvent(QWheelEvent*, QPoint)),
this, SLOT(scoreViewWheel(QWheelEvent*, QPoint)));
connect(v, SIGNAL(CAKeyPressEvent(QKeyEvent*)),
this, SLOT(scoreViewKeyPress(QKeyEvent*)));
connect(static_cast<CAScoreView*>(v)->textEdit(), SIGNAL(CAKeyPressEvent(QKeyEvent*)),
this, SLOT(onTextEditKeyPressEvent(QKeyEvent*)));
connect(v, SIGNAL(selectionChanged()),
this, SLOT(onScoreViewSelectionChanged()));
break;
}
case CAView::SourceView: {
connect(v, SIGNAL(CACommit(QString)), this, SLOT(sourceViewCommit(QString)));
break;
}
}
v->setFocusPolicy(Qt::ClickFocus);
v->setFocus();
setCurrentView(v);
setMode(mode()); // updates the new View border settings
}
/*!
Returns the currently selected sheet in the current view or 0, if no such view exists.
*/
CASheet* CAMainWin::currentSheet()
{
if (!currentView()) {
return nullptr;
}
switch (currentView()->viewType()) {
case CAView::ScoreView: {
CAScoreView* v = currentScoreView();
if (v)
return v->sheet();
break;
}
case CAView::SourceView: {
CASourceView* v = static_cast<CASourceView*>(currentView());
if (v->voice() && v->voice()->staff()) {
return v->voice()->staff()->sheet();
} else if (v->lyricsContext()) {
return v->lyricsContext()->sheet();
}
break;
}
}
return nullptr;
}
/*!
Returns the currently selected context in the current view port or 0 if no contexts are selected.
*/
CAContext* CAMainWin::currentContext()
{
if (currentScoreView() && currentScoreView()->currentContext()) {
return currentScoreView()->currentContext()->context();
} else
return nullptr;
}
/*!
Returns the pointer to the currently active voice or 0, if All voices are selected or the current context is not a staff at all.
*/
CAVoice* CAMainWin::currentVoice()
{
if (currentScoreView()) {
return currentScoreView()->selectedVoice();
}
return nullptr;
}
/*!
Sets the currently selected voice and update toolbars and helpers accordingly.
*/
void CAMainWin::setCurrentVoice(CAVoice* v)
{
if (currentScoreView()) {
if (v) {
currentScoreView()->selectContext(v->staff());
}
currentScoreView()->setSelectedVoice(v);
currentScoreView()->updateHelpers();
updateVoiceToolBar();
currentScoreView()->repaint();
}
}
/*!
Creates a new main window sharing the current document.
*/
void CAMainWin::on_uiNewWindow_triggered()
{
CAMainWin* newMainWin = new CAMainWin();
newMainWin->setDocument(document());
newMainWin->rebuildUI();
newMainWin->show();
}
void CAMainWin::on_uiNewDocument_triggered()
{
newDocument();
}
void CAMainWin::on_uiUndo_toggled(bool, int row)
{
stopPlayback();
if (document()) {
int curVoiceIdx = -1;
if (currentVoice() && currentVoice()->staff() && currentVoice()->staff()->sheet()) {
curVoiceIdx = currentVoice()->staff()->sheet()->voiceList().indexOf(currentVoice());
}
for (int i = 0; i <= row; i++) {
CACanorus::undo()->undo(document());
}
if (CACanorus::settings()->useNoteChecker()) {
for (int i = 0; i < document()->sheetList().size(); i++) {
_noteChecker.checkSheet(document()->sheetList()[i]);
}
}
CACanorus::rebuildUI(document());
if (curVoiceIdx >= 0 && curVoiceIdx < currentSheet()->voiceList().size()) {
setCurrentVoice(currentSheet()->voiceList()[curVoiceIdx]);
}
}
}
void CAMainWin::on_uiRedo_toggled(bool, int row)
{
stopPlayback();
if (document()) {
int curVoiceIdx = -1;
if (currentVoice() && currentVoice()->staff() && currentVoice()->staff()->sheet()) {
curVoiceIdx = currentVoice()->staff()->sheet()->voiceList().indexOf(currentVoice());
}
for (int i = 0; i <= row; i++) {
CACanorus::undo()->redo(document());
}
if (CACanorus::settings()->useNoteChecker()) {
for (int i = 0; i < document()->sheetList().size(); i++) {
_noteChecker.checkSheet(document()->sheetList()[i]);
}
}
CACanorus::rebuildUI(document(), nullptr);
if (curVoiceIdx >= 0 && curVoiceIdx < currentSheet()->voiceList().size()) {
setCurrentVoice(currentSheet()->voiceList()[curVoiceIdx]);
}
}
}
/*!
Enables or Disabled undo/redo buttons if there are undo/redo commands on the undo stack.
\sa CACanorus::undoStack()
*/
void CAMainWin::updateUndoRedoButtons()
{
if (CACanorus::undo()->canUndo(document()))
uiUndo->defaultAction()->setEnabled(true);
else
uiUndo->defaultAction()->setEnabled(false);
if (CACanorus::undo()->canRedo(document()))
uiRedo->defaultAction()->setEnabled(true);
else
uiRedo->defaultAction()->setEnabled(false);
}
/*!
Adds a new empty sheet.
*/
void CAMainWin::on_uiNewSheet_triggered()
{
stopPlayback();
CACanorus::undo()->createUndoCommand(document(), tr("new sheet", "undo"));
document()->addSheet();
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document());
uiTabWidget->setCurrentIndex(uiTabWidget->count() - 1);
}
/*!
Adds a new voice to the staff.
*/
void CAMainWin::on_uiNewVoice_triggered()
{
CAStaff* staff = currentStaff();
int voiceNumber = staff->voiceList().size() + 1;
CANote::CAStemDirection stemDirection;
if (voiceNumber == 1)
stemDirection = CANote::StemNeutral;
else {
staff->voiceList()[0]->setStemDirection(CANote::StemUp);
stemDirection = CANote::StemDown;
}
CACanorus::undo()->createUndoCommand(document(), tr("new voice", "undo"));
if (staff) {
staff->addVoice(new CAVoice(staff->name() + tr("Voice%1").arg(staff->voiceList().size() + 1), staff, stemDirection));
staff->synchronizeVoices();
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
uiVoiceNum->setRealValue(staff->voiceList().size());
}
/*!
Removes the current voice from the staff and deletes its contents.
*/
void CAMainWin::on_uiRemoveVoice_triggered()
{
CAVoice* voice = currentVoice();
if (voice) {
// Last voice cannot be deleted
if (voice->staff()->voiceList().size() == 1) {
/*int ret =*/QMessageBox::critical(
this, tr("Canorus"),
tr("Cannot delete the last voice in the staff!"));
return;
}
int ret = QMessageBox::warning(
this, tr("Canorus"),
tr("Are you sure do you want to delete voice\n%1 and all its notes?").arg(voice->name()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::Yes) {
stopPlayback();
CACanorus::undo()->createUndoCommand(document(), tr("voice removal", "undo"));
currentScoreView()->clearSelection();
uiVoiceNum->setRealValue(voice->staff()->voiceList().size() - 1);
voice->staff()->removeVoice(voice);
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
voice->staff()->addVoice(voice);
delete voice; // also removes voice from the staff
}
}
}
/*!
Removes the current context from the sheet and all its contents.
*/
void CAMainWin::on_uiRemoveContext_triggered()
{
CAContext* context = currentContext();
if (context) {
int ret = QMessageBox::warning(
this, tr("Canorus"),
tr("Are you sure do you want to delete context\n%1 and all its contents?").arg(context->name()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::Yes) {
stopPlayback();
CACanorus::undo()->createUndoCommand(document(), tr("context removal", "undo"));
CASheet* sheet = context->sheet();
sheet->removeContext(context);
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
delete context;
}
}
}
void CAMainWin::on_uiContextType_toggled(bool checked, int)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::Undefined);
setMode(InsertMode);
}
}
void CAMainWin::on_uiEditMode_toggled(bool checked)
{
if (checked)
setMode(EditMode);
}
/*!
Allows to set the current mode from privileged (ui/ctl) objects
*/
void CAMainWin::setMode(CAMode mode, const QString& oModeHash)
{
int iAllowed = _modeHash[oModeHash];
qWarning("Allowed %d, max allowed %d, modeHash %s", iAllowed, _iNumAllowed, oModeHash.toLatin1().constData());
if (iAllowed > 0 && iAllowed < _iNumAllowed)
setMode(mode);
}
/*!
Sets the current mode and updates the GUI and toolbars.
*/
void CAMainWin::setMode(CAMode mode)
{
_mode = mode;
switch (mode) {
case InsertMode: {
QPen p;
p.setColor(Qt::blue);
p.setWidth(3);
for (int i = 0; i < _viewList.size(); i++) {
if (_viewList[i]->viewType() == CAView::ScoreView) {
CAScoreView* v = static_cast<CAScoreView*>(_viewList[i]);
if (!v->playing())
v->setBorder(p);
}
}
if (currentScoreView()) {
/// \todo Set other mouse cursors
currentScoreView()->setShadowNoteVisible(musElementFactory()->musElementType() == CAMusElement::Note);
currentScoreView()->repaint();
}
break;
}
case EditMode: {
QPen p;
p.setColor(Qt::red);
p.setWidth(3);
for (int i = 0; i < _viewList.size(); i++) {
if (_viewList[i]->viewType() == CAView::ScoreView) {
CAScoreView* sv = static_cast<CAScoreView*>(_viewList[i]);
if (!sv->playing())
(sv->unsetBorder());
sv->setShadowNoteVisible(false);
sv->repaint();
}
}
if (currentScoreView()) {
if (!currentScoreView()->selection().size()) {
musElementFactory()->setMusElementType(CAMusElement::Undefined);
}
uiVoiceNum->setRealValue(0);
}
break;
}
case ReadOnlyMode:
case ProgressMode:
case NoDocumentMode:
fprintf(stderr, "Warning: CAMainWin::setMode - Unhandled mode %d\n", mode);
break;
} // switch (mode)
updateToolBars();
if ((currentScoreView() && !currentScoreView()->textEditVisible()) || (!currentScoreView() && currentView()))
currentView()->setFocus();
}
/*!
Create hash to allow changing the current mode from priviledged (ui/ctl) objects
*/
QString CAMainWin::createModeHash()
{
QString oHash = QUuid::createUuid().toString();
_modeHash.insert(oHash, _iNumAllowed++);
return oHash;
}
/*!
Rebuilds the GUI from data.
This method is called eg. when multiple Views share the same data and a change has been made (eg. a
note pitch has changed or a new element added). Views content is repositioned and redrawn (CAEngraver
creates CADrawable elements for every score View, sources are updated in source Views etc.).
\a sheet argument is a pointer to the data sheet where the change occured. This way only Views showing
the given sheet are updated which speeds up the process.
If \a sheet argument is null, all Views are rebuilt, but the Views contents, number and locations
remain the same.
If \a repaint is True (default) the rebuilt Views are also repainted. If False, Views content is
only created but not yet drawn. This is useful when multiple operations which could potentially change the
content are to happen and we want to actually draw it only at the end.
*/
void CAMainWin::rebuildUI(CASheet* sheet, bool repaint)
{
if (rebuildUILock())
return;
setRebuildUILock(true);
if (document()) {
// update views
for (int i = 0; i < _viewList.size(); i++) {
if (sheet && _viewList[i]->viewType() == CAView::ScoreView && static_cast<CAScoreView*>(_viewList[i])->sheet() != sheet)
continue;
_viewList[i]->rebuild();
if (_viewList[i]->viewType() == CAView::ScoreView)
static_cast<CAScoreView*>(_viewList[i])->checkScrollBars();
if (repaint)
_viewList[i]->repaint();
}
// update tab name
for (int i = 0; i < uiTabWidget->count(); i++) {
uiTabWidget->setTabText(i, document()->sheetList()[i]->name());
}
} else {
clearUI();
}
if (_resourceView) {
_resourceView->rebuildUi();
}
updateWindowTitle();
updateToolBars();
setRebuildUILock(false);
}
/*!
Rebuilds the GUI from data.
This method is called eg. when multiple Views share the same data and a change has been made (eg. a
note pitch has changed or a new element added). Views content is repositioned and redrawn (CAEngraver
creates CADrawable elements for every score View, sources are updated in source Views etc.).
This method in comparison to CAMainWin::rebuildUI(CASheet *s, bool repaint) rebuilds the whole GUI from
scratch and creates new Views for the sheets. This method is called for example when a new document
is created or opened.
If \a repaint is True (default) the rebuilt Views are also repainted. If False, Views content is
only created but not yet drawn. This is useful when multiple operations which could potentially change the
content are to happen and we want to actually draw it only at the end.
*/
void CAMainWin::rebuildUI(bool repaint)
{
if (rebuildUILock())
return;
setRebuildUILock(true);
if (document()) {
int curIndex = uiTabWidget->currentIndex();
// save the current state of Views
QList<QRectF> worldCoordsList;
for (int i = 0; i < _viewList.size(); i++)
if (_viewList[i]->viewType() == CAView::ScoreView)
worldCoordsList << static_cast<CAScoreView*>(_viewList[i])->worldCoords();
clearUI();
for (int i = 0; i < document()->sheetList().size(); i++) {
addSheet(document()->sheetList()[i]);
// restore the current state of Views
if (_viewList[i]->viewType() == CAView::ScoreView && i < worldCoordsList.size())
static_cast<CAScoreView*>(_viewList[i])->setWorldCoords(worldCoordsList[i]);
}
for (int i = 0; i < _viewList.size(); i++) {
_viewList[i]->rebuild();
if (_viewList[i]->viewType() == CAView::ScoreView)
static_cast<CAScoreView*>(_viewList[i])->checkScrollBars();
if (repaint)
_viewList[i]->repaint();
}
if (curIndex < uiTabWidget->count())
uiTabWidget->setCurrentIndex(curIndex);
} else {
clearUI();
}
if (_resourceView) {
_resourceView->rebuildUi();
}
updateWindowTitle();
updateToolBars();
setRebuildUILock(false);
}
/*!
Processes the mouse press event \a e with world coordinates \a coords.
Any action happened in any of the Views are always linked to these main window slots.
\sa CAScoreView::mousePressEvent(), scoreViewMouseMove(), scoreViewWheel(), scoreViewKeyPress()
*/
void CAMainWin::scoreViewMousePress(QMouseEvent* e, const QPoint coords)
{
CAScoreView* v = static_cast<CAScoreView*>(sender());
QList<CADrawableMusElement*> oldSelection = v->selection();
CADrawableContext* prevContext = v->currentContext();
v->selectCElement(coords.x(), coords.y());
QList<CADrawableMusElement*> l = v->musElementsAt(coords.x(), coords.y());
CADrawableMusElement* newlySelectedElement = nullptr;
int idx = -1;
if (l.size() > 0) { // multiple elements can share the same coordinates
if ((v->selection().size() > 0) && (!v->selection().contains(l.front()))) {
if (e->modifiers() != Qt::ShiftModifier)
v->clearSelection();
v->addToSelection(newlySelectedElement = l[0]); // if the previous selection was not a single element or if the new list doesn't contain the selection set the first element in the available list to the selection
} else {
if (e->modifiers() == Qt::ShiftModifier && v->selection().size() && !v->clickTimerActivated()) {
v->removeFromSelection(l[0]); // shift used on an already selected element - toggle selection
} else {
idx = (v->selection().size() ? l.indexOf(v->selection().front()) : -1);
v->clearSelection();
v->addToSelection(newlySelectedElement = l[((++idx < l.size()) ? idx : 0)]); // if there are two or more elements with the same coordinates, select the next one (behind it). This way, you can click multiple times on the same place and you'll always select the other element.
}
}
} else if (e->modifiers() == Qt::NoModifier) { // no elements at that coordinates
v->clearSelection();
}
// always select the context the current element belongs to
if (newlySelectedElement && (mode() != InsertMode || !uiInsertPlayable->isChecked()))
v->setCurrentContext(newlySelectedElement->drawableContext());
if (v->currentContext() && prevContext != v->currentContext() && mode() != InsertMode) { // new context was selected
// voice number widget
if (v->currentContext()->context()->contextType() == CAContext::Staff) {
uiVoiceNum->setRealValue(0);
uiVoiceNum->setMax(static_cast<CAStaff*>(v->currentContext()->context())->voiceList().size());
}
} else if (prevContext != v->currentContext() && uiInsertPlayable->isChecked()) { // but insert playable mode is active and context should remain the same
v->setCurrentContext(prevContext);
}
if (v->resizeDirection() != CADrawable::Undefined) {
CACanorus::undo()->createUndoCommand(document(), tr("resize", "undo"));
}
switch (mode()) {
case EditMode: {
v->clearSelectionRegionList();
CADrawableMusElement* dElt = nullptr;
CAMusElement* elt = nullptr;
if (v->selection().size()) {
dElt = v->selection().front();
elt = dElt->musElement();
if (!elt)
break;
// debug
QString debugStr;
QTextStream outStr(&debugStr);
outStr << "drawableMusElement: " << dElt << ", x,y=" << dElt->xPos() << "," << dElt->yPos() << ", w,h=" << dElt->width() << "," << dElt->height() << ", dContext=" << dElt->drawableContext() << endl;
outStr << "musElement: " << elt << ", timeStart=" << elt->timeStart() << ", timeEnd=" << elt->timeEnd() << ", context=" << elt->context();
if (elt->isPlayable()) {
outStr << ", voice=" << (static_cast<CAPlayable*>(elt))->voice() << ", voiceNr=" << (static_cast<CAPlayable*>(elt))->voice()->voiceNumber() << ", idxInVoice=" << (static_cast<CAPlayable*>(elt))->voice()->musElementList().indexOf(elt);
outStr << ", voiceStaff=" << (static_cast<CAPlayable*>(elt))->voice()->staff();
if (static_cast<CAPlayable*>(elt)->tuplet()) {
outStr << ", tuplet=" << static_cast<CAPlayable*>(elt)->tuplet();
}
if (elt->musElementType() == CAMusElement::Note)
outStr << ", pitch=" << static_cast<CANote*>(elt)->diatonicPitch().noteName();
}
if (elt->musElementType() == CAMusElement::Slur) {
outStr << "noteStart=" << static_cast<CASlur*>(elt)->noteStart() << ", noteEnd=" << static_cast<CASlur*>(elt)->noteStart();
}
outStr << endl;
qDebug().noquote() << debugStr;
}
// lyrics, texts, bookmarks, chord names
if (v->textEditVisible() && oldSelection.size() && oldSelection.front()->musElement()) {
confirmTextEdit(v, v->textEdit(), oldSelection.front()->musElement());
}
break;
}
case InsertMode: {
// Insert context
if (uiContextType->isChecked()) {
// Add new Context
CAContext* newContext = nullptr;
CADrawableContext* dupContext = v->nearestUpContext(coords.x(), coords.y());
switch (uiContextType->currentId()) {
case CAContext::Staff: {
CACanorus::undo()->createUndoCommand(document(), tr("new staff", "undo"));
QString name = v->sheet()->findUniqueContextName(tr("Staff%1"));
v->sheet()->insertContextAfter(
dupContext ? dupContext->context() : nullptr,
newContext = new CAStaff(name, v->sheet()));
static_cast<CAStaff*>(newContext)->addVoice();
break;
}
case CAContext::LyricsContext: {
CACanorus::undo()->createUndoCommand(document(), tr("new lyrics context", "undo"));
QString name = v->sheet()->findUniqueContextName(tr("LyricsContext%1"));
v->sheet()->insertContextAfter(
dupContext ? dupContext->context() : nullptr,
newContext = new CALyricsContext(
name,
0, // No stanza number by default.
(v->sheet()->voiceList().size() ? v->sheet()->voiceList().at(0) : nullptr)));
break;
}
case CAContext::FiguredBassContext: {
CACanorus::undo()->createUndoCommand(document(), tr("new figured bass context", "undo"));
QString name = v->sheet()->findUniqueContextName(tr("FiguredBassContext%1"));
v->sheet()->insertContextAfter(
dupContext ? dupContext->context() : nullptr,
newContext = new CAFiguredBassContext(name, v->sheet()));
break;
}
case CAContext::FunctionMarkContext: {
CACanorus::undo()->createUndoCommand(document(), tr("new function mark context", "undo"));
QString name = v->sheet()->findUniqueContextName(tr("FunctionMarkContext%1"));
v->sheet()->insertContextAfter(
dupContext ? dupContext->context() : nullptr,
newContext = new CAFunctionMarkContext(name, v->sheet()));
break;
}
case CAContext::ChordNameContext: {
CACanorus::undo()->createUndoCommand(document(), tr("new chord name context", "undo"));
QString name = v->sheet()->findUniqueContextName(tr("ChordNameContext%1"));
v->sheet()->insertContextAfter(
dupContext ? dupContext->context() : nullptr,
newContext = new CAChordNameContext(name, v->sheet()));
break;
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), v->sheet());
if (!newContext) {
qDebug() << "Error: newContext empty";
break;
}
v->selectContext(newContext);
if (newContext->contextType() == CAContext::Staff) {
uiVoiceNum->setMax(1);
uiVoiceNum->setRealValue(0);
}
uiEditMode->toggle();
v->repaint();
break;
}
// Insert playable music element
if (uiInsertPlayable->isChecked()) {
// Add Note/Rest
if (e->button() == Qt::RightButton && musElementFactory()->musElementType() == CAMusElement::Note)
// place a rest when using right mouse button and note insertion is selected
musElementFactory()->setMusElementType(CAMusElement::Rest);
// show the dotted shadow note
currentScoreView()->setShadowNoteLength(musElementFactory()->playableLength());
currentScoreView()->updateHelpers();
}
// Insert playable/music element
bool success = insertMusElementAt(coords, v);
if (musElementFactory()->musElementType() == CAMusElement::Rest)
musElementFactory()->setMusElementType(CAMusElement::Note);
// Insert Syllable, Text, or ChordName
if (!v->selection().isEmpty() && success && (uiInsertSyllable->isChecked() || uiInsertChordName->isChecked() || (uiMarkType->isChecked() && (musElementFactory()->markType() == CAMark::Text || musElementFactory()->markType() == CAMark::BookMark)))) {
v->createTextEdit(v->selection().front());
} else {
v->removeTextEdit();
}
break;
}
case ReadOnlyMode:
case ProgressMode:
case NoDocumentMode:
fprintf(stderr, "Warning: CAMainWin::scoreViewMousePress - Unhandled mode %d\n", mode());
break;
}
CAPluginManager::action("onScoreViewClick", document(), nullptr, nullptr, this);
updateToolBars();
v->repaint();
}
/*!
General View mouse press event.
Sets it as the current view port.
\sa scoreViewMousePress()
*/
void CAMainWin::viewClicked()
{
CAView* v = static_cast<CAView*>(sender());
setCurrentView(v);
if (currentView()->parent()) // not floating
currentViewContainer()->setCurrentView(currentView());
}
/*!
Processes the mouse move event \a e with coordinates \a coords.
Any action happened in any of the Views are always linked to its main window slots.
\sa CAScoreView::mouseMoveEvent(), scoreViewMousePress(), scoreViewWheel(), scoreViewKeyPress()
*/
void CAMainWin::scoreViewMouseMove(QMouseEvent* e, QPoint coords)
{
CAScoreView* c = static_cast<CAScoreView*>(sender());
c->setMouseTracking(false); // disable mouse move events until we finish with drawing
if ((mode() == InsertMode && musElementFactory()->musElementType() == CAMusElement::Note)) {
CADrawableStaff* s;
if (c->currentContext() ? (c->currentContext()->drawableContextType() == CADrawableContext::DrawableStaff) : 0)
s = static_cast<CADrawableStaff*>(c->currentContext());
else
return;
if (musElementFactory()->musElementType() == CAMusElement::Note || musElementFactory()->musElementType() == CAMusElement::Rest) {
c->setShadowNoteVisible(true);
}
// calculate the musical pitch out of absolute world coordinates and the current clef
int pitch = s->calculatePitch(coords.x(), coords.y());
// write into the main window's status bar the note pitch name
int iNoteAccs = s->getAccs(coords.x(), pitch) + musElementFactory()->noteExtraAccs();
musElementFactory()->setNoteAccs(iNoteAccs);
c->setShadowNoteAccs(iNoteAccs);
c->updateHelpers();
c->repaint();
} else if (mode() != InsertMode) {
if (c->resizeDirection() != CADrawable::Undefined) {
// resize element
int time = c->coordsToTime(coords.x());
time -= (time % CAPlayableLength::musicLengthToTimeLength(CAPlayableLength::Sixteenth)); // round timelength to eighth notes length
if (c->resizeDirection() == CADrawable::Right && (time > c->selection().at(0)->musElement()->timeStart())) {
c->selection().at(0)->musElement()->setTimeLength(time - c->selection().at(0)->musElement()->timeStart());
c->selection().at(0)->setWidth(c->timeToCoords(time) - c->selection().at(0)->xPos());
c->repaint();
} else if (c->resizeDirection() == CADrawable::Left && (time < c->selection().at(0)->musElement()->timeEnd())) {
c->selection().at(0)->musElement()->setTimeLength(c->selection().at(0)->musElement()->timeEnd() - time);
c->selection().at(0)->musElement()->setTimeStart(time);
c->selection().at(0)->setXPos(c->timeToCoords(time));
c->selection().at(0)->setWidth(c->timeToCoords(c->selection().at(0)->musElement()->timeEnd()) - c->timeToCoords(time));
c->repaint();
}
} else if (e->buttons() == Qt::LeftButton && c->mouseDragActivated()) {
// multiple selection
c->clearSelectionRegionList();
int x = c->lastMousePressCoords().x(), y = c->lastMousePressCoords().y(),
w = coords.x() - c->lastMousePressCoords().x(), h = coords.y() - c->lastMousePressCoords().y();
if (w < 0) {
x += w;
w *= (-1);
} // user selected from right to left
if (h < 0) {
y += h;
h *= (-1);
} // user selected from bottom to top
QRect selectionRect(x, y, w, h);
QList<CADrawableContext*> dcList = c->findContextsInRegion(selectionRect);
for (int i = 0; i < dcList.size(); i++) {
QList<CADrawableMusElement*> musEltList = dcList[i]->findInRange(selectionRect.x(), selectionRect.x() + selectionRect.width());
for (int j = 0; j < musEltList.size(); j++)
if (musEltList[j]->drawableMusElementType() == CADrawableMusElement::DrawableSlur)
musEltList.removeAt(j--);
if (musEltList.size()) {
c->addSelectionRegion(QRect(musEltList.front()->xPos(), dcList[i]->yPos(),
musEltList.back()->xPos() + musEltList.back()->width() - musEltList.front()->xPos(), dcList[i]->height()));
}
}
c->repaint();
}
}
c->setMouseTracking(true); // re-enable mouse move events, we finished rendering
}
/*!
Processes the mouse double click event.
Currently this selects the current bar.
\sa CAScoreView::selectAllCurBar()
*/
void CAMainWin::scoreViewDoubleClick(QMouseEvent* e, const QPoint p)
{
if (mode() == EditMode) {
CAScoreView* c = static_cast<CAScoreView*>(sender());
CADrawableMusElement* dElt = nullptr;
CAMusElement* elt = nullptr;
if (c->selection().size() == 1) {
dElt = c->selection().front();
elt = dElt->musElement();
}
if (elt && (elt->musElementType() == CAMusElement::Syllable || elt->musElementType() == CAMusElement::ChordName || (elt->musElementType() == CAMusElement::Mark && (static_cast<CAMark*>(elt)->markType() == CAMark::Text || static_cast<CAMark*>(elt)->markType() == CAMark::BookMark)))) {
if (e->modifiers()==Qt::ShiftModifier && elt->context() && (elt->musElementType() == CAMusElement::Syllable || elt->musElementType() == CAMusElement::ChordName)) {
CAMusElement::CAMusElementType t = musElementFactory()->musElementType();
musElementFactory()->setMusElementType(elt->musElementType());
insertMusElementAt(p, c);
musElementFactory()->setMusElementType(t);
dElt = (c->selection().size()?c->selection()[0]:dElt);
}
c->createTextEdit(dElt);
} else {
c->selectAllCurBar();
c->repaint();
}
}
}
/*!
Processes the mouse triple click event.
Currently this selects the current line.
\sa CAScoreView::selectAllCurContext()
*/
void CAMainWin::scoreViewTripleClick(QMouseEvent*, const QPoint)
{
if (mode() == EditMode) {
static_cast<CAScoreView*>(sender())->selectAllCurContext();
static_cast<CAScoreView*>(sender())->repaint();
}
}
/*!
Processes the mouse move event \a e with coordinates \a coords.
Any action happened in any of the Views are always linked to its main window slots.
\sa CAScoreView::mouseReleaseEvent(), scoreViewMousePress(), scoreViewMouseMove(), scoreViewWheel(), scoreViewKeyPress()
*/
void CAMainWin::scoreViewMouseRelease(QMouseEvent* e, QPoint coords)
{
CAScoreView* v = static_cast<CAScoreView*>(sender());
if (v->resizeDirection() != CADrawable::Undefined) {
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), v->sheet());
}
if (mode() != InsertMode) {
if (v->mouseDragActivated()) {
// area was selected
v->clearSelectionRegionList();
if (e->modifiers() == Qt::NoModifier)
v->clearSelection();
int x = v->lastMousePressCoords().x(), y = v->lastMousePressCoords().y(),
w = coords.x() - v->lastMousePressCoords().x(), h = coords.y() - v->lastMousePressCoords().y();
if (w < 0) {
x += w;
w *= (-1);
} // user selected from right to left
if (h < 0) {
y += h;
h *= (-1);
} // user selected from bottom to top
QRect selectionRect(x, y, w, h);
QList<CADrawableContext*> dcList = v->findContextsInRegion(selectionRect);
for (int i = 0; i < dcList.size(); i++) {
QList<CADrawableMusElement*> musEltList = dcList[i]->findInRange(selectionRect.x(), selectionRect.x() + selectionRect.width());
if (v->selectedVoice() && dcList[i]->context() != v->selectedVoice()->staff())
continue;
for (int j = 0; j < musEltList.size(); j++)
if ((!musEltList[j]->isSelectable()) || (v->selectedVoice() && musEltList[j]->musElement()->isPlayable() && static_cast<CAPlayable*>(musEltList[j]->musElement())->voice() != v->selectedVoice()) || (musEltList[j]->drawableMusElementType() == CADrawableMusElement::DrawableSlur))
musEltList.removeAt(j--);
v->addToSelection(musEltList);
}
} else {
// single element or none selected
CADrawableMusElement* dElt = nullptr;
CAMusElement* elt = nullptr;
if (v->selection().size() == 1) {
dElt = v->selection().front();
elt = dElt->musElement();
}
}
v->repaint();
}
}
/*!
Processes the mouse wheel event \a e with coordinates \a coords.
Any action happened in any of the Views are always linked to its main window slots.
\sa CAScoreView::wheelEvent(), scoreViewMousePress(), scoreViewMouseMove(), scoreViewKeyPress()
*/
void CAMainWin::scoreViewWheel(QWheelEvent* e, QPoint coords)
{
CAScoreView* sv = static_cast<CAScoreView*>(sender());
setCurrentView(sv);
//int val;
switch (e->modifiers()) {
case Qt::NoModifier: //scroll horizontally
sv->setWorldX(sv->worldX() - (0.5 * e->delta()) / sv->zoom(), CACanorus::settings()->animatedScroll());
break;
case Qt::AltModifier: //scroll horizontally, fast
sv->setWorldX(sv->worldX() - e->delta() / sv->zoom(), CACanorus::settings()->animatedScroll());
break;
case Qt::ShiftModifier: //scroll vertically
sv->setWorldY(sv->worldY() - (0.5 * e->delta()) / sv->zoom(), CACanorus::settings()->animatedScroll());
break;
case 0x0A000000: //SHIFT+ALT //scroll vertically, fast
sv->setWorldY(sv->worldY() - e->delta() / sv->zoom(), CACanorus::settings()->animatedScroll());
break;
case Qt::ControlModifier: //zoom
if (e->delta() > 0)
sv->setZoom(sv->zoom() * 1.1, coords.x(), coords.y(), CACanorus::settings()->animatedScroll());
else
sv->setZoom(sv->zoom() / 1.1, coords.x(), coords.y(), CACanorus::settings()->animatedScroll());
break;
}
sv->repaint();
}
/*!
Processes the key press event \a e.
Any action happened in any of the Views are always linked to its main window slots.
\sa CAScoreView::keyPressEvent(), scoreViewMousePress(), scoreViewMouseMove(), scoreViewWheel()
*/
void CAMainWin::scoreViewKeyPress(QKeyEvent* e)
{
CAScoreView* v = static_cast<CAScoreView*>(sender());
setCurrentView(v);
// go to Insert mode (if in Select mode) before changing note length
if (e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9 && e->key() != Qt::Key_3) {
if (currentScoreView()->currentContext() && currentScoreView()->currentContext()->context()->contextType() == CAContext::Staff && v->selection().size() == 0) {
uiInsertPlayable->setChecked(true);
}
}
switch (e->key()) {
// Music editing keys
case Qt::Key_Right: {
// select next music element
v->selectNextMusElement(e->modifiers() == Qt::ShiftModifier);
v->repaint();
break;
}
case Qt::Key_Left: {
// select previous music element
v->selectPrevMusElement(e->modifiers() == Qt::ShiftModifier);
v->repaint();
break;
}
case Qt::Key_B: {
// place a barline
CADrawableContext* drawableContext;
drawableContext = v->currentContext();
if ((!drawableContext) || (drawableContext->context()->contextType() != CAContext::Staff))
return;
CAStaff* staff = static_cast<CAStaff*>(drawableContext->context());
CAMusElement* right = nullptr;
if (!v->selection().isEmpty()) {
CAMusElement* e = v->selection().back()->musElement();
if (e->musElementType() == CAMusElement::Note) {
right = staff->next(static_cast<CANote*>(e)->getChord().back());
} else {
right = staff->next(e);
}
}
CACanorus::undo()->createUndoCommand(document(), tr("insert barline", "undo"));
CABarline* bar = new CABarline(
CABarline::Single,
staff,
0);
if (currentVoice()) {
currentVoice()->insert(right, bar); // insert the barline in all the voices, timeStart is set
} else {
if (right && right->isPlayable())
static_cast<CAPlayable*>(right)->voice()->insert(right, bar);
else
staff->voiceList()[0]->insert(right, bar);
}
staff->synchronizeVoices();
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), v->sheet());
v->selectMElement(bar);
v->repaint();
break;
}
case Qt::Key_Up: {
if ((mode() == InsertMode) || (mode() == EditMode)) {
bool rebuild = false;
if (v->selection().size())
CACanorus::undo()->createUndoCommand(document(), tr("rise note", "undo"));
QList<CAMusElement*> eltList;
for (int i = 0; i < v->selection().size(); i++) {
CADrawableMusElement* elt = v->selection().at(i);
// pitch note for one step higher
if (elt->drawableMusElementType() == CADrawableMusElement::DrawableNote) {
CANote* note = static_cast<CANote*>(elt->musElement());
CADiatonicKey key;
if (note->voice()->getKeySig(note)) {
key = note->voice()->getKeySig(note)->diatonicKey();
}
CADiatonicPitch pitch(note->diatonicPitch().noteName() + 1, key.noteAccs(note->diatonicPitch().noteName() + 1));
note->setDiatonicPitch(pitch);
CACanorus::undo()->pushUndoCommand();
rebuild = true;
eltList << note;
}
}
if (CACanorus::settings()->playInsertedNotes()) {
playImmediately(eltList);
}
if (rebuild)
CACanorus::rebuildUI(document(), currentSheet());
}
break;
}
case Qt::Key_Down: {
if ((mode() == InsertMode) || (mode() == EditMode)) {
//bool rebuild = false;
if (v->selection().size())
CACanorus::undo()->createUndoCommand(document(), tr("lower note", "undo"));
QList<CAMusElement*> eltList;
for (int i = 0; i < v->selection().size(); i++) {
CADrawableMusElement* elt = v->selection().at(i);
// pitch note for one step higher
if (elt->drawableMusElementType() == CADrawableMusElement::DrawableNote) {
CANote* note = static_cast<CANote*>(elt->musElement());
CADiatonicKey key;
if (note->voice()->getKeySig(note)) {
key = note->voice()->getKeySig(note)->diatonicKey();
}
CADiatonicPitch pitch(note->diatonicPitch().noteName() - 1, key.noteAccs(note->diatonicPitch().noteName() - 1));
note->setDiatonicPitch(pitch);
CACanorus::undo()->pushUndoCommand();
//rebuild = true;
eltList << note;
}
}
if (CACanorus::settings()->playInsertedNotes()) {
playImmediately(eltList);
}
CACanorus::rebuildUI(document(), currentSheet());
}
break;
}
case Qt::Key_PageDown: {
v->setWorldX(v->worldX() + v->worldWidth(), CACanorus::settings()->animatedScroll());
v->repaint();
break;
}
case Qt::Key_PageUp: {
v->setWorldX(v->worldX() - v->worldWidth(), CACanorus::settings()->animatedScroll());
v->repaint();
break;
}
case Qt::Key_End: {
v->setWorldX(std::numeric_limits<double>::max(), CACanorus::settings()->animatedScroll());
v->repaint();
break;
}
case Qt::Key_Home: {
v->setWorldX(0, CACanorus::settings()->animatedScroll());
v->repaint();
break;
}
case Qt::Key_Plus: {
if (mode() == InsertMode) {
musElementFactory()->addNoteExtraAccs(1);
musElementFactory()->addNoteAccs(1);
v->setDrawShadowNoteAccs(musElementFactory()->noteExtraAccs() != 0);
v->setShadowNoteAccs(musElementFactory()->noteAccs());
v->repaint();
} else if (mode() == EditMode) {
if (!v->selection().isEmpty()) {
QList<CAMusElement*> eltList;
CASheet* sheet = nullptr;
for (CADrawableMusElement* dElt : v->selection()) {
CAMusElement* elt = dElt->musElement();
if (elt->musElementType() == CAMusElement::Note) {
if (!sheet) {
sheet = static_cast<CANote*>(elt)->voice()->staff()->sheet();
CACanorus::undo()->createUndoCommand(document(), tr("add sharp", "undo"));
}
if (static_cast<CANote*>(elt)->diatonicPitch().accs() < 2) // limit the amount of accidentals
static_cast<CANote*>(elt)->diatonicPitch().setAccs(static_cast<CANote*>(elt)->diatonicPitch().accs() + 1);
}
eltList << elt;
}
if (sheet) { // something's changed
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), sheet);
if (CACanorus::settings()->playInsertedNotes()) {
playImmediately(eltList);
}
}
}
}
break;
}
case Qt::Key_Minus: {
if (mode() == InsertMode) {
musElementFactory()->subNoteExtraAccs(1);
musElementFactory()->subNoteAccs(1);
v->setDrawShadowNoteAccs(musElementFactory()->noteExtraAccs() != 0);
v->setShadowNoteAccs(musElementFactory()->noteAccs());
v->repaint();
} else if (mode() == EditMode) {
if (!v->selection().isEmpty()) {
QList<CAMusElement*> eltList;
CASheet* sheet = nullptr;
for (CADrawableMusElement* dElt : v->selection()) {
CAMusElement* elt = dElt->musElement();
if (elt->musElementType() == CAMusElement::Note) {
if (!sheet) {
sheet = static_cast<CANote*>(elt)->voice()->staff()->sheet();
CACanorus::undo()->createUndoCommand(document(), tr("add flat", "undo"));
}
if (static_cast<CANote*>(elt)->diatonicPitch().accs() > -2) // limit the amount of accidentals
static_cast<CANote*>(elt)->diatonicPitch().setAccs(static_cast<CANote*>(elt)->diatonicPitch().accs() - 1);
}
eltList << elt;
}
if (sheet) { // something's changed
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), sheet);
if (CACanorus::settings()->playInsertedNotes()) {
playImmediately(eltList);
}
}
}
}
break;
}
case Qt::Key_Period:
case Qt::Key_Colon:
case Qt::Key_Greater: {
if (mode() == InsertMode) {
musElementFactory()->addPlayableDotted(1, musElementFactory()->playableLength());
currentScoreView()->setShadowNoteLength(musElementFactory()->playableLength());
currentScoreView()->updateHelpers();
v->repaint();
} else if (mode() == EditMode) {
if (!(static_cast<CAScoreView*>(v))->selection().isEmpty()) {
CACanorus::undo()->createUndoCommand(document(), tr("set dotted", "undo"));
CAPlayable* p = dynamic_cast<CAPlayable*>(currentScoreView()->selection().front()->musElement());
if (p) {
CAMusElement* next = nullptr;
int oldLength = p->timeLength();
int dots = p->playableLength().dotted() + (e->modifiers() == Qt::ShiftModifier ? -1 : 1);
if (dots < 0) {
dots += 4;
} else {
dots %= 4;
}
if (p->musElementType() == CAMusElement::Note) { // change the length of the whole chord
QList<CANote*> chord = static_cast<CANote*>(p)->getChord();
for (int i = 0; i < chord.size(); i++) {
next = p->voice()->next(p);
p->voice()->remove(chord[i]);
chord[i]->playableLength().setDotted(dots);
chord[i]->calculateTimeLength();
}
p->voice()->insert(next, chord[0]);
for (int i = 1; i < chord.size(); i++) {
p->voice()->insert(chord[0], chord[i], true);
}
} else if (p->musElementType() == CAMusElement::Rest) {
next = p->voice()->next(p);
p->voice()->remove(p);
p->playableLength().setDotted(dots);
p->calculateTimeLength();
p->voice()->insert(next, p);
}
int newLength = p->timeLength();
if (newLength < oldLength) { // insert rests, if the new length is shorter to keep consistency
QList<CARest*> rests = CARest::composeRests(oldLength - newLength, p->timeStart() + p->timeLength(), p->voice(), CARest::Normal);
for (int i = rests.size() - 1; i >= 0; i--) {
p->voice()->insert(next, rests[i]); // insert rests from shortest to longest
}
} else {
p->staff()->synchronizeVoices();
}
for (int j = 0; j < p->voice()->lyricsContextList().size(); j++) { // reposit syllables
p->voice()->lyricsContextList().at(j)->repositionElements();
}
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), p->staff()->sheet());
}
}
}
break;
}
case Qt::Key_Delete:
case Qt::Key_Backspace:
deleteSelection(v, e->modifiers() == Qt::ShiftModifier, e->modifiers() == Qt::ShiftModifier, true);
break;
// Mode keys
case Qt::Key_Escape:
if (mode() == EditMode) {
if (v->selection().size()) {
v->clearSelection();
} else {
v->setCurrentContext(nullptr);
}
v->repaint();
}
uiEditMode->trigger();
break;
case Qt::Key_I:
uiInsertPlayable->trigger();
break;
case Qt::Key_E:
uiEditMode->trigger();
break;
case Qt::Key_Space:
uiPlayFromSelection->trigger();
break;
case Qt::Key_F5:
CACanorus::rebuildUI(document());
break;
// Note length keys
case Qt::Key_1:
uiPlayableLength->setCurrentId(CAPlayableLength::Whole, true);
break;
case Qt::Key_2:
uiPlayableLength->setCurrentId(CAPlayableLength::Half, true);
break;
case Qt::Key_4:
uiPlayableLength->setCurrentId(CAPlayableLength::Quarter, true);
break;
case Qt::Key_5:
uiPlayableLength->setCurrentId(CAPlayableLength::Eighth, true);
break;
case Qt::Key_6:
uiPlayableLength->setCurrentId(CAPlayableLength::Sixteenth, true);
break;
case Qt::Key_7:
uiPlayableLength->setCurrentId(CAPlayableLength::ThirtySecond, true);
break;
case Qt::Key_8:
uiPlayableLength->setCurrentId(CAPlayableLength::SixtyFourth, true);
break;
case Qt::Key_9:
uiPlayableLength->setCurrentId(CAPlayableLength::HundredTwentyEighth, true);
break;
case Qt::Key_0:
uiPlayableLength->setCurrentId(CAPlayableLength::Breve, true);
break;
case Qt::Key_Tab:
case Qt::Key_Backtab: {
int idx = -1;
if (e->modifiers() == Qt::ControlModifier) // Control tab has different use
idx = uiTabWidget->currentIndex();
else if (currentVoice())
idx = currentSheet()->voiceList().indexOf(currentVoice());
else
idx = currentSheet()->contextList().indexOf(currentContext());
if (e->key() == Qt::Key_Tab) {
idx++;
} else {
idx--;
}
// Next/Previous sheet selection
if (e->modifiers() == Qt::ControlModifier) {
// Cycle if first or last sheet was reached
if (idx >= uiTabWidget->count())
idx = 0;
else if (idx < 0)
idx = uiTabWidget->count() - 1;
//if( idx >=0 && idx < uiTabWidget->count() )
uiTabWidget->setCurrentIndex(idx);
} else // Next/Previous Voice selection
if (currentVoice() && (mode() == InsertMode || mode() == EditMode)) {
// Cycle if first or last voice number was reached
if (idx >= currentSheet()->voiceList().size())
idx = 0;
else if (idx < 0)
idx = currentSheet()->voiceList().size() - 1;
CAVoice* v = currentSheet()->voiceList()[idx];
currentScoreView()->selectContext(v->staff());
uiVoiceNum->setRealValue(v->voiceNumber()); // also calls setCurrentVoice and updates the UI
} else // Next/Previous Context, if selection is empty
if (currentScoreView()->selection().size() == 0) {
if (idx >= currentSheet()->contextList().size())
idx = 0;
else if (idx < 0)
idx = currentSheet()->contextList().size() - 1;
currentScoreView()->selectContext(currentSheet()->contextList()[idx]);
updateToolBars();
currentScoreView()->repaint();
}
break;
}
}
if (e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9 && e->key() != Qt::Key_3) {
musElementFactory()->playableLength().setDotted(0);
v->setShadowNoteLength(musElementFactory()->playableLength());
v->updateHelpers();
v->repaint();
}
updateToolBars();
}
/*!
This method places the currently prepared music element in CAMusElementFactory to the staff or
voice, dependent on the music element type and the View coordinates.
\return True, if a new element of any kind was inserted; False, if an
element was just edited or not handled at all.
*/
bool CAMainWin::insertMusElementAt(const QPoint coords, CAScoreView* v)
{
CADrawableContext* drawableContext = v->currentContext();
CAStaff* staff = nullptr;
CADrawableStaff* drawableStaff = nullptr;
if (drawableContext) {
drawableStaff = dynamic_cast<CADrawableStaff*>(drawableContext);
staff = dynamic_cast<CAStaff*>(drawableContext->context());
}
CADrawableMusElement* drawableRight = v->nearestRightElement(coords.x(), coords.y(), v->currentContext());
CAMusElement* right = nullptr;
if (drawableRight)
right = drawableRight->musElement();
bool success = false;
if (!drawableContext)
return false;
CACanorus::undo()->createUndoCommand(document(), tr("insertion of music element", "undo"));
switch (musElementFactory()->musElementType()) {
case CAMusElement::Clef: {
if (staff)
success = musElementFactory()->configureClef(staff, right);
break;
}
case CAMusElement::KeySignature: {
if (staff)
success = musElementFactory()->configureKeySignature(staff, right);
break;
}
case CAMusElement::TimeSignature: {
if (staff)
success = musElementFactory()->configureTimeSignature(staff, right);
break;
}
case CAMusElement::Barline: {
if (staff)
success = musElementFactory()->configureBarline(staff, right);
break;
}
case CAMusElement::Mark: {
if (v->musElementsAt(coords.x(), coords.y()).size())
success = musElementFactory()->configureMark(v->musElementsAt(coords.x(), coords.y())[0]->musElement());
break;
}
case CAMusElement::Note: { // Do we really need to do all that here??
CAVoice* voice = currentVoice();
if (!voice)
break;
CADrawableMusElement* left = v->nearestLeftElement(coords.x(), coords.y(), voice); // use nearestLeft search because it searches left borders
CADrawableMusElement* dright = v->nearestRightElement(coords.x(), coords.y(), voice);
if (left && left->musElement() && left->musElement()->musElementType() == CAMusElement::Note && left->xPos() <= coords.x() && (left->width() + left->xPos() >= coords.x())) {
// user clicked inside x borders of the note - add a note to the chord
if (voice->containsPitch(drawableStaff->calculatePitch(coords.x(), coords.y()), left->musElement()->timeStart()))
break; // user clicked on an already placed note or wanted to place illegal length (not the one the chord is of) - return and do nothing
success = musElementFactory()->configureNote(drawableStaff->calculatePitch(coords.x(), coords.y()), voice, left->musElement(), true);
} else if (left && left->musElement() && left->musElement()->musElementType() == CAMusElement::Rest && left->xPos() <= coords.x() && (left->width() + left->xPos() >= coords.x())) {
// user clicked inside x borders of the rest - replace the rest/rests with the note
// same code for the Rest insertion
CATuplet* tuplet = static_cast<CAPlayable*>(left->musElement())->tuplet();
QList<CAPlayable*> playableList;
int number = 0;
int actualNumber = 0;
if (tuplet) {
playableList = tuplet->noteList();
number = tuplet->number();
actualNumber = tuplet->actualNumber();
delete tuplet;
}
int timeSum = left->musElement()->timeLength();
int timeLength = CAPlayableLength::playableLengthToTimeLength(musElementFactory()->playableLength());
CAMusElement* next = nullptr;
while ((next = voice->next(left->musElement())) && next->musElementType() == CAMusElement::Rest && timeSum < timeLength) {
voice->remove(next);
playableList.removeAll(static_cast<CAPlayable*>(next));
timeSum += next->timeLength();
}
int tupIndex = playableList.indexOf(static_cast<CAPlayable*>(left->musElement()));
playableList.removeAll(static_cast<CAPlayable*>(left->musElement()));
voice->remove(left->musElement());
if (timeSum - timeLength > 0) {
// we removed too many rests - insert the delta of the missing rests
QList<CARest*> rests = CARest::composeRests(timeSum - timeLength, next ? next->timeStart() : voice->lastTimeEnd(), voice, CARest::Normal);
for (int i = rests.size() - 1; i >= 0; i--) {
voice->insert(next, rests[i]);
playableList.insert(tupIndex, rests[i]);
}
next = rests.last();
}
success = musElementFactory()->configureNote(drawableStaff->calculatePitch(coords.x(), coords.y()), voice, next, false);
if (success)
playableList.insert(tupIndex, static_cast<CAPlayable*>(musElementFactory()->musElement()));
if (success && tuplet) {
new CATuplet(number, actualNumber, playableList);
}
if (success && CACanorus::settings()->autoBar()) {
CAStaff::placeAutoBar(static_cast<CAPlayable*>(musElementFactory()->musElement()));
}
} else {
// user clicked outside x borders of the note or rest
if (dright && dright->musElement() && dright->musElement()->isPlayable() && static_cast<CAPlayable*>(dright->musElement())->tuplet() && !static_cast<CAPlayable*>(dright->musElement())->isFirstInTuplet()) {
delete static_cast<CAPlayable*>(dright->musElement())->tuplet();
}
success = musElementFactory()->configureNote(drawableStaff->calculatePitch(coords.x(), coords.y()), voice, dright ? dright->musElement() : nullptr, false);
if (success && CACanorus::settings()->autoBar())
CAStaff::placeAutoBar(static_cast<CAPlayable*>(musElementFactory()->musElement()));
if (success && uiTupletType->isChecked()) {
QList<CAPlayable*> elements;
elements << static_cast<CAPlayable*>(musElementFactory()->musElement());
for (int i = 1; i < uiTupletNumber->value(); i++) {
musElementFactory()->configureRest(voice, dright ? dright->musElement() : nullptr);
elements << static_cast<CAPlayable*>(musElementFactory()->musElement());
}
musElementFactory()->setMusElement(elements[0]);
new CATuplet(uiTupletNumber->value(), uiTupletActualNumber->value(), elements);
}
}
if (success) {
if (musElementFactory()->musElement()->musElementType() == CAMusElement::Note && CACanorus::settings()->playInsertedNotes()) {
playImmediately(QList<CAMusElement*>() << musElementFactory()->musElement());
}
musElementFactory()->setNoteExtraAccs(0);
v->setDrawShadowNoteAccs(false);
v->setShadowNoteLength(musElementFactory()->playableLength());
v->updateHelpers();
}
break;
}
case CAMusElement::Rest: {
CAVoice* voice = currentVoice();
if (!voice)
break;
CADrawableMusElement* left = v->nearestLeftElement(coords.x(), coords.y(), voice); // use nearestLeft search because it searches left borders
CADrawableMusElement* dright = v->nearestRightElement(coords.x(), coords.y(), voice);
if (left && left->musElement() && left->musElement()->isPlayable() && left->xPos() <= coords.x() && (left->width() + left->xPos() >= coords.x())) {
// user clicked inside x borders of the rest or note - replace the rest/rests with the rest
// same code for the Note insertion
CATuplet* tuplet = static_cast<CAPlayable*>(left->musElement())->tuplet();
QList<CAPlayable*> playableList;
int number = 0;
int actualNumber = 0;
if (tuplet) {
playableList = tuplet->noteList();
number = tuplet->number();
actualNumber = tuplet->actualNumber();
delete tuplet;
}
int timeSum = left->musElement()->timeLength();
int timeLength = CAPlayableLength::playableLengthToTimeLength(musElementFactory()->playableLength());
CAMusElement* next = nullptr;
// collect all preceeding rests to merge them as one, if needed
while ((next = voice->next(left->musElement())) && next->musElementType() == CAMusElement::Rest && timeSum < timeLength) {
voice->remove(next);
playableList.removeAll(static_cast<CAPlayable*>(next));
timeSum += next->timeLength();
}
// remove all notes in the chord except the last
if (left->musElement()->musElementType() == CAMusElement::Note && static_cast<CANote*>(left->musElement())->isPartOfChord()) {
QList<CANote*> chordNotes = static_cast<CANote*>(left->musElement())->getChord();
for (int i = 0; i < chordNotes.size(); i++) {
if (chordNotes[i] == left->musElement()) {
continue;
}
playableList.removeAll(chordNotes[i]);
voice->remove(chordNotes[i]);
}
// also update next
next = voice->next(static_cast<CANote*>(left->musElement())->getChord().last());
}
CAPlayable* playableToReplace = static_cast<CAPlayable*>(left->musElement());
int tupIndex = playableList.indexOf(playableToReplace);
playableList.removeAll(playableToReplace);
voice->remove(playableToReplace);
if (timeSum - timeLength > 0) {
// we removed too many rests - insert the delta of the missing rests
QList<CARest*> rests = CARest::composeRests(timeSum - timeLength, next ? next->timeStart() : voice->lastTimeEnd(), voice, CARest::Normal);
for (int i = rests.size() - 1; i >= 0; i--) {
voice->insert(next, rests[i]);
playableList.insert(tupIndex, rests[i]);
}
next = rests.last();
}
success = musElementFactory()->configureRest(voice, next);
if (success) {
playableList.insert(tupIndex, static_cast<CAPlayable*>(musElementFactory()->musElement()));
}
if (success && tuplet) {
new CATuplet(number, actualNumber, playableList);
}
if (success && CACanorus::settings()->autoBar()) {
CAStaff::placeAutoBar(static_cast<CAPlayable*>(musElementFactory()->musElement()));
}
} else {
if (dright && dright->musElement() && dright->musElement()->isPlayable() && static_cast<CAPlayable*>(dright->musElement())->tuplet() && !static_cast<CAPlayable*>(dright->musElement())->isFirstInTuplet()) {
delete static_cast<CAPlayable*>(dright->musElement())->tuplet();
}
success = musElementFactory()->configureRest(voice, dright ? dright->musElement() : nullptr);
if (success && CACanorus::settings()->autoBar())
CAStaff::placeAutoBar(static_cast<CAPlayable*>(musElementFactory()->musElement()));
}
if (success) {
v->setShadowNoteLength(musElementFactory()->playableLength());
v->updateHelpers();
}
break;
}
case CAMusElement::Slur: {
// Insert tie, slur or phrasing slur
if (v->selection().size()) { // start note has to always be selected
CAMusElement* eltStart = currentScoreView()->selection().front()->musElement();
CANote* noteStart = nullptr;
if (eltStart->musElementType() == CAMusElement::Note) {
noteStart = static_cast<CANote*>(eltStart);
} else if (eltStart->musElementType() == CAMusElement::Mark) {
noteStart = dynamic_cast<CANote*>(static_cast<CAMark*>(eltStart)->associatedElement());
}
CAMusElement* eltEnd = currentScoreView()->selection().back()->musElement();
CANote* noteEnd = nullptr;
if (eltEnd->musElementType() == CAMusElement::Note) {
noteEnd = static_cast<CANote*>(eltEnd);
} else if (eltEnd->musElementType() == CAMusElement::Mark) {
noteEnd = dynamic_cast<CANote*>(static_cast<CAMark*>(eltEnd)->associatedElement());
}
// Insert Tie
if (noteStart && musElementFactory()->slurType() == CASlur::TieType) {
noteEnd = nullptr; // find a fresh next note
QList<CANote*> noteList = noteStart->voice()->getNoteList();
if (noteStart->tieStart()) {
break; // return, if the tie already exists
} else {
// create a new tie
for (int i = 0; i < noteList.count() && noteList[i]->timeStart() <= noteStart->timeEnd(); i++) {
if (noteList[i]->timeStart() == noteStart->timeEnd() && noteList[i]->diatonicPitch() == noteStart->diatonicPitch()) {
noteEnd = noteList[i];
break;
}
}
}
success = musElementFactory()->configureSlur(staff, noteStart, noteEnd);
} else
// Insert slur or phrasing slur
if (noteStart && noteEnd && noteStart != noteEnd && (musElementFactory()->slurType() == CASlur::SlurType || musElementFactory()->slurType() == CASlur::PhrasingSlurType)) {
if (noteStart->isPartOfChord())
noteStart = noteStart->getChord().at(0);
if (noteEnd->isPartOfChord())
noteEnd = noteEnd->getChord().at(0);
QList<CANote*> noteList = noteStart->voice()->getNoteList();
int end = noteList.indexOf(noteEnd);
for (int i = noteList.indexOf(noteStart); i <= end; i++)
if ((musElementFactory()->slurType() == CASlur::SlurType && (noteList[i]->slurStart() || noteList[i]->slurEnd())) || (musElementFactory()->slurType() == CASlur::PhrasingSlurType && (noteList[i]->phrasingSlurStart() || noteList[i]->phrasingSlurEnd())))
return false;
if (((musElementFactory()->slurType() == CASlur::SlurType && (noteStart->slurStart())) || noteEnd->slurEnd()) || (((musElementFactory()->slurType() == CASlur::PhrasingSlurType && (noteStart->phrasingSlurStart()))) || noteEnd->phrasingSlurEnd()))
break; // return, if the slur already exist
success = musElementFactory()->configureSlur(staff, noteStart, noteEnd);
}
}
break;
}
case CAMusElement::FiguredBassMark: {
// Insert figured bass number
CADrawableMusElement* left = v->nearestLeftElement(coords.x(), coords.y());
int timeStart = ((left && left->musElement()) ? left->musElement()->timeStart() : 0);
if (drawableContext->context()->contextType() == CAContext::FiguredBassContext) {
CAFiguredBassContext* fbc = static_cast<CAFiguredBassContext*>(drawableContext->context());
CAFiguredBassMark* fbm = fbc->figuredBassMarkAtTimeStart(timeStart);
if (fbm) {
success = musElementFactory()->configureFiguredBassNumber(fbm);
}
}
break;
}
case CAMusElement::FunctionMark: {
// Insert function mark
if (drawableContext->context()->contextType() == CAContext::FunctionMarkContext) {
CAFunctionMarkContext* fmc = static_cast<CAFunctionMarkContext*>(drawableContext->context());
CADrawableMusElement* dLeft = v->nearestLeftElement(coords.x(), coords.y());
int timeStart = 0;
if (dLeft) // find the nearest left element from the cursor
timeStart = dLeft->musElement()->timeStart();
QList<CAPlayable*> chord = currentSheet()->getChord(timeStart);
int timeLength = chord.size() ? chord[0]->timeLength() : 256;
for (int i = 0; i < chord.size(); i++) // find the shortest note in the chord
if (chord[i]->timeLength() - (timeStart - chord[i]->timeStart()) < timeLength)
timeLength = chord[i]->timeLength() - (timeStart - chord[i]->timeStart());
success = musElementFactory()->configureFunctionMark(fmc, timeStart, timeLength);
}
break;
}
case CAMusElement::Syllable:
case CAMusElement::ChordName:
if (drawableContext->context()->contextType() == CAContext::LyricsContext || drawableContext->context()->contextType() == CAContext::ChordNameContext) {
CADrawableMusElement *dLeft = v->nearestLeftElement(coords.x(), coords.y(), drawableContext);
CAMusElement *newElt = drawableContext->context()->insertEmptyElement(dLeft ? dLeft->musElement()->timeStart() : 0);
if (newElt) {
newElt->context()->repositionElements();
musElementFactory()->setMusElement(newElt);
success = true;
}
}
break;
case CAMusElement::MidiNote:
case CAMusElement::Tuplet:
case CAMusElement::Undefined:
qDebug() << "Warning: CAMainWin::insertMusElementAt - Unhandled Element" << musElementFactory()->musElementType();
break;
}
if (success) {
if (staff)
staff->synchronizeVoices();
CACanorus::undo()->pushUndoCommand();
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
CACanorus::rebuildUI(document(), v->sheet());
CADrawableMusElement* d = v->selectMElement(musElementFactory()->musElement());
musElementFactory()->emptyMusElem();
// move the view to the right, if the right border was hit
if (d && (d->xPos() > v->worldX() + 0.85 * v->worldWidth())) {
v->setWorldX(d->xPos() - v->worldWidth() / 2, CACanorus::settings()->animatedScroll());
}
}
return success;
}
/*!
Main window's key press event.
\sa viewKeyPressEvent()
*/
void CAMainWin::keyPressEvent(QKeyEvent*)
{
}
/*!
Called when selection in score Views is changed.
*/
void CAMainWin::onScoreViewSelectionChanged()
{
if (static_cast<CAScoreView*>(sender())->selection().size()) {
uiCopy->setEnabled(true);
uiCut->setEnabled(true);
} else {
uiCopy->setEnabled(false);
uiCut->setEnabled(false);
}
CAPluginManager::action("onSelectionChanged", document(), nullptr, nullptr, this);
}
/*!
Called every second when timeEditedTimer has timeout.
Increases the locally stored time the document is being edited.
*/
void CAMainWin::onTimeEditedTimerTimeout()
{
_timeEditedTime++;
}
/*!
Called when playback is finished or interrupted by the user.
It stops the playback, closes ports etc.
*/
void CAMainWin::playbackFinished()
{
delete _playback;
_playback = nullptr;
uiPlayFromSelection->setChecked(false);
if (_playbackView) {
static_cast<CAScoreView*>(_playbackView)->setPlaying(false);
}
if (_repaintTimer) {
_repaintTimer->stop();
/// \todo crashes, if disconnected sometimes. -Matevz
//_repaintTimer->disconnect();
/// \todo crashes, if deleted. -Matevz
//delete _repaintTimer;
}
CACanorus::midiDevice()->closeOutputPort();
if (_playbackView) {
static_cast<CAScoreView*>(_playbackView)->clearSelection();
static_cast<CAScoreView*>(_playbackView)->addToSelection(_prePlaybackSelection);
static_cast<CAScoreView*>(_playbackView)->unsetBorder();
}
_prePlaybackSelection.clear();
_playbackView = nullptr;
setMode(mode());
}
/*!
Connected with the play button which starts the playback.
*/
void CAMainWin::on_uiPlayFromSelection_toggled(bool checked)
{
if (checked && currentScoreView() && !_playback) {
/// \todo replace raw pointer with shared or unique pointer
_repaintTimer = new QTimer();
_repaintTimer->setInterval(100);
_repaintTimer->start();
//connect(_repaintTimer, SIGNAL(timeout()), this, SLOT(on_repaintTimer_timeout())); //TODO: timeout is connected directly to repaint() directly. This should be optimized in the future -Matevz
connect(_repaintTimer, SIGNAL(timeout()), this, SLOT(onRepaintTimerTimeout()));
CACanorus::midiDevice()->openOutputPort(CACanorus::settings()->midiOutPort());
/// \todo replace raw pointer with shared or unique pointer
_playback = new CAPlayback(currentSheet(), CACanorus::midiDevice());
if (currentScoreView()->selection().size() && currentScoreView()->selection().at(0)->musElement())
_playback->setInitTimeStart(currentScoreView()->selection().at(0)->musElement()->timeStart());
connect(_playback, SIGNAL(playbackFinished()), this, SLOT(playbackFinished()));
QPen p;
p.setColor(Qt::green);
p.setWidth(3);
_playbackView = currentView();
currentScoreView()->setBorder(p);
currentScoreView()->setPlaying(true); // set the deadlock for borders
// Remember old selection
_prePlaybackSelection = currentScoreView()->selection();
currentScoreView()->clearSelection();
_playback->start();
} else if (_playback) {
_playback->stop();
}
}
/*!
Called every few miliseconds during playback to repaint score View as the GUI can
only be repainted from the main thread.
*/
void CAMainWin::onRepaintTimerTimeout()
{
CAScoreView* sv = static_cast<CAScoreView*>(_playbackView);
sv->clearSelection();
for (int i = 0; i < _playback->curPlaying().size(); i++) {
if (_playback->curPlaying().at(i)->musElementType() == CAMusElement::Note) {
CADrawableMusElement* elt = sv->addToSelection(_playback->curPlaying()[i]);
if (CACanorus::settings()->lockScrollPlayback()) {
if (elt && (elt->xPos() > (sv->worldX() + sv->worldWidth()) || elt->xPos() < sv->worldX())) {
sv->setWorldX(elt->xPos() - 50, CACanorus::settings()->animatedScroll());
}
}
}
}
sv->repaint();
}
void CAMainWin::on_uiLockScrollPlayback_toggled(bool val)
{
CACanorus::settings()->setLockScrollPlayback(val);
}
void CAMainWin::on_uiSelectAll_triggered()
{
if (!currentView())
return;
if (currentView()->viewType() == CAView::ScoreView)
static_cast<CAScoreView*>(currentView())->selectAll();
else if (currentView()->viewType() == CAView::SourceView)
static_cast<CASourceView*>(currentView())->selectAll();
currentView()->repaint();
}
void CAMainWin::on_uiInvertSelection_triggered()
{
if (currentView() && currentView()->viewType() == CAView::ScoreView) {
static_cast<CAScoreView*>(currentView())->invertSelection();
currentView()->repaint();
}
}
void CAMainWin::on_uiZoomToSelection_triggered()
{
if (_currentView->viewType() == CAView::ScoreView)
(static_cast<CAScoreView*>(_currentView))->zoomToSelection(CACanorus::settings()->animatedScroll());
}
void CAMainWin::on_uiZoomToFit_triggered()
{
if (_currentView->viewType() == CAView::ScoreView)
(static_cast<CAScoreView*>(_currentView))->zoomToFit();
}
void CAMainWin::on_uiZoomToWidth_triggered()
{
if (_currentView->viewType() == CAView::ScoreView)
(static_cast<CAScoreView*>(_currentView))->zoomToWidth();
}
void CAMainWin::on_uiZoomToHeight_triggered()
{
if (_currentView->viewType() == CAView::ScoreView)
(static_cast<CAScoreView*>(_currentView))->zoomToHeight();
}
void CAMainWin::closeEvent(QCloseEvent* event)
{
if (!handleUnsavedChanges()) {
event->ignore();
} else {
clearUI();
event->accept();
}
}
void CAMainWin::on_uiOpenDocument_triggered()
{
if (!handleUnsavedChanges()) {
return;
}
if (CAMainWin::uiOpenDialog->exec() && CAMainWin::uiOpenDialog->selectedFiles().size()) {
openDocument(CAMainWin::uiOpenDialog->selectedFiles().at(0));
}
}
/**
Calls the save document method or save as, if the document doesn't exist yet.
Returns True, if the document was saved; False otherwise.
*/
bool CAMainWin::on_uiSaveDocument_triggered()
{
QString s;
if (document()) {
if ((s = document()->fileName()).isEmpty()) {
return on_uiSaveDocumentAs_triggered();
} else {
return saveDocument(s);
}
}
return false;
}
/**
Calls the save document method.
Returns True, if the document was saved; False otherwise.
*/
bool CAMainWin::on_uiSaveDocumentAs_triggered()
{
if (document()) {
if (CAMainWin::uiSaveDialog) {
CAMainWin::uiSaveDialog->exec();
if (CAMainWin::uiSaveDialog->selectedFiles().size()) {
QString s = CAMainWin::uiSaveDialog->selectedFiles().at(0);
// append the extension, if the filename doesn't contain a dot
//int i;
if (!s.contains('.')) {
int left = uiSaveDialog->selectedNameFilter().indexOf("(*.") + 2;
int len = uiSaveDialog->selectedNameFilter().size() - left - 1;
s.append(uiSaveDialog->selectedNameFilter().mid(left, len));
}
return saveDocument(s);
} else {
qWarning() << "Save Document: No file selected.";
return false;
}
} else {
qWarning() << "Save Document: Save Dialog does not exist.";
return false;
}
} else {
qWarning() << "Save Document: Missing ressources to create Save Dialog.";
return false;
}
}
/*!
Opens a document with the given absolute file name.
The previous document will be lost.
Returns a pointer to the opened document or null if opening the document has failed.
*/
CADocument* CAMainWin::openDocument(const QString& fileName)
{
stopPlayback();
if (_importFile) {
_importFile.reset();
}
if (fileName.endsWith(".xml")) {
_importFile = std::make_unique<CACanorusMLImport>();
uiSaveDialog->selectNameFilter(CAFileFormats::CANORUSML_FILTER);
} else if (fileName.endsWith(".can")) {
_importFile = std::make_unique<CACanImport>();
uiSaveDialog->selectNameFilter(CAFileFormats::CAN_FILTER);
} else {
return nullptr; // FIXME Failing quietly, add error message
}
connect(_importFile.get(), SIGNAL(importDone(int)), this, SLOT(onImportDone(int)));
_importFile->setStreamFromFile(fileName);
_importFile->importDocument();
_mainWinProgressCtl.startProgress(*_importFile.get());
return _importFile->importedDocument();
}
/*!
Opens the given document.
The previous document will be lost.
Returns a pointer to the opened document or null if opening the document has failed.
*/
CADocument* CAMainWin::openDocument(CADocument* doc)
{
stopPlayback();
if (doc) {
if (document() && CACanorus::mainWinCount(document()) == 1) {
CACanorus::undo()->deleteUndoStack(document());
clearUI();
delete document();
}
setDocument(doc);
if (!doc->fileName().isEmpty()) {
CACanorus::insertRecentDocument(doc->fileName());
QDir dir(QFileInfo(doc->fileName()).absoluteDir());
uiOpenDialog->setDirectory(dir);
uiSaveDialog->setDirectory(dir);
uiExportDialog->setDirectory(dir);
uiImportDialog->setDirectory(dir);
}
CACanorus::undo()->createUndoStack(document());
uiCloseDocument->setEnabled(true);
if (CACanorus::settings()->useNoteChecker()) {
for (int i = 0; i < doc->sheetList().size(); i++) {
_noteChecker.checkSheet(doc->sheetList()[i]);
}
}
rebuildUI(); // local rebuild only
if (doc->sheetList().size())
uiTabWidget->setCurrentIndex(0);
setMode(EditMode);
// select the first context automatically
if (document() && document()->sheetList().size() && document()->sheetList()[0]->contextList().size())
currentScoreView()->selectContext(document()->sheetList()[0]->contextList()[0]);
updateToolBars();
return doc;
}
return nullptr;
}
/*!
Saves the current document to a given absolute \a fileName.
This function is usually called when the filename was entered and save document dialog
successfully closed.
If \a recovery is False (default), it changes the timeEdit, fileName and some other document
properties before saving it.
Returns True, if the save was complete; False otherwise.
*/
bool CAMainWin::saveDocument(QString fileName)
{
document()->setTimeEdited(document()->timeEdited() + _timeEditedTime);
document()->setDateLastModified(QDateTime::currentDateTime());
CACanorus::restartTimeEditedTimes(document());
CAExport* save = nullptr;
if (fileName.endsWith(".xml")) { // check the filename extension directly without accessing the uiSaveDialog object due to a bug in Qt. -Matevz
/// \todo replace raw pointer with shared or unique pointer
save = new CACanorusMLExport();
} else if (fileName.endsWith(".can")) {
/// \todo replace raw pointer with shared or unique pointer
save = new CACanExport();
}
if (save) {
save->setStreamToFile(fileName);
save->exportDocument(document());
save->wait();
if (save->status() == 0) {
document()->setFileName(fileName);
CACanorus::insertRecentDocument(fileName);
delete save;
QDir dir(QFileInfo(fileName).absoluteDir());
uiOpenDialog->setDirectory(dir);
uiSaveDialog->setDirectory(dir);
uiExportDialog->setDirectory(dir);
uiImportDialog->setDirectory(dir);
document()->setModified(false);
updateWindowTitle();
return true;
} else {
QMessageBox::critical(
this,
tr("Error while saving document"),
tr("The document was not saved!\nError number %1 %2.").arg(save->status()).arg(save->readableStatus()));
delete save;
return false;
}
}
QMessageBox::critical(
this,
tr("Error while saving document"),
tr("Unknown file format %1.").arg(uiSaveDialog->selectedNameFilter()));
return false;
}
void CAMainWin::updateWindowTitle()
{
if (document() && !document()->title().isEmpty()) {
setWindowTitle(document()->title() + " - Canorus");
} else if (document() && !document()->fileName().isEmpty()) {
setWindowTitle(document()->fileName().right(document()->fileName().size() - document()->fileName().lastIndexOf('/') - 1) + " - Canorus");
} else if (document()) {
setWindowTitle(tr("Untitled") + " - Canorus");
} else {
setWindowTitle("Canorus");
}
if (document() && document()->isModified()) {
setWindowTitle(windowTitle() + " " + tr("(modified)"));
}
}
void CAMainWin::onMidiInEvent(QVector<unsigned char> m)
{
_keybdInput->onMidiInEvent(m);
return;
}
/*!
Called when File->Export is clicked.
*/
void CAMainWin::on_uiExportDocument_triggered()
{
QStringList fileNames;
QString fileExtString;
QStringList fileExtList;
int ffound = uiExportDialog->exec();
if (!ffound)
return;
// ! Warning: If there is still a running export instance
// ! this will stop the old one (kill it actually)
/// \todo: maybe block new export until the old is finished
if (_poExp) // Delete old export instance
delete _poExp;
fileNames = uiExportDialog->selectedFiles();
QString s = fileNames[0];
if (s.isEmpty()) {
QMessageBox::information(nullptr, tr("No file name"), tr("Warning: No file name for export specified."));
return;
}
if (!s.contains('.')) {
int left = uiExportDialog->selectedNameFilter().indexOf("(*.") + 2;
int len = uiExportDialog->selectedNameFilter().size() - left - 1;
fileExtString = uiExportDialog->selectedNameFilter().mid(left, len);
// the default file extension is the first one:
fileExtList = fileExtString.split(" ");
s.append(fileExtList[0]);
}
if (CAPluginManager::exportFilterExists(uiExportDialog->selectedNameFilter())) {
CAPluginManager::exportAction(uiExportDialog->selectedNameFilter(), document(), s);
} else {
if (uiExportDialog->selectedNameFilter() == CAFileFormats::MIDI_FILTER) {
/// \todo replace raw pointer with shared or unique pointer
CAMidiExport* pme = new CAMidiExport;
_poExp = pme;
} else if (uiExportDialog->selectedNameFilter() == CAFileFormats::LILYPOND_FILTER) {
/// \todo replace raw pointer with shared or unique pointer
CALilyPondExport* ple = new CALilyPondExport;
_poExp = ple;
} else if (uiExportDialog->selectedNameFilter() == CAFileFormats::MUSICXML_FILTER) {
/// \todo replace raw pointer with shared or unique pointer
CAMusicXmlExport* musicxml = new CAMusicXmlExport;
_poExp = musicxml;
} else if (uiExportDialog->selectedNameFilter() == CAFileFormats::PDF_FILTER) {
/// \todo replace raw pointer with shared or unique pointer
CAPDFExport* ppe = new CAPDFExport;
_poExp = ppe;
} else if (uiExportDialog->selectedNameFilter() == CAFileFormats::SVG_FILTER) {
/// \todo replace raw pointer with shared or unique pointer
CASVGExport* pse = new CASVGExport;
_poExp = pse;
} else {
//TODO: unknown/unsupported format, raise an error
return;
}
if (_poExp) {
_poExp->setStreamToFile(s);
// @ToDo Complete document export is not supported currently
// Also when (context) to print current sheet and when the whole document ?
//_poExp->exportDocument( document() );
_poExp->exportSheet(currentSheet());
_poExp->wait();
//delete _poExp;
}
}
}
/*!
Called when File->Import is clicked.
*/
void CAMainWin::on_uiImportDocument_triggered()
{
if (!handleUnsavedChanges()) {
return;
}
QStringList fileNames;
int ffound = uiImportDialog->exec();
if (ffound)
fileNames = uiImportDialog->selectedFiles();
if (!ffound)
return;
stopPlayback();
QString s = fileNames[0];
if (CAPluginManager::importFilterExists(uiImportDialog->selectedNameFilter())) {
// Import done using a scripting engine
/// \todo replace raw pointer with shared or unique pointer
setDocument(new CADocument());
CACanorus::undo()->createUndoStack(document());
uiCloseDocument->setEnabled(true);
CAPluginManager::importAction(uiImportDialog->selectedNameFilter(), document(), fileNames[0]);
CACanorus::rebuildUI(document());
} else {
if (_importFile) {
_importFile.reset();
}
if (uiImportDialog->selectedNameFilter() == CAFileFormats::MIDI_FILTER) {
if (!document())
newDocument();
_importFile = std::make_unique<CAMidiImport>();
if (_importFile) {
_importFile->setStreamFromFile(s);
connect(_importFile.get(), SIGNAL(importDone(int)), this, SLOT(onImportDone(int)));
_importFile->importSheet();
}
} else if (uiImportDialog->selectedNameFilter() == CAFileFormats::LILYPOND_FILTER) {
// activate this filter in src/canorus.cpp when sheet import is usable
if (!document())
newDocument();
_importFile = std::make_unique<CALilyPondImport>();
if (_importFile) {
_importFile->setStreamFromFile(s);
connect(_importFile.get(), SIGNAL(importDone(int)), this, SLOT(onImportDone(int)));
_importFile->importSheet();
}
} else if (uiImportDialog->selectedNameFilter() == CAFileFormats::MUSICXML_FILTER) {
_importFile = std::make_unique<CAMusicXmlImport>();
if (_importFile) {
_importFile->setStreamFromFile(s);
connect(_importFile.get(), SIGNAL(importDone(int)), this, SLOT(onImportDone(int)));
_importFile->importDocument();
}
} else if (uiImportDialog->selectedNameFilter() == CAFileFormats::MXL_FILTER) {
_importFile = std::make_unique<CAMXLImport>();
if (_importFile) {
_importFile->setStreamFromFile(s);
connect(_importFile.get(), SIGNAL(importDone(int)), this, SLOT(onImportDone(int)));
_importFile->importDocument();
}
}
if (_importFile) {
_mainWinProgressCtl.startProgress(*_importFile.get());
}
}
}
void CAMainWin::onImportDone(int)
{
CAImport* import = static_cast<CAImport*>(sender());
if (!import) {
return;
}
bool success = (import->status() == 0);
if (success) {
if (import->importedDocument()) {
openDocument(import->importedDocument());
} else {
if (import->importedSheet()) {
addSheet(import->importedSheet());
document()->addSheet(import->importedSheet());
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(import->importedSheet());
}
CACanorus::rebuildUI(document());
}
}
// select the first context automatically
if (document() && document()->sheetList().size() && document()->sheetList()[0]->contextList().size()) {
currentScoreView()->selectContext(document()->sheetList()[0]->contextList()[0]);
}
updateToolBars();
} else {
QMessageBox::critical(this, tr("Canorus"),
tr("Error while opening the file!\nError %1: ").arg(import->status()) + import->readableStatus());
}
}
/*!
Called when Export directly to PDF action is clicked.
*/
void CAMainWin::on_uiExportToPdf_triggered()
{
uiExportDialog->setNameFilter(CAFileFormats::PDF_FILTER);
on_uiExportDocument_triggered();
}
void CAMainWin::onExportDone(int)
{
}
/*!
Called when a user changes the current voice number.
*/
void CAMainWin::on_uiVoiceNum_valChanged(int voiceNr)
{
if (currentScoreView()) {
// Store voice name if changed.
on_uiVoiceName_editingFinished();
if (voiceNr && currentScoreView()->currentContext() && currentScoreView()->currentContext()->context()->contextType() == CAContext::Staff && voiceNr <= static_cast<CAStaff*>(currentScoreView()->currentContext()->context())->voiceList().size()) {
setCurrentVoice(static_cast<CAStaff*>(currentScoreView()->currentContext()->context())->voiceList()[voiceNr - 1]);
} else {
setCurrentVoice(nullptr);
}
}
}
/*!
Brings up the properties dialog.
*/
void CAMainWin::on_uiVoiceProperties_triggered()
{
CAPropertiesDialog::voiceProperties(currentVoice(), this);
}
/*!
Changes the offset of the clef.
*/
void CAMainWin::on_uiClefOffset_valueChanged(int newOffset)
{
if (oldUiClefOffsetValue == 0 && qAbs(newOffset) == 1) {
uiClefOffset->setValue((newOffset / qAbs(newOffset)) * 2);
return;
} else if (qAbs(oldUiClefOffsetValue) == 2 && qAbs(newOffset) == 1) {
uiClefOffset->setValue(0);
return;
}
oldUiClefOffsetValue = newOffset;
if (mode() == InsertMode) {
musElementFactory()->setClefOffset(newOffset);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CACanorus::undo()->createUndoCommand(document(), tr("change clef offset", "undo"));
CAClef* clef = dynamic_cast<CAClef*>(v->selection().at(0)->musElement());
if (clef) {
clef->setOffset(CAClef::offsetFromReadable(newOffset));
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
/*!
Gets the current voice and sets its name.
*/
void CAMainWin::on_uiVoiceName_editingFinished()
{
CAVoice* voice = currentVoice();
if (voice && voice->name()!=uiVoiceName->text()) {
CACanorus::undo()->createUndoCommand(document(), tr("change voice name", "undo"));
CACanorus::undo()->pushUndoCommand();
voice->setName(uiVoiceName->text());
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Changes voice instrument.
*/
void CAMainWin::on_uiVoiceInstrument_activated(int index)
{
if (!currentVoice() || index < 0)
return;
CACanorus::undo()->createUndoCommand(document(), tr("change voice instrument", "undo"));
CACanorus::undo()->pushUndoCommand();
currentVoice()->setMidiProgram(static_cast<unsigned char>(index));
CACanorus::rebuildUI(document(), currentSheet());
}
void CAMainWin::on_uiInsertPlayable_toggled(bool checked)
{
if (checked) {
if (!uiVoiceNum->getRealValue())
uiVoiceNum->setRealValue(1); // select the first voice if none selected
musElementFactory()->setMusElementType(CAMusElement::Note);
setMode(InsertMode);
on_uiPlayableLength_toggled(uiPlayableLength->isChecked(), uiPlayableLength->currentId());
}
}
void CAMainWin::on_uiInsertSyllable_toggled(bool checked)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::Syllable);
setMode(InsertMode);
}
}
void CAMainWin::on_uiInsertFBM_toggled(bool checked)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::FiguredBassMark);
setMode(InsertMode);
}
}
void CAMainWin::on_uiInsertFM_toggled(bool checked)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::FunctionMark);
setMode(InsertMode);
}
}
void CAMainWin::on_uiInsertChordName_toggled(bool checked)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::ChordName);
setMode(InsertMode);
}
}
void CAMainWin::on_uiPlayableLength_toggled(bool, int buttonId)
{
// Read currently selected entry from tool button menu
CAPlayableLength length = CAPlayableLength(static_cast<CAPlayableLength::CAMusicLength>(buttonId));
if (mode() == InsertMode) {
// New note length type
musElementFactory()->setPlayableLength(length);
if (currentScoreView()) {
currentScoreView()->setShadowNoteLength(musElementFactory()->playableLength());
currentScoreView()->updateHelpers();
}
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change playable length", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAPlayable* p = dynamic_cast<CAPlayable*>(v->selection().at(i)->musElement());
if (p) {
CAMusElement* next = nullptr;
int oldLength = p->timeLength();
int newLength = CAPlayableLength::playableLengthToTimeLength(length);
if (p->musElementType() == CAMusElement::Note) { // change the length of the whole chord
QList<CANote*> chord = static_cast<CANote*>(p)->getChord();
next = p->voice()->next(chord.back());
for (int i = 0; i < chord.size(); i++) {
p->voice()->remove(chord[i]);
chord[i]->setPlayableLength(length);
chord[i]->calculateTimeLength();
}
p->voice()->insert(next, chord[0], false);
for (int i = 1; i < chord.size(); i++) {
p->voice()->insert(chord[0], chord[i], true);
}
} else if (p->musElementType() == CAMusElement::Rest) {
next = p->voice()->next(p);
p->voice()->remove(p);
p->setPlayableLength(length);
p->calculateTimeLength();
p->voice()->insert(next, p);
}
if (newLength < oldLength) { // insert rests, if the new length is shorter to keep consistency
QList<CARest*> rests = CARest::composeRests(oldLength - newLength, p->timeStart() + p->timeLength(), p->voice(), CARest::Normal);
for (int i = rests.size() - 1; i >= 0; i--) {
p->voice()->insert(next, rests[i]); // insert rests from shortest to longest
}
} else {
p->staff()->synchronizeVoices();
}
for (int j = 0; j < p->voice()->lyricsContextList().size(); j++) { // reposit syllables
p->voice()->lyricsContextList().at(j)->repositionElements();
}
}
}
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Function called when user types the text of the syllable or chord name.
The following behaviour is implemented:
- alphanumeric keys are pressed - writes text
- spacebar is pressed - creates the current syllable/chord name and jumps to the next syllable
- return is pressed - creates the current syllable/chord name and hides the edit widget
- left key is pressed - if cursorPosition()==0, jumps to the previous syllable/chord name
- right key is pressed - if cursorPosition()==length(), same as spacebar
- escape key is pressed - hides the edit widget and cancels any changes to syllable/chord name
*/
void CAMainWin::onTextEditKeyPressEvent(QKeyEvent* e)
{
if (!currentScoreView())
return;
CATextEdit* textEdit = static_cast<CATextEdit*>(sender());
CAScoreView* v = currentScoreView();
CAMusElement* elt = (v->selection().size() ? v->selection().front()->musElement() : nullptr);
if (!elt)
return;
switch (elt->musElementType()) {
case CAMusElement::Syllable:
case CAMusElement::ChordName: {
if (e->key() == Qt::Key_Space || e->key() == Qt::Key_Return || (e->key() == Qt::Key_Right && textEdit->cursorPosition() == textEdit->text().size()) || ((e->key() == Qt::Key_Left || e->key() == Qt::Key_Backspace) && textEdit->cursorPosition() == 0) || (elt->musElementType() == CAMusElement::Syllable && CACanorus::settings()->finaleLyricsBehaviour() && e->key() == Qt::Key_Minus)) {
// one of control keys were hit, create or edit syllable/chord name
confirmTextEdit(currentScoreView(), textEdit, elt);
CAMusElement* next = nullptr;
if (e->key() == Qt::Key_Space || e->key() == Qt::Key_Right || e->key() == Qt::Key_Return) {
// move to the right neighbor
next = elt->context()->next(elt);
} else if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Backspace) {
// move to the left neighbor
next = elt->context()->previous(elt);
} else if (e->key() == Qt::Key_Minus && elt->musElementType() == CAMusElement::Syllable) {
// move to the right neighbor + set hyphen
static_cast<CASyllable*>(elt)->setHyphenStart(true);
next = elt->context()->next(elt);
}
if (next) {
CADrawableMusElement* dNext = v->selectMElement(next);
v->createTextEdit(dNext);
if (e->key() == Qt::Key_Space || e->key() == Qt::Key_Right || e->key() == Qt::Key_Return) {
// edit widget cursor is at the end by default. go to the beginning, if moving to the right neighbor.
v->textEdit()->setCursorPosition(0);
}
if (dNext && (dNext->xPos() > v->worldX() + 0.85 * v->worldWidth())) {
v->setWorldX(dNext->xPos() - v->worldWidth() / 2, CACanorus::settings()->animatedScroll());
}
}
}
break;
}
case CAMusElement::Mark: {
// CAMark::Text and CAMark::BookMark
if (e->key() == Qt::Key_Return) {
confirmTextEdit(currentScoreView(), textEdit, elt);
}
break;
default:
break;
}
}
// escape key - cancel
if (e->key() == Qt::Key_Escape) {
v->removeTextEdit();
}
}
void CAMainWin::confirmTextEdit(CAScoreView* v, CATextEdit* textEdit, CAMusElement* elt)
{
switch (elt->musElementType()) {
case CAMusElement::Syllable: {
// create or edit syllable
CASyllable* syllable = static_cast<CASyllable*>(elt);
QString text = textEdit->text().simplified(); // remove any trailing whitespaces
bool hyphen = false;
if (text.right(1) == "-") {
hyphen = true;
text.chop(1);
}
bool melisma = false;
if (text.right(1) == "_") {
melisma = true;
text.chop(1);
}
CACanorus::undo()->createUndoCommand(document(), tr("lyrics edit", "undo"));
syllable->setText(text);
syllable->setHyphenStart(hyphen);
syllable->setMelismaStart(melisma);
v->removeTextEdit();
break;
}
case CAMusElement::Mark: {
CAMark* mark = static_cast<CAMark*>(elt);
CACanorus::undo()->createUndoCommand(document(), tr("text edit", "undo"));
if (mark->markType() == CAMark::Text) {
static_cast<CAText*>(mark)->setText(textEdit->text());
} else if (mark->markType() == CAMark::BookMark) {
static_cast<CABookMark*>(mark)->setText(textEdit->text());
}
v->removeTextEdit();
break;
}
case CAMusElement::ChordName: {
// create or edit chord name
CAChordName* cn = static_cast<CAChordName*>(elt);
CACanorus::undo()->createUndoCommand(document(), tr("chord name edit", "undo"));
QString text = textEdit->text().simplified(); // remove any trailing whitespaces
cn->importFromString(text);
_noteChecker.checkSheet(v->sheet());
v->removeTextEdit();
break;
}
case CAMusElement::Note:
case CAMusElement::Rest:
case CAMusElement::MidiNote:
case CAMusElement::Barline:
case CAMusElement::Clef:
case CAMusElement::TimeSignature:
case CAMusElement::KeySignature:
case CAMusElement::Slur:
case CAMusElement::Tuplet:
case CAMusElement::FunctionMark:
case CAMusElement::FiguredBassMark:
case CAMusElement::Undefined:
qDebug() << "Error: confirmTextEdit() called on element of type" << elt->musElementType();
break;
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
void CAMainWin::on_uiFBMNumber_toggled(bool checked, int buttonId)
{
if (!checked && !uiFBMAccs->isChecked()) {
uiFBMNumber->setChecked(true);
return;
}
if (mode() == InsertMode) {
if (checked) {
musElementFactory()->setFBMNumber(buttonId);
} else {
musElementFactory()->setFBMNumber(0);
}
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change figured bass", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFiguredBassMark* fbm = dynamic_cast<CAFiguredBassMark*>(v->selection().at(i)->musElement());
if (fbm) {
int number = static_cast<CADrawableFiguredBassNumber*>(v->selection().at(i))->number();
fbm->removeNumber(number);
if (uiFBMAccs->isChecked()) {
fbm->addNumber((checked ? (buttonId) : 0), uiFBMAccs->currentId() - 2);
} else {
fbm->addNumber((checked ? (buttonId) : 0));
}
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFBMAccs_toggled(bool checked, int buttonId)
{
if (!checked && !uiFBMNumber->isChecked()) {
uiFBMAccs->setChecked(true);
return;
}
if (mode() == InsertMode) {
if (checked) {
musElementFactory()->setFBMAccs(buttonId - 2);
musElementFactory()->setFBMAccsVisible(true);
} else {
musElementFactory()->setFBMAccsVisible(false);
}
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change figured bass", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFiguredBassMark* fbm = dynamic_cast<CAFiguredBassMark*>(v->selection().at(i)->musElement());
if (fbm) {
int number = static_cast<CADrawableFiguredBassNumber*>(v->selection().at(i))->number();
fbm->removeNumber(number);
if (checked) {
fbm->addNumber((uiFBMNumber->isChecked() ? (uiFBMNumber->currentId()) : 0), buttonId - 2);
} else {
fbm->addNumber((uiFBMNumber->isChecked() ? (uiFBMNumber->currentId()) : 0));
}
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFMFunction_toggled(bool, int buttonId)
{
if (mode() == InsertMode) {
musElementFactory()->setFMFunction(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
musElementFactory()->setFMFunctionMinor(buttonId < 0);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change function", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(v->selection().at(i)->musElement());
if (fm) {
fm->setFunction(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
fm->setMinor(buttonId < 0);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFMChordArea_toggled(bool, int buttonId)
{
if (mode() == InsertMode) {
musElementFactory()->setFMChordArea(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
musElementFactory()->setFMChordAreaMinor(buttonId < 0);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change chord area", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(v->selection().at(i)->musElement());
if (fm) {
fm->setChordArea(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
fm->setChordAreaMinor(buttonId < 0);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFMTonicDegree_toggled(bool, int buttonId)
{
if (mode() == InsertMode) {
musElementFactory()->setFMTonicDegree(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
musElementFactory()->setFMTonicDegreeMinor(buttonId < 0);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change tonic degree", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(v->selection().at(i)->musElement());
if (fm) {
fm->setTonicDegree(static_cast<CAFunctionMark::CAFunctionType>(buttonId * (buttonId < 0 ? -1 : 1)));
fm->setTonicDegreeMinor(buttonId < 0);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFMEllipse_toggled(bool checked)
{
if (mode() == InsertMode) {
musElementFactory()->setFMEllipse(checked);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("set/unset ellipse", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(v->selection().at(i)->musElement());
if (fm) {
fm->setEllipse(checked);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiSlurType_toggled(bool, int buttonId)
{
// remember previous muselement type so we can return to previous state after
CAMusElement::CAMusElementType prevMusEltType = musElementFactory()->musElementType();
// Read currently selected entry from tool button menu
CASlur::CASlurType slurType = static_cast<CASlur::CASlurType>(buttonId);
musElementFactory()->setMusElementType(CAMusElement::Slur);
// New clef type
musElementFactory()->setSlurType(slurType);
insertMusElementAt(QPoint(0, 0), currentScoreView()); // inserts a slur or tie and quits the insert mode
musElementFactory()->setMusElementType(prevMusEltType);
}
void CAMainWin::on_uiClefType_toggled(bool checked, int buttonId)
{
if (checked) {
// Read currently selected entry from tool button menu
CAClef::CAPredefinedClefType clefType = static_cast<CAClef::CAPredefinedClefType>(buttonId);
musElementFactory()->setMusElementType(CAMusElement::Clef);
// New clef type
musElementFactory()->setClef(clefType);
setMode(InsertMode);
}
}
void CAMainWin::on_uiMarkType_toggled(bool checked, int buttonId)
{
if (checked) {
CAMark::CAMarkType markType;
// Read currently selected entry from tool button menu
if (buttonId == CAMark::Ritardando * (-1)) {
markType = CAMark::Ritardando;
musElementFactory()->setRitardandoType(CARitardando::Accellerando);
} else if (buttonId == CAMark::Ritardando) {
markType = CAMark::Ritardando;
musElementFactory()->setRitardandoType(CARitardando::Ritardando);
} else if (buttonId == CAMark::Crescendo * (-1)) {
markType = CAMark::Crescendo;
musElementFactory()->setCrescendoType(CACrescendo::Decrescendo);
} else if (buttonId == CAMark::Crescendo) {
markType = CAMark::Crescendo;
musElementFactory()->setCrescendoType(CACrescendo::Crescendo);
} else {
markType = static_cast<CAMark::CAMarkType>(buttonId);
}
musElementFactory()->setMusElementType(CAMusElement::Mark);
// New mark type
musElementFactory()->setMarkType(markType);
setMode(InsertMode);
}
}
void CAMainWin::on_uiArticulationType_toggled(bool checked, int buttonId)
{
if (checked) {
// Read currently selected entry from tool button menu
CAArticulation::CAArticulationType type = static_cast<CAArticulation::CAArticulationType>(buttonId);
musElementFactory()->setMusElementType(CAMusElement::Mark);
// New mark type
musElementFactory()->setMarkType(CAMark::Articulation);
musElementFactory()->setArticulationType(type);
setMode(InsertMode);
}
}
void CAMainWin::on_uiTimeSigBeats_valueChanged(int beats)
{
if (mode() == InsertMode) {
musElementFactory()->setTimeSigBeats(beats);
if (uiTimeSigBeats->value() == 4 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(44);
else if (uiTimeSigBeats->value() == 3 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(34);
else if (uiTimeSigBeats->value() == 2 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(24);
else if (uiTimeSigBeats->value() == 2 && uiTimeSigBeat->value() == 2)
uiTimeSigType->setCurrentId(22);
else if (uiTimeSigBeats->value() == 3 && uiTimeSigBeat->value() == 8)
uiTimeSigType->setCurrentId(38);
else if (uiTimeSigBeats->value() == 6 && uiTimeSigBeat->value() == 8)
uiTimeSigType->setCurrentId(68);
else
uiTimeSigType->setCurrentId(0);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CATimeSignature* timeSig = dynamic_cast<CATimeSignature*>(v->selection().at(0)->musElement());
if (timeSig) {
timeSig->setBeats(beats);
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
void CAMainWin::on_uiTimeSigBeat_valueChanged(int beat)
{
if (mode() == InsertMode) {
musElementFactory()->setTimeSigBeat(beat);
if (uiTimeSigBeats->value() == 4 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(44);
else if (uiTimeSigBeats->value() == 3 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(34);
else if (uiTimeSigBeats->value() == 2 && uiTimeSigBeat->value() == 4)
uiTimeSigType->setCurrentId(24);
else if (uiTimeSigBeats->value() == 2 && uiTimeSigBeat->value() == 2)
uiTimeSigType->setCurrentId(22);
else if (uiTimeSigBeats->value() == 3 && uiTimeSigBeat->value() == 8)
uiTimeSigType->setCurrentId(38);
else if (uiTimeSigBeats->value() == 6 && uiTimeSigBeat->value() == 8)
uiTimeSigType->setCurrentId(68);
else
uiTimeSigType->setCurrentId(0);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CATimeSignature* timeSig = dynamic_cast<CATimeSignature*>(v->selection().at(0)->musElement());
if (timeSig) {
timeSig->setBeat(beat);
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
void CAMainWin::on_uiTimeSigType_toggled(bool checked, int buttonId)
{
if (checked) {
switch (buttonId) {
case 44:
uiTimeSigBeats->setValue(4);
uiTimeSigBeat->setValue(4);
break;
case 22:
uiTimeSigBeats->setValue(2);
uiTimeSigBeat->setValue(2);
break;
case 34:
uiTimeSigBeats->setValue(3);
uiTimeSigBeat->setValue(4);
break;
case 24:
uiTimeSigBeats->setValue(2);
uiTimeSigBeat->setValue(4);
break;
case 38:
uiTimeSigBeats->setValue(3);
uiTimeSigBeat->setValue(8);
break;
case 68:
uiTimeSigBeats->setValue(6);
uiTimeSigBeat->setValue(8);
break;
case 0:
break;
}
musElementFactory()->setTimeSigBeats(uiTimeSigBeats->value());
musElementFactory()->setTimeSigBeat(uiTimeSigBeat->value());
musElementFactory()->setMusElementType(CAMusElement::TimeSignature);
setMode(InsertMode);
}
}
void CAMainWin::on_uiTupletType_toggled(bool checked, int type)
{
if (checked) {
if (mode() == EditMode && currentScoreView()->selection().size() > 1) {
CACanorus::undo()->createUndoCommand(document(), tr("insert tuplet", "undo"));
QList<CAPlayable*> playableList;
bool wrongVoice = false; // all elements should belong to a single voice. If multiple voices detected, cancel the tuplet creation.
CAVoice* tupletVoice = nullptr;
for (int i = 0; i < currentScoreView()->selection().size(); i++) {
if (currentScoreView()->selection()[i]->musElement() && currentScoreView()->selection()[i]->musElement()->isPlayable()) {
playableList << static_cast<CAPlayable*>(currentScoreView()->selection()[i]->musElement());
if (!tupletVoice || static_cast<CAPlayable*>(currentScoreView()->selection()[i]->musElement())->voice() == tupletVoice) {
tupletVoice = static_cast<CAPlayable*>(currentScoreView()->selection()[i]->musElement())->voice();
} else {
wrongVoice = true;
break;
}
}
}
if (!wrongVoice) {
if (type == 0) {
new CATuplet(3, 2, playableList);
} else {
new CATuplet(uiTupletNumber->value(), uiTupletActualNumber->value(), playableList);
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
} else {
switch (type) {
case 0:
uiTupletNumber->setValue(3);
uiTupletActualNumber->setValue(2);
break;
}
}
}
updatePlayableToolBar();
}
void CAMainWin::on_uiTupletNumber_valueChanged(int value)
{
musElementFactory()->setTupletNumber(value);
}
void CAMainWin::on_uiTupletActualNumber_valueChanged(int value)
{
musElementFactory()->setTupletActualNumber(value);
}
void CAMainWin::on_uiBarlineType_toggled(bool checked, int buttonId)
{
if (checked) {
musElementFactory()->setMusElementType(CAMusElement::Barline);
musElementFactory()->setBarlineType(static_cast<CABarline::CABarlineType>(buttonId));
setMode(InsertMode);
}
}
/*!
Called when a user clicks "Commit" button in source View.
*/
void CAMainWin::sourceViewCommit(QString inputString)
{
CASourceView* v = static_cast<CASourceView*>(sender());
stopPlayback();
if (v->document()) {
// CanorusML document source
CACanorus::undo()->createUndoCommand(document(), tr("commit CanorusML source", "undo"));
clearUI(); // clear GUI before clearing the data part!
CADocument* oldDoc = document();
CACanorusMLImport open(inputString);
open.importDocument();
open.wait();
if (open.importedDocument()) {
CACanorus::undo()->replaceDocument(document(), open.importedDocument());
setDocument(open.importedDocument());
// TODO UX: Set previous voice, set previous context.
}
if (CACanorus::settings()->useNoteChecker()) {
for (int i = 0; i < document()->sheetList().size(); i++) {
_noteChecker.checkSheet(document()->sheetList()[i]);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document());
if (oldDoc) {
delete oldDoc;
}
} else if (v->voice()) {
// LilyPond voice source
CACanorus::undo()->createUndoCommand(document(), tr("commit LilyPond source", "undo"));
CALilyPondImport li(inputString);
CAVoice* oldVoice = v->voice();
QList<CAMusElement*> signList = oldVoice->getSignList();
for (int i = 0; i < signList.size(); i++)
oldVoice->remove(signList[i]); // removes signs from all voices
li.setTemplateVoice(oldVoice); // copy properties
li.importVoice();
li.wait();
CAVoice* newVoice = li.importedVoice();
int voiceNumber = oldVoice->voiceNumber();
oldVoice->staff()->removeVoice(oldVoice);
newVoice->staff()->insertVoice(voiceNumber - 1, newVoice);
newVoice->staff()->synchronizeVoices();
// FIXME any way to avoid this?
CAScoreView* scorevp;
for (CAView* vp : _viewList) {
if (vp->viewType() == CAView::ScoreView && (scorevp = static_cast<CAScoreView*>(vp))->selectedVoice() == oldVoice)
scorevp->setSelectedVoice(newVoice);
}
v->setVoice(newVoice);
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(newVoice->staff()->sheet());
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), newVoice->staff()->sheet());
setCurrentView(v);
// oldVoice must be cleaned *after* rebuildUI(), because of shadow notes referencing it!
delete oldVoice;
} else if (v->lyricsContext()) {
// LilyPond lyrics source
CACanorus::undo()->createUndoCommand(document(), tr("commit LilyPond source", "undo"));
CALilyPondImport li(inputString);
li.importLyricsContext();
li.wait();
CALyricsContext* newLc = li.importedLyricsContext();
CALyricsContext* oldLc = v->lyricsContext();
newLc->cloneLyricsContextProperties(oldLc);
if (newLc->associatedVoice()) {
newLc->associatedVoice()->removeLyricsContext(oldLc);
newLc->associatedVoice()->addLyricsContext(newLc);
}
newLc->sheet()->insertContextAfter(oldLc, newLc);
newLc->sheet()->removeContext(oldLc);
v->setLyricsContext(newLc);
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), v->lyricsContext()->sheet());
setCurrentView(v);
delete oldLc;
}
}
void CAMainWin::on_uiUsersGuide_triggered()
{
#ifdef QT_WEBENGINEWIDGETS_LIB
CACanorus::help()->showUsersGuide("playback", this);
#else
CACanorus::help()->showUsersGuide("playback");
#endif
}
void CAMainWin::on_uiAboutQt_triggered()
{
QMessageBox::aboutQt(this, tr("About Qt"));
}
void CAMainWin::on_uiAboutCanorus_triggered()
{
QString about = tr("<p><b>Canorus - The next generation music score editor</b></p>\
<p>Version %1<br>\
(C) 2006-2020 Canorus Development team. All rights reserved.<br>\
See the file AUTHORS for the list of Canorus developers<br><br>\
This program is licensed under the GNU General Public License (GPL).<br>\
See the file LICENSE.GPL for details.<br><br>\
Homepage: <a href=\"http://www.canorus.org\">http://www.canorus.org</a></p>")
.arg(CANORUS_VERSION);
#ifdef USE_PYTHON
about += "<p>" + tr("Canorus is compiled with Python support.");
#endif
QMessageBox::about(this, tr("About Canorus"), about);
}
void CAMainWin::on_uiSettings_triggered()
{
CASettingsDialog(CASettingsDialog::EditorSettings, this);
if (CACanorus::settings()->useNoteChecker()) {
for (int i = 0; i < document()->sheetList().size(); i++) {
_noteChecker.checkSheet(document()->sheetList()[i]);
}
} else {
for (int i = 0; i < document()->sheetList().size(); i++) {
document()->sheetList()[i]->clearNoteCheckerErrors();
}
}
CACanorus::rebuildUI();
}
void CAMainWin::on_uiMidiRecorder_triggered()
{
if (document()) {
std::shared_ptr<CAResource> myMidiFile = CAResourceCtl::createEmptyResource(tr("Recorded Midi file"), document(), CAResource::Sound);
if (_midiRecorderView) {
delete _midiRecorderView;
}
_midiRecorderView = new CAMidiRecorderView(new CAMidiRecorder(myMidiFile, CACanorus::midiDevice()), this);
addDockWidget(Qt::TopDockWidgetArea, _midiRecorderView);
_midiRecorderView->show();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiTranspose_triggered()
{
if (document()) {
_transposeView->show();
}
}
void CAMainWin::on_uiJumpTo_triggered()
{
if (document() && currentSheet()) {
_jumpToView->show();
}
}
void CAMainWin::on_uiLilyPondSource_triggered()
{
CAContext* context = currentContext();
if (!context)
return;
CASourceView* v = nullptr;
CAStaff* staff = currentStaff();
if (staff) {
int voiceNum = uiVoiceNum->getRealValue() - 1 < 0 ? 0 : uiVoiceNum->getRealValue() - 1;
CAVoice* voice = staff->voiceList()[voiceNum];
v = new CASourceView(voice, nullptr);
} else if (context->contextType() == CAContext::LyricsContext) {
v = new CASourceView(static_cast<CALyricsContext*>(context), nullptr);
}
initView(v);
currentViewContainer()->addView(v);
uiUnsplitAll->setEnabled(true);
uiCloseCurrentView->setEnabled(true);
}
/*!
Adds a new score View to default View container.
*/
void CAMainWin::on_uiScoreView_triggered()
{
CASheet* s = _sheetMap[currentViewContainer()];
if (currentViewContainer() && s) {
CAScoreView* v = new CAScoreView(s, nullptr);
initView(v);
currentViewContainer()->addView(v);
v->rebuild();
uiUnsplitAll->setEnabled(true);
uiCloseCurrentView->setEnabled(true);
}
}
/*!
Removes the sheet, all its contents and rebuilds the GUI.
*/
void CAMainWin::on_uiRemoveSheet_triggered()
{
stopPlayback();
CASheet* sheet = currentSheet();
if (sheet) {
CACanorus::undo()->createUndoCommand(document(), tr("deletion of the sheet", "undo"));
CACanorus::undo()->pushUndoCommand();
document()->removeSheet(currentSheet());
removeSheet(sheet);
delete sheet;
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Removes the sheet from the GUI and deletes the Views and View containers and tabs
pointing to the given \a sheet.
*/
void CAMainWin::removeSheet(CASheet* sheet)
{
CAViewContainer* vpc = _sheetMap.key(sheet);
_sheetMap.remove(vpc);
// remove tab
int idx = uiTabWidget->indexOf(vpc);
uiTabWidget->removeTab(idx);
delete vpc;
if (idx < uiTabWidget->count())
uiTabWidget->setCurrentIndex(idx);
setCurrentViewContainer(static_cast<CAViewContainer*>(uiTabWidget->currentWidget()));
setCurrentView(static_cast<CAViewContainer*>(uiTabWidget->currentWidget()) ? static_cast<CAViewContainer*>(uiTabWidget->currentWidget())->currentView() : nullptr);
// remove other Views pointing to the sheet
QList<CAView*> vpl = viewList();
for (int i = 0; i < vpl.size(); i++) {
switch (vpl[i]->viewType()) {
case CAView::ScoreView: {
if (static_cast<CAScoreView*>(vpl[i])->sheet() == sheet)
delete vpl[i];
break;
}
case CAView::SourceView: {
CASourceView* sv = static_cast<CASourceView*>(vpl[i]);
if (sv->voice() && sv->voice()->staff()->sheet() == sheet)
delete vpl[i];
else if (sv->lyricsContext() && sv->lyricsContext()->sheet() == sheet)
delete vpl[i];
break;
}
}
}
}
/*!
Brings up the properties dialog.
*/
void CAMainWin::on_uiDocumentProperties_triggered()
{
CAPropertiesDialog::documentProperties(document(), this);
}
void CAMainWin::on_uiSheetName_editingFinished()
{
CASheet* sheet = currentSheet();
if (sheet && sheet->name()!=uiSheetName->text()) {
CACanorus::undo()->createUndoCommand(document(), tr("change sheet name", "undo"));
CACanorus::undo()->pushUndoCommand();
sheet->setName(uiSheetName->text());
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Brings up properties dialog.
*/
void CAMainWin::on_uiSheetProperties_triggered()
{
CAPropertiesDialog::sheetProperties(currentSheet(), this);
}
/*!
Sets the current context name.
*/
void CAMainWin::on_uiContextName_editingFinished()
{
CAContext* context = currentContext();
if (context && context->name()!=uiContextName->text()) {
CACanorus::undo()->createUndoCommand(document(), tr("change context name", "undo"));
CACanorus::undo()->pushUndoCommand();
context->setName(uiContextName->text());
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Brings up the properties dialog.
*/
void CAMainWin::on_uiContextProperties_triggered()
{
CAPropertiesDialog::contextProperties(currentContext(), this);
}
/*!
Sets the stanza number of the current lyrics context.
*/
void CAMainWin::on_uiStanzaNumber_valueChanged(int stanzaNumber)
{
if (currentContext() && currentContext()->contextType() == CAContext::LyricsContext) {
CACanorus::undo()->createUndoCommand(document(), tr("change stanza number", "undo"));
if (static_cast<CALyricsContext*>(currentContext())->stanzaNumber() != stanzaNumber)
CACanorus::undo()->pushUndoCommand();
static_cast<CALyricsContext*>(currentContext())->setStanzaNumber(stanzaNumber);
}
}
/*!
Sets the associated voice of the current lyrics context.
*/
void CAMainWin::on_uiAssociatedVoice_activated(int idx)
{
if (idx != -1 && currentContext() && currentContext()->contextType() == CAContext::LyricsContext) {
CACanorus::undo()->createUndoCommand(document(), tr("change associated voice", "undo"));
if (static_cast<CALyricsContext*>(currentContext())->associatedVoice() != currentSheet()->voiceList().at(idx))
CACanorus::undo()->pushUndoCommand();
static_cast<CALyricsContext*>(currentContext())->setAssociatedVoice(currentSheet()->voiceList().at(idx));
CACanorus::rebuildUI(document(), currentSheet()); // needs a rebuild if lyrics contexts are to be moved
}
}
void CAMainWin::on_uiVoiceStemDirection_toggled(bool, int direction)
{
CAVoice* voice = currentVoice();
if (voice) {
CACanorus::undo()->createUndoCommand(document(), tr("change voice stem direction", "undo"));
if (voice->stemDirection() != static_cast<CANote::CAStemDirection>(direction))
CACanorus::undo()->pushUndoCommand();
CACanorus::undo()->pushUndoCommand();
voice->setStemDirection(static_cast<CANote::CAStemDirection>(direction));
CACanorus::rebuildUI(document(), currentSheet());
}
}
/*!
Sets the currently selected note stem direction if in insert/edit mode or the music elements factory note stem direction if in insert mode.
*/
void CAMainWin::on_uiNoteStemDirection_toggled(bool, int id)
{
CANote::CAStemDirection direction = static_cast<CANote::CAStemDirection>(id);
if (mode() == InsertMode)
musElementFactory()->setNoteStemDirection(direction);
else if (mode() == EditMode) {
CACanorus::undo()->createUndoCommand(document(), tr("change note stem direction", "undo"));
CAScoreView* v = currentScoreView();
bool changed = false;
for (int i = 0; v && i < v->selection().size(); i++) {
CANote* note = dynamic_cast<CANote*>(v->selection().at(i)->musElement());
if (note) {
note->setStemDirection(direction);
changed = true;
}
}
if (changed) {
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
/*!
Updates all the toolbars according to the current state of the main window.
*/
void CAMainWin::updateToolBars()
{
updateUndoRedoButtons();
updateInsertToolBar();
updateSheetToolBar();
updateContextToolBar();
updateVoiceToolBar();
updatePlayableToolBar();
_poKeySignatureUI->updateKeySigToolBar();
updateTimeSigToolBar();
updateClefToolBar();
updateFBMToolBar();
updateFMToolBar();
updateDynamicToolBar();
updateInstrumentToolBar();
updateTempoToolBar();
updateFermataToolBar();
updateRepeatMarkToolBar();
updateFingeringToolBar();
if (document())
uiNewSheet->setVisible(true);
else
uiNewSheet->setVisible(false);
}
/*!
Shows sheet tool bar if nothing selected. Otherwise hides it.
*/
void CAMainWin::updateSheetToolBar()
{
CAScoreView* v = currentScoreView();
if (document()) {
if (v) {
if (v->sheet() && v->selection().isEmpty() && (!v->currentContext())) {
// no track selected, show sheet actions
uiSheetName->setText(v->sheet()->name());
uiSheetName->setEnabled(true);
uiRemoveSheet->setVisible(true);
uiSheetProperties->setVisible(true);
uiSheetToolBar->show();
} else {
// other track or elements selected, hide sheet actions
uiSheetToolBar->hide();
}
} else {
// no sheet exist: hide everything except the new sheet button
uiSheetName->setEnabled(false);
uiRemoveSheet->setVisible(false);
uiSheetProperties->setVisible(false);
uiSheetToolBar->show();
}
} else {
// no document exists, hide sheet actions
uiSheetToolBar->hide();
}
}
/*!
Shows/Hides the Voice properties tool bar according to the currently selected context and updates its properties.
*/
void CAMainWin::updateVoiceToolBar()
{
CAContext* context = currentContext();
if (context && context->contextType() == CAContext::Staff && currentScoreView() && ((mode() == EditMode && currentScoreView()->selection().size() == 0) || (mode() == InsertMode && uiInsertPlayable->isChecked()))) {
CAStaff* staff = static_cast<CAStaff*>(context);
uiNewVoice->setVisible(true);
uiNewVoice->setEnabled(true);
if (staff->voiceList().size()) {
uiVoiceNum->setMax(staff->voiceList().size());
int voiceNr = uiVoiceNum->getRealValue();
if (currentVoice() && voiceNr) {
CAVoice* curVoice = (voiceNr <= staff->voiceList().size() ? staff->voiceList()[voiceNr - 1] : staff->voiceList()[0]);
uiVoiceName->setText(curVoice->name());
uiVoiceName->setEnabled(true);
uiVoiceInstrument->setEnabled(true);
uiVoiceInstrument->setCurrentIndex(currentVoice()->midiProgram());
uiRemoveVoice->setEnabled(true);
uiVoiceStemDirection->setCurrentId(curVoice->stemDirection());
uiVoiceStemDirection->setEnabled(true);
uiVoiceProperties->setEnabled(true);
} else {
uiVoiceName->setEnabled(false);
uiVoiceInstrument->setEnabled(false);
uiRemoveVoice->setEnabled(false);
uiVoiceStemDirection->setEnabled(false);
uiVoiceProperties->setEnabled(false);
}
}
uiVoiceToolBar->show();
} else {
uiNewVoice->setVisible(false);
uiVoiceToolBar->hide();
}
}
/*!
Shows/Hides context tool bar according to the selected context (if any) and hides/shows specific actions in the toolbar for the current context.
*/
void CAMainWin::updateContextToolBar()
{
CAContext* context = currentContext();
if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() == 0 && context) {
if (!uiInsertPlayable->isChecked())
uiContextToolBar->show();
switch (context->contextType()) {
case CAContext::Staff: {
uiStanzaNumberAction->setVisible(false);
uiAssociatedVoiceAction->setVisible(false);
break;
}
case CAContext::LyricsContext: {
CALyricsContext* c = static_cast<CALyricsContext*>(context);
uiStanzaNumber->setValue(c->stanzaNumber());
uiStanzaNumberAction->setVisible(true);
uiStanzaNumberAction->setEnabled(true);
uiAssociatedVoice->clear();
QList<CAVoice*> voiceList = currentSheet()->voiceList();
for (int i = 0; i < voiceList.count(); i++)
uiAssociatedVoice->addItem(voiceList[i]->name());
uiAssociatedVoice->setCurrentIndex(voiceList.indexOf(c->associatedVoice()));
uiAssociatedVoiceAction->setVisible(true);
uiAssociatedVoiceAction->setEnabled(true);
break;
}
case CAContext::FunctionMarkContext: {
uiStanzaNumberAction->setVisible(false);
uiAssociatedVoiceAction->setVisible(false);
break;
}
case CAContext::FiguredBassContext:
case CAContext::ChordNameContext: {
uiStanzaNumberAction->setVisible(false);
uiAssociatedVoiceAction->setVisible(false);
break;
}
}
uiContextName->setText(context->name());
} else {
uiContextToolBar->hide();
}
}
/*!
Shows/Hides music elements which cannot be placed in the selected context.
*/
void CAMainWin::updateInsertToolBar()
{
if (mode() == InsertMode) {
// Do not change any insert toolbar layout when in Insert mode. Otherwise the user couldn't leave the Insert mode,
// because the specific toggle button may be evicted.
return;
}
if (currentSheet()) {
uiNewContext->setVisible(true);
uiInsertToolBar->show();
CAContext* context = currentContext();
if (context) {
switch (context->contextType()) {
case CAContext::Staff:
// staff selected
uiInsertPlayable->setVisible(true);
uiSlurType->defaultAction()->setVisible(true);
uiSlurType->defaultAction()->setEnabled(true);
/// \todo This is needed in order for actions to hide?! -Matevz
//uiSlurType->setVisible(true);
uiInsertClef->setVisible(true); // menu
uiInsertBarline->setVisible(true); // menu
uiClefType->defaultAction()->setVisible(true);
uiClefType->defaultAction()->setEnabled(true);
uiTimeSigType->defaultAction()->setVisible(true);
uiTimeSigType->defaultAction()->setEnabled(true);
uiInsertKeySig->setVisible(true);
uiMarkType->defaultAction()->setVisible(true);
uiMarkType->defaultAction()->setEnabled(true);
uiArticulationType->defaultAction()->setVisible(true);
uiArticulationType->defaultAction()->setEnabled(true);
uiInsertTimeSig->setVisible(true);
uiBarlineType->defaultAction()->setVisible(true);
uiBarlineType->defaultAction()->setEnabled(true);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(false);
break;
case CAContext::FunctionMarkContext:
// function mark context selected
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(true);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(false);
break;
case CAContext::LyricsContext:
// lyrics context selected
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(true);
uiInsertChordName->setVisible(false);
break;
case CAContext::FiguredBassContext:
// lyrics context selected
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(true);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(false);
break;
case CAContext::ChordNameContext:
// chord name context selected
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(true);
break;
}
} else {
// no contexts selected
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(false);
}
} else {
uiInsertToolBar->hide();
uiNewContext->setVisible(false);
uiInsertPlayable->setVisible(false);
uiSlurType->defaultAction()->setVisible(false);
/// \todo This is needed in order for actions to hide?! -Matevz
//uiSlurType->setVisible(false);
uiInsertClef->setVisible(false); // menu
uiInsertBarline->setVisible(false); // menu
uiClefType->defaultAction()->setVisible(false);
uiTimeSigType->defaultAction()->setVisible(false);
uiInsertKeySig->setVisible(false);
uiMarkType->defaultAction()->setVisible(false);
uiArticulationType->defaultAction()->setVisible(false);
uiInsertTimeSig->setVisible(false);
uiBarlineType->defaultAction()->setVisible(false);
uiInsertFBM->setVisible(false);
uiInsertFM->setVisible(false);
uiInsertSyllable->setVisible(false);
uiInsertChordName->setVisible(false);
}
}
/*!
Show/Hides the playable tool bar and its properties according to the current state.
*/
void CAMainWin::updatePlayableToolBar()
{
if (uiInsertPlayable->isChecked() && mode() == InsertMode) {
uiPlayableLength->setCurrentId(musElementFactory()->playableLength().musicLength());
uiNoteStemDirection->setCurrentId(musElementFactory()->noteStemDirection());
uiTupletType->defaultAction()->setVisible(true);
if (uiTupletType->isChecked() && uiTupletType->currentId() == 1) {
uiTupletNumberAction->setVisible(true);
uiTupletInsteadOfAction->setVisible(true);
uiTupletActualNumberAction->setVisible(true);
} else {
uiTupletNumberAction->setVisible(false);
uiTupletInsteadOfAction->setVisible(false);
uiTupletActualNumberAction->setVisible(false);
}
uiHiddenRest->setEnabled(true);
uiHiddenRest->setChecked(musElementFactory()->restType() == CARest::Hidden);
uiPlayableToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAPlayable*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CAPlayable* playable = dynamic_cast<CAPlayable*>(v->selection().at(0)->musElement());
if (playable) {
uiPlayableLength->setCurrentId(playable->playableLength().musicLength());
if (playable->musElementType() == CAMusElement::Note) {
CANote* note = static_cast<CANote*>(playable);
uiNoteStemDirection->setCurrentId(note->stemDirection());
uiHiddenRest->setEnabled(false);
} else if (playable->musElementType() == CAMusElement::Rest) {
CARest* rest = static_cast<CARest*>(playable);
uiHiddenRest->setEnabled(true);
uiHiddenRest->setChecked(rest->restType() == CARest::Hidden);
}
uiPlayableToolBar->show();
} else {
uiPlayableToolBar->hide();
uiHiddenRest->setEnabled(false);
}
uiTupletType->defaultAction()->setVisible(false);
uiTupletNumberAction->setVisible(false);
uiTupletInsteadOfAction->setVisible(false);
uiTupletActualNumberAction->setVisible(false);
}
} else {
uiPlayableToolBar->hide();
}
}
/*!
Shows/Hides the time signature properties tool bar according to the current state.
*/
void CAMainWin::updateTimeSigToolBar()
{
if (uiTimeSigType->isChecked() && mode() == InsertMode) {
uiTimeSigBeats->setValue(musElementFactory()->timeSigBeats());
uiTimeSigBeat->setValue(musElementFactory()->timeSigBeat());
uiTimeSigToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CATimeSignature*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CATimeSignature* timeSig = dynamic_cast<CATimeSignature*>(v->selection().at(0)->musElement());
if (timeSig) {
uiTimeSigBeats->setValue(timeSig->beats());
uiTimeSigBeat->setValue(timeSig->beat());
uiTimeSigToolBar->show();
} else
uiTimeSigToolBar->hide();
}
} else
uiTimeSigToolBar->hide();
}
/*!
Shows/Hides the clef properties tool bar according to the current state.
*/
void CAMainWin::updateClefToolBar()
{
if (uiClefType->isChecked() && mode() == InsertMode) {
uiClefOffset->setValue(musElementFactory()->clefOffset());
uiClefToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAClef*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CAClef* clef = dynamic_cast<CAClef*>(v->selection().at(0)->musElement());
if (clef) {
uiClefOffset->setValue(CAClef::offsetToReadable(clef->offset()));
uiClefToolBar->show();
} else
uiClefToolBar->hide();
}
} else
uiClefToolBar->hide();
}
/*!
Shows/Hides the figured bass mark properties tool bar according to the current state.
*/
void CAMainWin::updateFBMToolBar()
{
if (uiInsertFBM->isChecked() && mode() == InsertMode) {
if (musElementFactory()->fbmNumber()) {
uiFBMNumber->setCurrentId(musElementFactory()->fbmNumber());
uiFBMNumber->setChecked(true);
} else {
uiFBMNumber->setChecked(false);
}
uiFBMAccs->setCurrentId(musElementFactory()->fbmAccs() + 2);
uiFBMAccs->setChecked(musElementFactory()->fbmAccsVisible());
uiFBMToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAFiguredBassMark*>(currentScoreView()->selection().at(0)->musElement())) {
CAFiguredBassMark* fbm = dynamic_cast<CAFiguredBassMark*>(currentScoreView()->selection().at(0)->musElement());
int number = static_cast<CADrawableFiguredBassNumber*>(currentScoreView()->selection().at(0))->number();
if (number) {
uiFBMNumber->setCurrentId(number);
uiFBMNumber->setChecked(true);
} else {
uiFBMNumber->setChecked(false);
}
if (fbm->accs().contains(number)) {
uiFBMAccs->setCurrentId(fbm->accs()[number] + 2);
uiFBMAccs->setChecked(true);
} else {
uiFBMAccs->setChecked(false);
}
uiFBMToolBar->show();
} else {
uiFBMToolBar->hide();
}
}
/*!
Shows/Hides the function mark properties tool bar according to the current state.
*/
void CAMainWin::updateFMToolBar()
{
if (uiInsertFM->isChecked() && mode() == InsertMode) {
uiFMFunction->setCurrentId(musElementFactory()->fmFunction() * (musElementFactory()->isFMFunctionMinor() ? -1 : 1));
uiFMChordArea->setCurrentId(musElementFactory()->fmChordArea() * (musElementFactory()->isFMChordAreaMinor() ? -1 : 1));
uiFMTonicDegree->setCurrentId(musElementFactory()->fmTonicDegree() * (musElementFactory()->isFMTonicDegreeMinor() ? -1 : 1));
uiFMEllipse->setChecked(musElementFactory()->isFMEllipse());
uiFMKeySig->setCurrentIndex((musElementFactory()->diatonicKeyNumberOfAccs() + 7) * 2 + ((musElementFactory()->diatonicKeyGender() == CADiatonicKey::Minor) ? 1 : 0));
uiFMToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAFunctionMark*>(currentScoreView()->selection().at(0)->musElement())) {
CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(currentScoreView()->selection().at(0)->musElement());
uiFMFunction->setCurrentId(fm->function() * (fm->isMinor() ? -1 : 1));
uiFMChordArea->setCurrentId(fm->chordArea() * (fm->isChordAreaMinor() ? -1 : 1));
uiFMTonicDegree->setCurrentId(fm->tonicDegree() * (fm->isTonicDegreeMinor() ? -1 : 1));
uiFMEllipse->setChecked(fm->isPartOfEllipse());
uiFMKeySig->setCurrentIndex(
uiFMKeySig->findData(
CADiatonicKey::diatonicKeyToString(fm->key())));
uiFMToolBar->show();
} else {
uiFMToolBar->hide();
}
}
/*!
Shows/Hides the dynamic marks properties tool bar according to the current state.
*/
void CAMainWin::updateDynamicToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::Dynamic && mode() == InsertMode) {
uiDynamicText->setCurrentId(CADynamic::dynamicTextFromString(musElementFactory()->dynamicText()));
uiDynamicVolume->setValue(musElementFactory()->dynamicVolume());
uiDynamicCustomText->setText(musElementFactory()->dynamicText());
uiDynamicToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CADynamic*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CADynamic* dynamic = dynamic_cast<CADynamic*>(v->selection().at(0)->musElement());
if (dynamic) {
uiDynamicText->setCurrentId(CADynamic::dynamicTextFromString(dynamic->text()));
uiDynamicVolume->setValue(dynamic->volume());
uiDynamicCustomText->setText(dynamic->text());
uiDynamicToolBar->show();
} else
uiDynamicToolBar->hide();
}
} else
uiDynamicToolBar->hide();
}
/*!
Shows/Hides the fermata properties tool bar according to the current state.
*/
void CAMainWin::updateFermataToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::Fermata && mode() == InsertMode) {
uiFermataType->setCurrentId(musElementFactory()->fermataType());
uiFermataToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAFermata*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CAFermata* f = dynamic_cast<CAFermata*>(v->selection().at(0)->musElement());
if (f) {
uiFermataType->setCurrentId(f->fermataType());
uiFermataToolBar->show();
} else
uiFermataToolBar->hide();
}
} else
uiFermataToolBar->hide();
}
/*!
Shows/Hides the repeat mark properties tool bar according to the current state.
*/
void CAMainWin::updateRepeatMarkToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::RepeatMark && mode() == InsertMode) {
if (musElementFactory()->repeatMarkType() == CARepeatMark::Volta)
uiRepeatMarkType->setCurrentId(musElementFactory()->repeatMarkVoltaNumber() * (-1) - 1);
else
uiRepeatMarkType->setCurrentId(musElementFactory()->repeatMarkType());
uiRepeatMarkToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CARepeatMark*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CARepeatMark* r = dynamic_cast<CARepeatMark*>(v->selection().at(0)->musElement());
if (r) {
if (r->repeatMarkType() == CARepeatMark::Volta)
uiRepeatMarkType->setCurrentId(r->voltaNumber() * (-1) - 1);
else
uiRepeatMarkType->setCurrentId(r->repeatMarkType());
uiRepeatMarkToolBar->show();
} else
uiRepeatMarkToolBar->hide();
}
} else
uiRepeatMarkToolBar->hide();
}
/*!
Shows/Hides the fingering properties tool bar according to the current state.
*/
void CAMainWin::updateFingeringToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::Fingering && mode() == InsertMode) {
uiFinger->setCurrentId(musElementFactory()->fingeringFinger());
uiFingeringOriginal->setChecked(musElementFactory()->isFingeringOriginal());
uiFingeringToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAFingering*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CAFingering* f = dynamic_cast<CAFingering*>(v->selection().at(0)->musElement());
if (f) {
uiFinger->setCurrentId(f->finger());
uiFingeringOriginal->setChecked(f->isOriginal());
uiFingeringToolBar->show();
} else
uiFingeringToolBar->hide();
}
} else
uiFingeringToolBar->hide();
}
/*!
Shows/Hides the tempo marks properties tool bar according to the current state.
*/
void CAMainWin::updateTempoToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::Tempo && mode() == InsertMode) {
uiTempoBeat->setCurrentId(musElementFactory()->tempoBeat().musicLength() * (musElementFactory()->tempoBeat().dotted() ? -1 : 1));
uiTempoBpm->setText(QString::number(musElementFactory()->tempoBpm()));
uiTempoToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CATempo*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CATempo* tempo = dynamic_cast<CATempo*>(v->selection().at(0)->musElement());
if (tempo) {
uiTempoBeat->setCurrentId(tempo->beat().musicLength() * (tempo->beat().dotted() ? -1 : 1));
uiTempoBpm->setText(QString::number(tempo->bpm()));
uiTempoToolBar->show();
} else
uiTempoToolBar->hide();
}
} else
uiTempoToolBar->hide();
}
/*!
Shows/Hides the instrument marks properties tool bar according to the current state.
*/
void CAMainWin::updateInstrumentToolBar()
{
if (uiMarkType->isChecked() && uiMarkType->currentId() == CAMark::InstrumentChange && mode() == InsertMode) {
uiInstrumentChange->setCurrentIndex(musElementFactory()->instrument());
uiInstrumentToolBar->show();
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size() && dynamic_cast<CAInstrumentChange*>(currentScoreView()->selection().at(0)->musElement())) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CAInstrumentChange* instrument = dynamic_cast<CAInstrumentChange*>(v->selection().at(0)->musElement());
if (instrument) {
uiInstrumentChange->setCurrentIndex(instrument->instrument());
uiInstrumentToolBar->show();
} else
uiInstrumentToolBar->hide();
}
} else
uiInstrumentToolBar->hide();
}
/*!
Action on Edit->Copy.
*/
void CAMainWin::on_uiCopy_triggered()
{
if (currentScoreView()) {
copySelection(currentScoreView());
}
}
/*!
Action on Edit->Cut.
*/
void CAMainWin::on_uiCut_triggered()
{
if (currentScoreView()) {
stopPlayback();
CACanorus::undo()->createUndoCommand(document(), tr("cut", "undo"));
copySelection(currentScoreView());
deleteSelection(currentScoreView(), false, true, false); // and don't make undo as we already make it
CACanorus::undo()->pushUndoCommand();
}
}
/*!
Action on Edit->Paste.
*/
void CAMainWin::on_uiPaste_triggered()
{
if (currentScoreView()) {
pasteAt(currentScoreView()->lastMousePressCoords(), currentScoreView());
}
}
/*!
Backend for Edit->Copy.
*/
void CAMainWin::copySelection(CAScoreView* v)
{
if (v->selection().size()) {
CASheet* currentSheet = v->sheet();
QHash<CAContext*, QList<CAMusElement*>> eltMap;
QList<CAContext*> contexts;
for (int i = 0; i < currentSheet->contextList().size(); i++)
contexts << nullptr;
for (CADrawableMusElement* drawable : v->selection()) {
CAMusElement* elt;
CAContext* context;
if (!(elt = drawable->musElement()) || !(context = elt->context()))
continue;
if (elt->musElementType() == CAMusElement::Mark || elt->musElementType() == CAMusElement::Tuplet || elt->musElementType() == CAMusElement::Slur)
continue; // marks are cloned together with their associated element, no need to clone them separately.
// tuplets and slurs cannot be inserted into a context or a voice
if (context->contextType() != CAContext::Staff && context->contextType() != CAContext::LyricsContext)
continue; // only these context types are impl'd. If we added anything else, we'd have old pointers in the context list.
eltMap[context] << elt;
int idx = currentSheet->contextList().indexOf(context);
contexts[idx] = context;
}
contexts.removeAll(nullptr);
// contexts now contains the contexts of the selected elements, in the correct order.
// Copy staff elements
QHash<CAVoice*, CAVoice*> voiceMap; // all voices in selection
for (int i = 0; i < contexts.size(); i++) {
CAContext* context = contexts[i];
if (context->contextType() != CAContext::Staff)
continue;
CAStaff* staff = static_cast<CAStaff*>(context);
CAStaff* newStaff = new CAStaff("", nullptr, staff->numberOfLines());
contexts[i] = newStaff;
QList<CAVoice*> voices;
for (int i = 0; i < staff->voiceList().size(); i++)
voices << nullptr;
// create voices
for (CAMusElement* elt : eltMap[context]) {
if (!elt->isPlayable())
continue;
CAVoice* voice = static_cast<CAPlayable*>(elt)->voice();
int idx = staff->voiceList().indexOf(voice);
if (!voices[idx])
voiceMap[voice] = voices[idx] = new CAVoice("", newStaff);
}
CAVoice* defaultVoice = nullptr; // for non-playable elements
for (CAVoice* voice : voices) {
if (voice) {
defaultVoice = voice;
break;
}
}
if (!defaultVoice)
defaultVoice = new CAVoice("", newStaff);
// future FIXME (also in pasteAt): tuplets across staves (when cross-staff beam are impl'd GUI-wise).
QHash<CATuplet*, QList<CAPlayable*>> tupletMap;
QHash<CASlur*, CANote*> slurMap; //FIXME cross-staff slurs, when the crash is fixed (try cutting one)
for (CAMusElement* elt : eltMap[context]) {
if (elt->isPlayable()) {
CAPlayable* pl = static_cast<CAPlayable*>(elt);
CAVoice* voice = pl->voice();
int idx = staff->voiceList().indexOf(voice);
bool addToChord = false;
int eltidx = eltMap[context].indexOf(elt);
CANote* note = (pl->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(pl) : nullptr;
if (note) {
CAMusElement* prev = nullptr;
for (int previdx = eltidx - 1; previdx >= 0; previdx--) {
if ((prev = eltMap[context][previdx]) && prev->musElementType() == CAMusElement::Note
&& pl->voice() == static_cast<CAPlayable*>(prev)->voice()) {
//CANote *prevNote = static_cast<CANote*>(prev);
addToChord = prev->timeStart() == note->timeStart();
break;
}
}
}
CAPlayable* cloned = pl->clone(voices[idx]);
voices[idx]->append(cloned, addToChord);
if (pl->tuplet()) {
tupletMap[pl->tuplet()] << cloned;
if (tupletMap[pl->tuplet()].size() == pl->tuplet()->noteList().size())
pl->tuplet()->clone(tupletMap[pl->tuplet()]);
}
if (note) {
QList<CASlur*> slurs;
slurs << note->tieStart() << note->tieEnd() << note->slurStart() << note->slurEnd() << note->phrasingSlurStart() << note->phrasingSlurEnd();
slurs.removeAll(nullptr);
for (CASlur* s : slurs) {
if (!slurMap.contains(s))
slurMap[s] = static_cast<CANote*>(cloned);
else {
CANote *noteStart = slurMap[s], *noteEnd = static_cast<CANote*>(cloned);
CASlur* newSlur = s->clone(noteStart->context(), noteStart, noteEnd);
switch (s->slurType()) {
case CASlur::TieType:
noteStart->setTieStart(newSlur);
noteEnd->setTieEnd(newSlur);
break;
case CASlur::SlurType:
noteStart->setSlurStart(newSlur);
noteEnd->setSlurEnd(newSlur);
break;
case CASlur::PhrasingSlurType:
noteStart->setPhrasingSlurStart(newSlur);
noteEnd->setPhrasingSlurEnd(newSlur);
break;
}
}
}
}
} else
defaultVoice->append(elt->clone(newStaff));
}
voices.removeAll(nullptr);
if (voices.isEmpty())
voices << defaultVoice;
//CAStaff *last = static_cast<CAStaff*>(currentSheet->contextList().last());
for (CAVoice* voice : voices)
newStaff->addVoice(voice);
}
// Copy lyrics
for (int i = 0; i < contexts.size(); i++) {
CAContext* context = contexts[i];
if (context->contextType() != CAContext::LyricsContext)
continue;
CALyricsContext* lc = static_cast<CALyricsContext*>(context);
CAVoice* associated = voiceMap[lc->associatedVoice()]; // init'd to 0 if map doesn't contain the voice.
CALyricsContext* newLc = new CALyricsContext("", 0 /*FIXME*/, associated);
contexts[i] = newLc;
for (CAMusElement* elt : eltMap[context])
newLc->addSyllable(static_cast<CASyllable*>(elt->clone(newLc)), false);
}
QApplication::clipboard()->setMimeData(new CAMimeData(contexts));
}
}
/*!
Delete action.
If \a deleteSyllables or \a deleteNotes is True, it completely removes the element (shift+del).
Otherwise it only replaces it with rest (del).
If \a doUndo is True, it also creates undo. doUndo should be False when cutting.
*/
void CAMainWin::deleteSelection(CAScoreView* v, bool deleteSyllables, bool deleteNotes, bool doUndo)
{
if (v->selection().size()) {
if (doUndo)
CACanorus::undo()->createUndoCommand(document(), tr("deletion of elements", "undo"));
QSet<CAMusElement*> musElemSet;
QHash<CAFiguredBassMark*, QList<int>> numbersToDelete;
for (int i = 0; i < v->selection().size(); i++) {
musElemSet << v->selection().at(i)->musElement();
// gather numbers to delete of figured bass numbers
if (dynamic_cast<CADrawableFiguredBassNumber*>(v->selection().at(i))) {
CAFiguredBassMark* fbm = static_cast<CAFiguredBassMark*>(v->selection().at(i)->musElement());
if (!numbersToDelete.contains(fbm)) {
numbersToDelete[fbm] = QList<int>();
}
numbersToDelete[fbm] << dynamic_cast<CADrawableFiguredBassNumber*>(v->selection().at(i))->number();
}
}
// cleans up the set - removes empty elements and elements which get deleted automatically (eg. slurs, if both notes are deleted, marks)
for (QSet<CAMusElement*>::iterator i = musElemSet.begin(); i != musElemSet.end();) {
if (!(*i) || ((*i)->musElementType() == CAMusElement::Slur && musElemSet.contains(static_cast<CASlur*>(*i)->noteStart())) || ((*i)->musElementType() == CAMusElement::Slur && musElemSet.contains(static_cast<CASlur*>(*i)->noteEnd())) || ((*i)->musElementType() == CAMusElement::Mark && musElemSet.contains(static_cast<CAMark*>(*i)->associatedElement()))) {
i = musElemSet.erase(i);
} else {
i++;
}
}
for (QSet<CAMusElement*>::const_iterator i = musElemSet.constBegin(); i != musElemSet.constEnd(); i++) {
if ((*i)->isPlayable()) {
CAPlayable* p = static_cast<CAPlayable*>(*i);
if ((p->musElementType() == CAMusElement::Rest) || (!static_cast<CANote*>(p)->isPartOfChord())) {
// find out the status of the rests in other voices
QList<CAPlayable*> chord = p->staff()->getChord(p->timeStart());
QList<CARest*> restsInOtherVoices;
// if deleting a rest, shift back by default
if (p->musElementType() == CAMusElement::Rest)
deleteNotes = true;
int chordIdx;
for (chordIdx = 0; chordIdx < chord.size(); chordIdx++) { // calculates chordIdx
if (chord[chordIdx]->voice() != p->voice()) {
CAPlayable* current = chord[chordIdx];
do {
if (current->musElementType() == CAMusElement::Rest)
restsInOtherVoices << static_cast<CARest*>(current);
else if (!musElemSet.contains(current)) {
deleteNotes = false; // note in other voice which is not going to be deleted, don't shift back
break;
}
// loop over following playables while they start before p ends. i.e., not shifting back in situations such as: << { c1 } \ { r4 r g g } >>.
} while ((current = current->voice()->nextPlayable(current->timeStart())) && (current->timeStart() < p->timeEnd()));
if (!current && restsInOtherVoices.size() && (restsInOtherVoices.back()->voice() != chord[chordIdx]->voice() || (restsInOtherVoices.back()->voice() == chord[chordIdx]->voice() && restsInOtherVoices.back()->timeEnd() < p->timeEnd()))) {
deleteNotes = false;
break;
}
}
}
if (!deleteNotes) {
// replace note with rest
QList<CARest*> rests = CARest::composeRests(CAPlayableLength::playableLengthToTimeLength(p->playableLength()), p->timeStart(), p->voice(), CARest::Normal);
for (int j = 0; j < rests.size(); j++)
p->voice()->insert(p, rests[j]);
for (int j = 0; j < p->voice()->lyricsContextList().size(); j++) { // remove syllables
CASyllable* removedSyllable = p->voice()->lyricsContextList().at(j)->syllableAtTimeStart(p->timeStart());
musElemSet.remove(removedSyllable); // only remove syllables from the selection
}
if (p->tuplet()) { // remove the note from tuplet and add a rest
CATuplet* tuplet = p->tuplet();
tuplet->removeNote(p);
p->setTuplet(nullptr);
for (int j = 0; j < rests.size(); j++) {
tuplet->addNote(rests[j]);
}
p->voice()->remove(p, true);
tuplet->assignTimes();
}
} else {
// Actually remove the note or rest and shift other elements back if only rests in other voices present.
// This is allowed, if only rests are present below the deleted element in other voices.
// Example - the most comprehensive deletion:
// When deleting a half note in the first voice and there are two half rests in the second voice sticking
// together just in the middle of our half note, the deletion is made in 3 steps:
// 1. Convert the two rests below the deleted element to one quarter rest before the element, one half rest
// just below the deleted element (its timeStart and timeLength are now equal to deleted elt) and one
// quarter rest after the deleted element.
// 2. Do step 1 for all other voices (we only have 2 voices in our case).
// 3. Delete the newly generated rest right below the element in other voices and do not shift back
// shared elements (shared elements are shifted back in the next step).
// 4. Delete the deleted element and shift back shared elements.
QList<CARest*> restRightBelowDeletedElement;
// remove any rests from other voices
for (int j = 0; j < restsInOtherVoices.size(); j++) {
// gather rests in the current voice
QList<CARest*> restsInCurVoice;
restsInCurVoice << restsInOtherVoices[j];
CAVoice* rVoice = restsInOtherVoices[j]->voice();
while ((++j < restsInOtherVoices.size()) && (restsInOtherVoices[j]->voice() == rVoice)) {
restsInCurVoice << restsInOtherVoices[j];
}
int firstTimeStart = restsInCurVoice.front()->timeStart();
int fullTimeLength = restsInCurVoice.back()->timeEnd() - restsInCurVoice.front()->timeStart();
int firstTimeLength = p->timeStart() - firstTimeStart;
CARest::CARestType firstRestType = restsInCurVoice.front()->restType();
CARest::CARestType lastRestType = restsInCurVoice.back()->restType();
CAMusElement* nextElt = rVoice->next(restsInCurVoice.back()); // needed later for insertion
// convert the rests
for (int k = 0; k < restsInCurVoice.size(); k++) {
if (restsInCurVoice[k]->tuplet()) {
musElemSet.remove(restsInCurVoice[k]->tuplet());
}
musElemSet.remove(restsInCurVoice[k]);
rVoice->remove(restsInCurVoice[k], true);
}
// insert the first rests
QList<CARest*> firstRests = CARest::composeRests(firstTimeLength, firstTimeStart, rVoice, firstRestType);
for (int k = 0; k < firstRests.size(); k++) {
rVoice->insert(nextElt, firstRests[k]);
}
// insert the rests below the element - needed to correctly update timeStart of shared elements
QList<CARest*> restsRightBelow = CARest::composeRests(p->timeLength(), firstTimeStart + firstTimeLength, rVoice, CARest::Normal);
for (int k = 0; k < restsRightBelow.size(); k++) {
rVoice->insert(nextElt, restsRightBelow[k]);
}
// insert the rests after the element
QList<CARest*> lastRests = CARest::composeRests(fullTimeLength - (firstTimeLength + p->timeLength()), firstTimeStart + firstTimeLength + p->timeLength(), rVoice, lastRestType);
for (int k = 0; k < lastRests.size(); k++) {
rVoice->insert(nextElt, lastRests[k]);
}
// delete the rests below the element
for (int k = 0; k < restsRightBelow.size(); k++) {
delete restsRightBelow[k]; // do not shift back shared elements
}
}
for (int j = 0; j < p->voice()->lyricsContextList().size(); j++) // delete and shift syllables
musElemSet.remove(p->voice()->lyricsContextList().at(j)->removeSyllableAtTimeStart(p->timeStart()));
if (p->tuplet()) { // remove the tuplet from selection, if any, because it's deleted in playable destructor
musElemSet.remove(p->tuplet());
}
}
}
// stop the playback before deleting the note
if (_playback && _playback->curPlaying().contains(p)) {
_playback->stopNow();
}
p->voice()->remove(p, true);
for (int j = 0; j < p->voice()->lyricsContextList().size(); j++) {
p->voice()->lyricsContextList().at(j)->repositionElements();
}
delete p;
} else if ((*i)->musElementType() == CAMusElement::Syllable) {
if (deleteSyllables) {
CALyricsContext* lc = static_cast<CALyricsContext*>((*i)->context());
(*i)->context()->remove(*i); // actually removes the syllable if SHIFT is pressed
lc->repositionElements();
} else {
static_cast<CASyllable*>(*i)->clear(); // only clears syllable's text
}
} else if ((*i)->musElementType() == CAMusElement::ChordName) {
if (deleteSyllables) {
CAChordNameContext* cc = static_cast<CAChordNameContext*>((*i)->context());
(*i)->context()->remove(*i); // actually removes the chord if SHIFT is pressed
cc->repositionElements();
} else {
static_cast<CAChordName*>(*i)->clear(); // only clears the chord pitch/modifiers
}
} else if ((*i)->musElementType() == CAMusElement::FiguredBassMark) {
CAFiguredBassMark* fbm = static_cast<CAFiguredBassMark*>(*i);
CAFiguredBassContext* fbc = static_cast<CAFiguredBassContext*>(fbm->context());
if (deleteSyllables && fbm->numbers().size() == numbersToDelete[fbm].size()) {
(*i)->context()->remove(*i); // actually removes the function if SHIFT is pressed
fbc->repositionElements();
} else {
for (int j = 0; j < numbersToDelete[fbm].size(); j++) {
fbm->removeNumber(numbersToDelete[fbm][j]);
}
}
} else if ((*i)->musElementType() == CAMusElement::FunctionMark) {
if (deleteSyllables) {
CAFunctionMarkContext* fmc = static_cast<CAFunctionMarkContext*>((*i)->context());
(*i)->context()->remove(*i); // actually removes the function if SHIFT is pressed
fmc->repositionElements();
} else {
static_cast<CAFunctionMark*>(*i)->clear(); // only clears the function
}
} else if ((*i)->musElementType() == CAMusElement::Mark) {
delete *i; // also removes itself from associated elements
} else if ((*i)->musElementType() == CAMusElement::Slur) {
delete *i; // also removes itself from associated elements
} else if ((*i)->musElementType() == CAMusElement::Tuplet) {
delete *i; // also removes itself from associated elements
} else {
(*i)->context()->remove(*i);
}
}
if (doUndo)
CACanorus::undo()->pushUndoCommand();
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(v->sheet());
}
v->clearSelection();
CACanorus::rebuildUI(document(), v->sheet());
}
}
/*!
Backend for Edit->Paste.
*/
void CAMainWin::pasteAt(const QPoint coords, CAScoreView* v)
{
if (QApplication::clipboard()->mimeData() && dynamic_cast<const CAMimeData*>(QApplication::clipboard()->mimeData()) && v->currentContext()) {
CACanorus::undo()->createUndoCommand(document(), tr("paste", "undo"));
CAContext* currentContext = v->currentContext()->context();
CASheet* currentSheet = currentContext->sheet();
QList<CAMusElement*> newEltList;
QList<CAContext*> contexts = static_cast<const CAMimeData*>(QApplication::clipboard()->mimeData())->contexts();
QHash<CAVoice*, CAVoice*> voiceMap; // MimeData -> paste
CAContext* insertAfter = nullptr;
for (CAContext* context : contexts) {
// create a new context if there isn't one of the right type.
// exception: if the context is a staff, skip lyrics contexts instead of inserting a staff before a lyrics context.
if (context->contextType() == CAContext::Staff) {
while (currentContext && currentContext->contextType() == CAContext::LyricsContext)
if (currentContext != currentSheet->contextList().last())
currentContext = currentSheet->contextList()[currentSheet->contextList().indexOf(currentContext) + 1];
else
currentContext = nullptr;
}
if (!currentContext || context->contextType() != currentContext->contextType()) {
CAContext* newContext = nullptr;
switch (context->contextType()) {
case CAContext::Staff: {
CAStaff /* * s = static_cast<CAStaff*>(context),*/* newStaff;
newContext = newStaff = new CAStaff(tr("Staff%1").arg(v->sheet()->staffList().size() + 1), currentSheet);
break;
}
case CAContext::LyricsContext: {
/* Two cases:
* - Some notes were copied together with the lyrics below them: in this case the linked voice would've already been pasted (as the context list is ordered top to bottom), so we find the new voice using voiceMap.
* - Lyrics were copied without the notes. If currentContext is a staff, we'll use the current voice. Otherwise lyrics will not be pasted.
*/
CAVoice* voice = voiceMap[static_cast<CALyricsContext*>(context)->associatedVoice()];
if (!voice && currentContext && currentContext->contextType() == CAContext::Staff)
voice = static_cast<CAStaff*>(currentContext)->voiceList()[(currentContext == v->currentContext()->context()) ? (uiVoiceNum->getRealValue() ? uiVoiceNum->getRealValue() - 1 : uiVoiceNum->getRealValue()) : 1]; // That is, if the currentContext is still the context that the user last clicked before pasting, use the current voice number. Otherwise, use the first voice.
if (!voice)
continue; // skipping lyrics - can't find a staff.
newContext = new CALyricsContext(tr("LyricsContext%1").arg(v->sheet()->contextList().size() + 1), 1, voice);
insertAfter = voice->staff();
break;
}
case CAContext::FunctionMarkContext: {
newContext = new CAFunctionMarkContext(tr("FunctionMarkContext%1").arg(v->sheet()->contextList().size() + 1), currentSheet);
break;
}
case CAContext::FiguredBassContext:
break;
case CAContext::ChordNameContext:
newContext = new CAChordNameContext(tr("ChordNameContext%1").arg(v->sheet()->contextList().size() + 1), currentSheet);
break;
}
if (insertAfter) {
currentSheet->insertContextAfter(insertAfter, newContext);
insertAfter = nullptr;
} else if (currentContext)
currentSheet->insertContextAfter(currentContext, newContext);
else
currentSheet->addContext(newContext);
currentContext = newContext;
}
if (context->contextType() == CAContext::Staff) {
CAStaff *staff = static_cast<CAStaff*>(currentContext), *cbstaff = static_cast<CAStaff*>(context);
int voice = uiVoiceNum->getRealValue() ? uiVoiceNum->getRealValue() - 1 : uiVoiceNum->getRealValue();
for (int i = staff->voiceList().size() - 1; i < voice + cbstaff->voiceList().size() - 1; i++) {
staff->addVoice();
}
for (int i = voice; i < voice + cbstaff->voiceList().size(); i++) {
int cbi = i - voice;
CADrawableMusElement* drawable = v->nearestRightElement(coords.x(), coords.y(), staff->voiceList()[i]);
voiceMap[cbstaff->voiceList()[cbi]] = staff->voiceList()[i];
CAMusElement* right = (drawable) ? drawable->musElement() : nullptr;
// Can't have playables between two notes linked by a tie. Remove the tie in this case.
// FIXME this should be the behavior for insert as well.
CAMusElement* leftPl = right;
while ((leftPl = staff->voiceList()[i]->previous(leftPl)) && !leftPl->isPlayable())
;
CANote* leftNote = (leftPl && leftPl->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(leftPl) : nullptr;
CASlur* tie = leftNote ? leftNote->tieStart() : nullptr;
if (tie) {
if (tie->noteEnd() && staff->voiceList()[i]->musElementList().contains(tie->noteEnd()))
// pasting between two tied notes - remove tie
delete tie; // resets notes' tieStart/tieEnd;
else {
// pasting after an "open" tie - if the first paste element is a note, connect them. Otherwise delete the tie.
int idx = 0;
for (; idx < cbstaff->voiceList()[cbi]->musElementList().size() && !cbstaff->voiceList()[cbi]->musElementList()[idx]->isPlayable(); idx++)
;
CAPlayable* first = (idx != cbstaff->voiceList()[cbi]->musElementList().size()) ? static_cast<CAPlayable*>(cbstaff->voiceList()[cbi]->musElementList()[idx]) : nullptr;
if (first && first->musElementType() == CAMusElement::Note)
static_cast<CANote*>(first)->setTieEnd(tie);
else
delete tie;
}
}
QHash<CATuplet*, QList<CAPlayable*>> tupletMap;
QHash<CASlur*, CANote*> slurMap;
for (CAMusElement* elt : cbstaff->voiceList()[cbi]->musElementList()) {
CAMusElement* cloned = (elt->isPlayable()) ? static_cast<CAPlayable*>(elt)->clone(staff->voiceList()[i]) : elt->clone(staff);
CANote* n = (elt->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(elt) : nullptr;
CAMusElement* prev = cbstaff->voiceList()[cbi]->previous(n);
CANote* prevNote = (prev && prev->musElementType() == CAMusElement::Note) ? static_cast<CANote*>(prev) : nullptr;
bool chord = n && prevNote && prevNote->timeStart() == n->timeStart();
if (n) {
QList<CASlur*> slurs;
slurs << n->tieStart() << n->tieEnd() << n->slurStart() << n->slurEnd() << n->phrasingSlurStart() << n->phrasingSlurEnd();
slurs.removeAll(nullptr);
for (CASlur* s : slurs) {
if (!slurMap.contains(s))
slurMap[s] = static_cast<CANote*>(cloned);
else {
CANote *noteStart = slurMap[s], *noteEnd = static_cast<CANote*>(cloned);
CASlur* newSlur = s->clone(noteStart->context(), noteStart, noteEnd);
switch (s->slurType()) {
case CASlur::TieType:
noteStart->setTieStart(newSlur);
noteEnd->setTieEnd(newSlur);
break;
case CASlur::SlurType:
noteStart->setSlurStart(newSlur);
noteEnd->setSlurEnd(newSlur);
break;
case CASlur::PhrasingSlurType:
noteStart->setPhrasingSlurStart(newSlur);
noteEnd->setPhrasingSlurEnd(newSlur);
break;
}
}
}
}
staff->voiceList()[i]->insert(chord ? newEltList.last() : right, cloned, chord);
newEltList << cloned;
if (elt->isPlayable()) {
CAPlayable* pl = static_cast<CAPlayable*>(elt);
if (pl->tuplet()) {
tupletMap[pl->tuplet()] << static_cast<CAPlayable*>(cloned);
if (tupletMap[pl->tuplet()].size() == pl->tuplet()->noteList().size())
pl->tuplet()->clone(tupletMap[pl->tuplet()]);
}
}
// FIXME duplicated from CAMusElementFactory::configureNote.
if (n && staff->voiceList()[i]->lastNote() != static_cast<CANote*>(cloned)) {
for (CALyricsContext* context : staff->voiceList()[i]->lyricsContextList())
context->insertEmptyElement(cloned->timeStart());
for (CAContext* context : currentSheet->contextList())
if (context->contextType() == CAContext::FunctionMarkContext)
static_cast<CAFunctionMarkContext*>(context)->insertEmptyElement(cloned->timeStart());
}
}
for (CALyricsContext* context : staff->voiceList()[i]->lyricsContextList())
context->repositionElements();
for (CAContext* context : currentSheet->contextList())
if (context->contextType() == CAContext::FunctionMarkContext)
static_cast<CAFunctionMarkContext*>(context)->repositionElements();
}
staff->synchronizeVoices();
} else {
/// \todo function mark copy&paste unimplemented
if (context->contextType() == CAContext::LyricsContext) {
CALyricsContext* lc = static_cast<CALyricsContext*>(context);
CALyricsContext* currentLc = static_cast<CALyricsContext*>(currentContext);
CADrawableMusElement* drawable = nullptr;
if (currentContext == v->currentContext()->context()) // pasting where the user has clicked
drawable = v->nearestRightElement(coords.x(), coords.y(), v->currentContext());
int offset = lc->syllableList()[0]->timeStart() - (drawable ? drawable->musElement()->timeStart() : 0);
// Add syllables until there are no more notes, [popping existing syllables on the right end?].
for (CASyllable* syl : lc->syllableList()) {
CASyllable* clone = syl->clone(currentLc);
clone->setTimeStart(clone->timeStart() - offset);
currentLc->addSyllable(clone, false);
newEltList << clone;
}
}
}
int idx = currentSheet->contextList().indexOf(currentContext);
currentContext = (idx + 1 < currentSheet->contextList().size()) ? currentSheet->contextList()[idx + 1] : nullptr;
}
if (CACanorus::settings()->useNoteChecker()) {
_noteChecker.checkSheet(currentSheet);
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet);
// select pasted elements
currentScoreView()->clearSelection();
for (int i = 0; i < newEltList.size(); i++)
currentScoreView()->addToSelection(newEltList[i]);
currentScoreView()->setLastMousePressCoordsAfter(newEltList);
currentScoreView()->repaint();
}
}
void CAMainWin::on_uiDynamicText_toggled(bool, int t)
{
if (t == CADynamic::Custom)
return;
QString text = CADynamic::dynamicTextToString(static_cast<CADynamic::CADynamicText>(t));
if (mode() == InsertMode) {
musElementFactory()->setDynamicText(text);
uiDynamicCustomText->setText(text);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CADynamic* dynamic = dynamic_cast<CADynamic*>(v->selection().at(0)->musElement());
if (dynamic) {
dynamic->setText(text);
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
void CAMainWin::on_uiDynamicVolume_valueChanged(int vol)
{
if (mode() == InsertMode) {
musElementFactory()->setDynamicVolume(vol);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CADynamic* dynamic = dynamic_cast<CADynamic*>(v->selection().at(0)->musElement());
if (dynamic) {
dynamic->setVolume(vol);
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
void CAMainWin::on_uiDynamicCustomText_editingFinished()
{
QString text = uiDynamicCustomText->text();
CADynamic::CADynamicText t = CADynamic::dynamicTextFromString(text);
uiDynamicText->setCurrentId(t);
if (mode() == InsertMode) {
musElementFactory()->setDynamicText(text);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
if (v && v->selection().size()) {
CADynamic* dynamic = dynamic_cast<CADynamic*>(v->selection().at(0)->musElement());
if (dynamic && dynamic->text()!=text) {
CACanorus::undo()->createUndoCommand(document(), tr("change dynamic text", "undo"));
dynamic->setText(text);
CACanorus::rebuildUI(document(), currentSheet());
}
}
}
}
void CAMainWin::on_uiInstrumentChange_activated(int index)
{
if (mode() == InsertMode) {
musElementFactory()->setInstrument(index);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change fermata type", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAInstrumentChange* instrument = dynamic_cast<CAInstrumentChange*>(v->selection().at(i)->musElement());
if (instrument) {
instrument->setInstrument(index);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFermataType_toggled(bool, int t)
{
CAFermata::CAFermataType type = static_cast<CAFermata::CAFermataType>(t);
if (mode() == InsertMode) {
musElementFactory()->setFermataType(type);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change fermata type", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFermata* fm = dynamic_cast<CAFermata*>(v->selection().at(i)->musElement());
if (fm) {
fm->setFermataType(type);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFinger_toggled(bool, int t)
{
CAFingering::CAFingerNumber type = static_cast<CAFingering::CAFingerNumber>(t);
if (mode() == InsertMode) {
musElementFactory()->setFingeringFinger(type);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change finger", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFingering* f = dynamic_cast<CAFingering*>(v->selection().at(i)->musElement());
if (f) {
f->setFinger(type);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiFingeringOriginal_toggled(bool checked)
{
if (mode() == InsertMode) {
musElementFactory()->setFingeringOriginal(checked);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change finger original property", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CAFingering* f = dynamic_cast<CAFingering*>(v->selection().at(i)->musElement());
if (f) {
f->setOriginal(checked);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiRepeatMarkType_toggled(bool, int t)
{
CARepeatMark::CARepeatMarkType type;
int voltaNumber;
if (t >= 0) {
type = static_cast<CARepeatMark::CARepeatMarkType>(t);
voltaNumber = 0;
} else {
type = CARepeatMark::Volta;
voltaNumber = t * (-1) - 1;
}
if (mode() == InsertMode) {
musElementFactory()->setRepeatMarkType(type);
musElementFactory()->setRepeatMarkVoltaNumber(voltaNumber);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change repeat mark", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CARepeatMark* r = dynamic_cast<CARepeatMark*>(v->selection().at(i)->musElement());
if (r) {
r->setRepeatMarkType(type);
r->setVoltaNumber(voltaNumber);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiTempoBeat_toggled(bool, int t)
{
CAPlayableLength length = CAPlayableLength(static_cast<CAPlayableLength::CAMusicLength>(t < 0 ? t * (-1) : t), t < 0 ? 1 : 0);
if (mode() == InsertMode) {
musElementFactory()->setTempoBeat(length);
} else if (mode() == EditMode && currentScoreView() && currentScoreView()->selection().size()) {
CAScoreView* v = currentScoreView();
CACanorus::undo()->createUndoCommand(document(), tr("change tempo beat", "undo"));
for (int i = 0; i < v->selection().size(); i++) {
CATempo* tempo = dynamic_cast<CATempo*>(v->selection().at(i)->musElement());
if (tempo) {
tempo->setBeat(length);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiTempoBpm_editingFinished()
{
QString text = uiTempoBpm->text();
int bpm = text.toInt();
if (mode() == InsertMode) {
musElementFactory()->setTempoBpm(bpm);
} else if (mode() == EditMode) {
CAScoreView* v = currentScoreView();
bool undoDone = false;
for (int i = 0; i < v->selection().size(); i++) {
CATempo* tempo = dynamic_cast<CATempo*>(v->selection().at(i)->musElement());
if (tempo && tempo->bpm()!=bpm) {
if (!undoDone) {
CACanorus::undo()->createUndoCommand(document(), tr("change tempo bpm", "undo"));
undoDone = true;
}
tempo->setBpm(bpm);
}
}
CACanorus::undo()->pushUndoCommand();
CACanorus::rebuildUI(document(), currentSheet());
}
}
void CAMainWin::on_uiOpenRecent_aboutToShow()
{
while (uiOpenRecent->actions().size())
delete uiOpenRecent->actions().at(0);
for (int i = 0; i < CACanorus::recentDocumentList().size(); i++) {
QAction* a = new QAction(CACanorus::recentDocumentList()[i], this);
uiOpenRecent->addAction(a);
connect(a, SIGNAL(triggered()), this, SLOT(onUiOpenRecentDocumentTriggered()));
}
}
void CAMainWin::onUiOpenRecentDocumentTriggered()
{
if (!handleUnsavedChanges()) {
return;
}
bool success = openDocument(CACanorus::recentDocumentList().at(
uiOpenRecent->actions().indexOf(static_cast<QAction*>(sender()))));
if (!success) {
CACanorus::removeRecentDocument(CACanorus::recentDocumentList().at(
uiOpenRecent->actions().indexOf(static_cast<QAction*>(sender()))));
}
}
/*!
Immediately plays the notes. This is usually called when inserting
new notes or changing the pitch of existing notes.
\sa CASettings::_playInsertedNotes
*/
void CAMainWin::playImmediately(QList<CAMusElement*> elements)
{
if (!_playback) {
_playback = new CAPlayback(CACanorus::midiDevice());
connect(_playback, SIGNAL(playbackFinished()), this, SLOT(playbackFinished()));
}
_playback->playImmediately(elements, CACanorus::settings()->midiOutPort());
}
/*!
\var CADocument *CAMainWin::_document
Pointer to the main window's document it represents.
Null if no document opened.
\sa document()
*/
/*!
\var CAMode CAMainWin::_mode
Main window's current mode (Select mode, Edit mode, Playback mode, Insert mode etc.).
\sa CAMode, mode(), setMode()
*/
/*!
\var QList<CAView*> CAMainWin::_viewList
List of all available Views for any sheet in this main window.
*/
/*!
\var CAView* CACanorus::_currentView
Currently active View. Only one View per main window can be active.
*/
/*!
\var CAView* CAMainWin::_playbackView
View needed to be updated when playback is active.
*/
/*!
\var QTimer* CACanorus::_repaintTimer
Used when playback is active to repaint the playback View.
\todo View should be repainted only when needed, not constantly as now. This should result in much less resource hunger.
*/
/*!
\var CAMusElementFactory *CACanorus::_musElementFactory
Factory for creating/configuring music elements before actually placing them.
*/
/*!
\var bool CAMainWin::_rebuildUILock
Lock to avoid recursive rebuilds of the GUI Views.
*/
| 267,725
|
C++
|
.cpp
| 5,563
| 38.624483
| 392
| 0.620386
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,398
|
propertiesdialog.cpp
|
canorusmusic_canorus/src/ui/propertiesdialog.cpp
|
/*!
Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QDate>
#include <QDateTime>
#include <QHeaderView> // needed to hide header widget from document tree
#include <QTreeWidgetItem>
#include "ui/propertiesdialog.h"
#include "canorus.h"
#include "core/undo.h"
#include "score/chordnamecontext.h"
#include "score/document.h"
#include "score/functionmarkcontext.h"
#include "score/lyricscontext.h"
#include "score/sheet.h"
#include "score/staff.h"
#include "score/voice.h"
/*!
\class CAPropertiesDialog
\brief Advanced Document, Sheet, Staff etc. properties
This dialog offers changing all the settings for Canorus objects. It is similar to CASettingsDialog.
On the left it shows you a tree widget view of the current document and allows you to select
one of the objects and sub-objects. On the right, the object properties are shown. Changes are
managed using Ok, Apply and Cancel buttons.
To use this dialog, call one of the static methods documentProperties(), sheetProperties(), contextProperties()
or voiceProperties() and pass the current document, sheet, context or voice. Methods will generate and show
the dialog and delete it in the end.
Actual objects properties widgets (properties widget for document, sheet etc.) are stored inside *.ui files.
*/
CAPropertiesDialog::CAPropertiesDialog(CADocument* doc, QWidget* parent)
: QDialog(parent)
{
_document = doc;
Ui::uiPropertiesDialog::setupUi(this);
uiDocumentTree->header()->hide();
buildTree();
setWindowFlags(Qt::Window);
}
CAPropertiesDialog::~CAPropertiesDialog()
{
}
/*!
Fills the content of the document tree on the left.
Tree always shows the whole Document structure.
*/
void CAPropertiesDialog::buildTree()
{
QWidget* w = nullptr;
// get current item
QTreeWidgetItem* curItem = uiDocumentTree->currentItem();
CADocument* curDocument = nullptr;
CASheet* curSheet = nullptr;
CAContext* curContext = nullptr;
CAVoice* curVoice = nullptr;
if (curItem) {
if (_documentItem == curItem)
curDocument = _document;
else if (_sheetItem.contains(curItem))
curSheet = _sheetItem[curItem];
else if (_contextItem.contains(curItem))
curContext = _contextItem[curItem];
else if (_voiceItem.contains(curItem))
curVoice = _voiceItem[curItem];
}
QTreeWidgetItem* docItem = nullptr;
uiDocumentTree->clear();
_documentItem = nullptr;
_sheetItem.clear();
_contextItem.clear();
_voiceItem.clear();
if (_document) {
w = new CADocumentProperties(_document, this);
_documentPropertiesWidget = w;
uiPropertiesWidget->addWidget(w);
updateDocumentProperties(_document);
docItem = new QTreeWidgetItem(uiDocumentTree);
docItem->setText(0, tr("Document"));
docItem->setIcon(0, QIcon("images:document/document.svg"));
_documentItem = docItem;
for (int i = 0; i < _document->sheetList().size(); i++) {
w = new CASheetProperties(this);
_sheetPropertiesWidget[_document->sheetList()[i]] = w;
uiPropertiesWidget->addWidget(w);
updateSheetProperties(_document->sheetList()[i]);
QTreeWidgetItem* sheetItem = nullptr;
sheetItem = new QTreeWidgetItem(docItem);
sheetItem->setText(0, _document->sheetList()[i]->name());
sheetItem->setIcon(0, QIcon("images:document/sheet.svg"));
_sheetItem[sheetItem] = _document->sheetList()[i];
for (int j = 0; j < _document->sheetList()[i]->contextList().size(); j++) {
QTreeWidgetItem* contextItem = nullptr;
contextItem = new QTreeWidgetItem(sheetItem);
contextItem->setText(0, _document->sheetList()[i]->contextList()[j]->name());
_contextItem[contextItem] = _document->sheetList()[i]->contextList()[j];
switch (_document->sheetList()[i]->contextList()[j]->contextType()) {
case CAContext::Staff: {
contextItem->setIcon(0, QIcon("images:document/staff.svg"));
w = new CAStaffProperties(this);
uiPropertiesWidget->addWidget(w);
_contextPropertiesWidget[_document->sheetList()[i]->contextList()[j]] = w;
CAStaff* s = static_cast<CAStaff*>(_document->sheetList()[i]->contextList()[j]);
updateStaffProperties(s);
for (int k = 0; k < s->voiceList().size(); k++) {
QWidget* v = new CAVoiceProperties(this);
uiPropertiesWidget->addWidget(v);
_voicePropertiesWidget[s->voiceList()[k]] = v;
updateVoiceProperties(s->voiceList()[k]);
QTreeWidgetItem* voiceItem = nullptr;
voiceItem = new QTreeWidgetItem(contextItem);
voiceItem->setText(0, s->voiceList()[k]->name());
voiceItem->setIcon(0, QIcon("images:document/voice.svg"));
_voiceItem[voiceItem] = s->voiceList()[k];
}
break;
}
case CAContext::LyricsContext: {
contextItem->setIcon(0, QIcon("images:document/lyricscontext.svg"));
w = new CALyricsContextProperties(this);
uiPropertiesWidget->addWidget(w);
_contextPropertiesWidget[_document->sheetList()[i]->contextList()[j]] = w;
updateLyricsContextProperties(static_cast<CALyricsContext*>(_document->sheetList()[i]->contextList()[j]));
break;
}
case CAContext::FunctionMarkContext: {
contextItem->setIcon(0, QIcon("images:document/fmcontext.svg"));
w = new CAFunctionMarkContextProperties(this);
uiPropertiesWidget->addWidget(w);
_contextPropertiesWidget[_document->sheetList()[i]->contextList()[j]] = w;
updateFunctionMarkContextProperties(static_cast<CAFunctionMarkContext*>(_document->sheetList()[i]->contextList()[j]));
break;
}
case CAContext::ChordNameContext: {
contextItem->setIcon(0, QIcon("images:document/chordnamecontext.svg"));
w = new CAChordNameContextProperties(this);
uiPropertiesWidget->addWidget(w);
_contextPropertiesWidget[_document->sheetList()[i]->contextList()[j]] = w;
updateChordNameContextProperties(static_cast<CAChordNameContext*>(_document->sheetList()[i]->contextList()[j]));
break;
}
case CAContext::FiguredBassContext: {
break;
}
}
}
}
uiDocumentTree->addTopLevelItem(docItem);
uiDocumentTree->expandAll();
}
// updates to the current item
if (curItem) {
if (curDocument)
uiDocumentTree->setCurrentItem(_documentItem);
else if (curSheet)
uiDocumentTree->setCurrentItem(_sheetItem.key(curSheet));
else if (curContext)
uiDocumentTree->setCurrentItem(_contextItem.key(curContext));
else if (curVoice)
uiDocumentTree->setCurrentItem(_voiceItem.key(curVoice));
}
}
void CAPropertiesDialog::documentProperties(CADocument* doc, QWidget* parent)
{
if (doc) {
CAPropertiesDialog pd(doc, parent);
pd.uiDocumentTree->setCurrentItem(pd.documentItem());
pd.exec();
}
}
void CAPropertiesDialog::sheetProperties(CASheet* sheet, QWidget* parent)
{
if (sheet && sheet->document()) {
CAPropertiesDialog pd(sheet->document(), parent);
pd.uiDocumentTree->setCurrentItem(pd.sheetItem().key(sheet));
pd.exec();
}
}
void CAPropertiesDialog::contextProperties(CAContext* context, QWidget* parent)
{
if (context && context->sheet() && context->sheet()->document()) {
CAPropertiesDialog pd(context->sheet()->document(), parent);
pd.uiDocumentTree->setCurrentItem(pd.contextItem().key(context));
pd.exec();
}
}
void CAPropertiesDialog::voiceProperties(CAVoice* voice, QWidget* parent)
{
if (voice && voice->staff() && voice->staff()->sheet() && voice->staff()->sheet()->document()) {
CAPropertiesDialog pd(voice->staff()->sheet()->document(), parent);
pd.uiDocumentTree->setCurrentItem(pd.voiceItem().key(voice));
pd.exec();
}
}
void CADocumentProperties::on_uiComposer_editingFinished()
{
QString curText = uiCopyright->currentText();
uiCopyright->clear();
QString startMsg = "(C) ";
int yearStart = _document->dateCreated().date().year();
int yearCur = QDate::currentDate().year();
if (yearStart && yearStart != yearCur)
startMsg += QString::number(yearStart) + "-";
startMsg += QString::number(yearCur);
if (uiComposer->text().size())
startMsg += " " + uiComposer->text() + ",";
uiCopyright->addItem(startMsg + " " + tr("CC, Some rights reserved", "copyright"));
uiCopyright->addItem(startMsg + " " + tr("Public domain", "copyright"));
uiCopyright->addItem(startMsg + " " + tr("All rights reserved", "copyright"));
uiCopyright->setEditText(curText);
}
void CAPropertiesDialog::on_uiDocumentTree_currentItemChanged(QTreeWidgetItem* cur, QTreeWidgetItem*)
{
if (!cur)
return;
uiElementName->setText(cur->text(0));
if (_documentItem == cur) {
uiPropertiesWidget->setCurrentWidget(_documentPropertiesWidget);
// update uiUp/uiDown buttons
uiUp->setEnabled(false);
uiDown->setEnabled(false);
} else if (_sheetItem.contains(cur)) {
uiPropertiesWidget->setCurrentWidget(_sheetPropertiesWidget[_sheetItem[cur]]);
// update uiUp/uiDown buttons
uiUp->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) > 0)
uiUp->setEnabled(true);
uiDown->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) < cur->parent()->childCount() - 1)
uiDown->setEnabled(true);
} else if (_contextItem.contains(cur)) {
uiPropertiesWidget->setCurrentWidget(_contextPropertiesWidget[_contextItem[cur]]);
// update uiUp/uiDown buttons
uiUp->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) > 0) // context has another context above
uiUp->setEnabled(true);
uiDown->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) < cur->parent()->childCount() - 1) // context has another context below
uiDown->setEnabled(true);
} else if (_voiceItem.contains(cur)) {
uiPropertiesWidget->setCurrentWidget(_voicePropertiesWidget[_voiceItem[cur]]);
// update uiUp/uiDown buttons
uiUp->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) > 0) // voice has another voice above
uiUp->setEnabled(true);
uiDown->setEnabled(false);
if (cur->parent()->childCount() > 1 && cur->parent()->indexOfChild(cur) < cur->parent()->childCount() - 1) // voice has another voice below
uiDown->setEnabled(true);
}
}
void CAPropertiesDialog::on_uiButtonBox_clicked(QAbstractButton* button)
{
if (uiButtonBox->standardButton(button) == QDialogButtonBox::Ok) {
applyProperties();
hide();
} else if (uiButtonBox->standardButton(button) == QDialogButtonBox::Cancel) {
hide();
} else if (uiButtonBox->standardButton(button) == QDialogButtonBox::Apply) {
applyProperties();
}
}
/*!
Called when "Apply" button is clicked.
*/
void CAPropertiesDialog::applyProperties()
{
CACanorus::undo()->createUndoCommand(_document, tr("apply properties", "undo"));
CACanorus::undo()->pushUndoCommand();
createDocumentFromTree();
// store Document properties
CADocumentProperties* dp = static_cast<CADocumentProperties*>(_documentPropertiesWidget);
_document->setTitle(dp->uiTitle->text());
_document->setSubtitle(dp->uiSubtitle->text());
_document->setComposer(dp->uiComposer->text());
_document->setArranger(dp->uiArranger->text());
_document->setPoet(dp->uiPoet->text());
_document->setTextTranslator(dp->uiTextTranslator->text());
_document->setDedication(dp->uiDedication->text());
_document->setCopyright(dp->uiCopyright->currentText());
_document->setComments(dp->uiComments->toPlainText());
// store Context properties
for (int i = 0; i < _contextPropertiesWidget.keys().size(); i++) {
CAContext* c = _contextPropertiesWidget.keys().at(i);
switch (c->contextType()) {
case CAContext::Staff: {
CAStaff* staff = static_cast<CAStaff*>(c);
CAStaffProperties* sp = static_cast<CAStaffProperties*>(_contextPropertiesWidget[staff]);
staff->setNumberOfLines(sp->uiNumberOfLines->value());
break;
}
case CAContext::LyricsContext: {
break;
}
case CAContext::FunctionMarkContext: {
break;
}
case CAContext::FiguredBassContext:
case CAContext::ChordNameContext:
break;
}
}
// store Voice properties
for (int i = 0; i < _voicePropertiesWidget.keys().size(); i++) {
CAVoice* voice = _voicePropertiesWidget.keys().at(i);
CAVoiceProperties* vp = static_cast<CAVoiceProperties*>(_voicePropertiesWidget[voice]);
voice->setMidiChannel(vp->uiMidiChannel->value() - 1);
voice->setMidiPitchOffset(vp->uiMidiPitchOffset->value());
}
CACanorus::rebuildUI(_document);
buildTree();
}
/*!
Repositions staffs, voices and other document structures so they match
the order in the document tree widget.
This method is usually called when applying the changes.
*/
void CAPropertiesDialog::createDocumentFromTree()
{
while (_document->sheetList().size())
_document->removeSheet(_document->sheetList()[0]);
QTreeWidgetItem* cur = uiDocumentTree->topLevelItem(0);
for (int i = 0; i < cur->childCount(); i++) {
CASheet* sheet = _sheetItem[cur->child(i)];
while (sheet->contextList().size())
sheet->removeContext(sheet->contextList()[0]);
_document->addSheet(sheet);
for (int j = 0; j < cur->child(i)->childCount(); j++) {
CAContext* c = _contextItem[cur->child(i)->child(j)];
if (c->contextType() == CAContext::Staff) {
CAStaff* s = static_cast<CAStaff*>(c);
while (s->voiceList().size())
s->removeVoice(s->voiceList()[0]);
for (int k = 0; k < cur->child(i)->child(j)->childCount(); k++) {
s->addVoice(_voiceItem[cur->child(i)->child(j)->child(k)]);
}
}
sheet->addContext(c);
}
}
}
void CAPropertiesDialog::on_uiUp_clicked(bool)
{
QTreeWidgetItem* cur = uiDocumentTree->currentItem();
QTreeWidgetItem* parent = cur->parent();
int idx;
if (!parent || (idx = parent->indexOfChild(cur)) == -1)
return;
parent->removeChild(cur);
parent->insertChild(idx - 1, cur);
uiDocumentTree->setCurrentItem(cur);
uiDocumentTree->expandAll();
}
void CAPropertiesDialog::on_uiDown_clicked(bool)
{
QTreeWidgetItem* cur = uiDocumentTree->currentItem();
QTreeWidgetItem* parent = cur->parent();
int idx;
if (!parent || (idx = parent->indexOfChild(cur)) == -1)
return;
parent->removeChild(cur);
parent->insertChild(idx + 1, cur);
uiDocumentTree->setCurrentItem(cur);
uiDocumentTree->expandAll();
}
void CAPropertiesDialog::updateDocumentProperties(CADocument* doc)
{
CADocumentProperties* dp = static_cast<CADocumentProperties*>(_documentPropertiesWidget);
dp->uiTitle->setText(doc->title());
dp->uiSubtitle->setText(doc->subtitle());
dp->uiComposer->setText(doc->composer());
dp->uiArranger->setText(doc->arranger());
dp->uiPoet->setText(doc->poet());
dp->uiTextTranslator->setText(doc->textTranslator());
dp->uiDedication->setText(doc->dedication());
dp->on_uiComposer_editingFinished();
dp->uiCopyright->setEditText(doc->copyright());
dp->uiComments->setText(doc->comments());
}
void CAPropertiesDialog::updateSheetProperties(CASheet* sheet)
{
}
void CAPropertiesDialog::updateStaffProperties(CAStaff* staff)
{
CAStaffProperties* sp = static_cast<CAStaffProperties*>(_contextPropertiesWidget[staff]);
sp->uiNumberOfLines->setValue(staff->numberOfLines());
}
void CAPropertiesDialog::updateVoiceProperties(CAVoice* voice)
{
static_cast<CAVoiceProperties*>(_voicePropertiesWidget[voice])->uiMidiChannel->setValue(voice->midiChannel() + 1);
static_cast<CAVoiceProperties*>(_voicePropertiesWidget[voice])->uiMidiPitchOffset->setValue(voice->midiPitchOffset());
}
void CAPropertiesDialog::updateLyricsContextProperties(CALyricsContext* lc)
{
}
void CAPropertiesDialog::updateFunctionMarkContextProperties(CAFunctionMarkContext* fmc)
{
}
void CAPropertiesDialog::updateChordNameContextProperties(CAChordNameContext* cnc)
{
}
| 17,713
|
C++
|
.cpp
| 400
| 36.2625
| 151
| 0.645725
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,399
|
singleaction.cpp
|
canorusmusic_canorus/src/ui/singleaction.cpp
|
/*!
Copyright (c) 2009-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details.
*/
#include <QString>
#include "singleaction.h"
CASingleAction::CASingleAction(QObject*)
: _pAction(nullptr)
{
_bMidiShortCutCombined = false;
}
CASingleAction::~CASingleAction()
{
if (m_localCreated) {
delete _pAction;
}
_pAction = nullptr;
}
void CASingleAction::setCommandName(QString oCommandName)
{
if (!oCommandName.isEmpty()) {
_oCommandName = oCommandName;
if (_pAction) {
_pAction->setText(oCommandName);
}
_oCommandNameNoAmpersand = _oCommandName;
_oCommandNameNoAmpersand.remove("&");
}
}
void CASingleAction::setDescription(QString oDescription)
{
if (!oDescription.isEmpty()) {
_oDescription = oDescription;
if (_pAction) {
_pAction->setToolTip(oDescription);
}
}
}
void CASingleAction::setShortCutAsString(QString oShortCut)
{
if (!oShortCut.isEmpty()) {
_oShortCut = oShortCut;
if (_pAction) {
_pAction->setShortcut(oShortCut);
}
//_oSysShortCut = shortcut();
}
}
void CASingleAction::setMidiKeySequence(QString oMidiKeySequence, bool combined)
{
if (!oMidiKeySequence.isEmpty()) {
_oMidiKeySequence = oMidiKeySequence;
_bMidiShortCutCombined = combined;
QStringList mksList = oMidiKeySequence.split(" ");
QString le;
_oMidiKeyParameters.clear();
foreach (le, mksList) {
_oMidiKeyParameters.push_back(le.toInt());
}
}
}
//void CASingleAction::setAction(QAction *pAction)
//{
// if(pAction == nullptr)
// {
// qWarning("Not overwriting action with Null-Pointer");
// return;
// }
// _pAction = pAction;
//}
QAction* CASingleAction::newAction(QObject* parent)
{
if (_pAction && m_localCreated) {
delete _pAction;
}
m_localCreated = true;
_pAction = new QAction(getCommandName(), parent);
_pAction->setText(getCommandName());
_pAction->setShortcut(getShortCutAsString());
_pAction->setToolTip(getDescription());
return _pAction;
}
void CASingleAction::fromQAction(const QAction& action, CASingleAction& sAction)
{
sAction.getAction()->setActionGroup(action.actionGroup());
sAction.getAction()->setAutoRepeat(action.autoRepeat());
sAction.getAction()->setCheckable(action.isCheckable());
sAction.getAction()->setChecked(action.isChecked());
sAction.getAction()->setData(action.data());
sAction.getAction()->setEnabled(action.isEnabled());
sAction.getAction()->setFont(action.font());
sAction.getAction()->setIcon(action.icon());
sAction.getAction()->setIconText(action.iconText());
sAction.getAction()->setIconVisibleInMenu(action.isIconVisibleInMenu());
sAction.getAction()->setMenu(action.menu());
sAction.getAction()->setMenuRole(action.menuRole());
sAction.getAction()->setObjectName(action.objectName());
sAction.getAction()->setParent(action.parent());
sAction.getAction()->setPriority(action.priority());
sAction.getAction()->setSeparator(action.isSeparator());
sAction.getAction()->setStatusTip(action.statusTip());
sAction.getAction()->setShortcut(action.shortcut());
sAction.getAction()->setShortcutContext(action.shortcutContext());
sAction.getAction()->setShortcuts(action.shortcuts());
sAction.getAction()->setStatusTip(action.statusTip());
sAction.getAction()->setText(action.text());
sAction.getAction()->setToolTip(action.toolTip());
sAction.getAction()->setVisible(action.isVisible());
sAction.getAction()->setWhatsThis(action.whatsThis());
}
| 3,843
|
C++
|
.cpp
| 111
| 29.882883
| 86
| 0.694892
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,400
|
actionstorage.cpp
|
canorusmusic_canorus/src/ui/actionstorage.cpp
|
/*!
Copyright (c) 2015-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QDebug>
#include "actionstorage.h"
#include "core/actiondelegate.h"
#include "mainwin.h"
#include "singleaction.h"
#include "widgets/undotoolbutton.h"
CAActionStorage::CAActionStorage()
: _actionDelegate(nullptr)
{
_actionWidget.actions().clear();
}
CAActionStorage::~CAActionStorage()
{
_actionWidget.actions().clear();
if (nullptr != _actionDelegate)
delete _actionDelegate;
_actionDelegate = nullptr;
}
void CAActionStorage::storeActionsFromMainWindow(CAMainWin& mainWin)
{
storeAction(mainWin.uiQuit);
storeAction(mainWin.uiNewDocument);
storeAction(mainWin.uiOpenDocument);
storeAction(mainWin.uiSaveDocument);
storeAction(mainWin.uiSaveDocumentAs);
storeAction(mainWin.uiCloseDocument);
storeAction(mainWin.uiImportDocument);
storeAction(mainWin.uiExportDocument);
storeAction(mainWin.uiPrintPreview);
storeAction(mainWin.uiPrint);
storeAction(mainWin.uiCopy);
storeAction(mainWin.uiCut);
storeAction(mainWin.uiPaste);
storeAction(mainWin.uiSelectAll);
storeAction(mainWin.uiInvertSelection);
storeAction(mainWin.uiZoomToWidth);
storeAction(mainWin.uiJumpTo);
storeAction(mainWin.uiShowStatusBar);
storeAction(mainWin.uiFullscreen);
storeAction(mainWin.uiInsertTimeSig);
storeAction(mainWin.uiInsertKeySig);
storeAction(mainWin.uiInsertBarline);
storeAction(mainWin.uiNoteCount);
storeAction(mainWin.uiSettings);
storeAction(mainWin.uiUsersGuide);
storeAction(mainWin.uiWhatsThis);
storeAction(mainWin.uiTipOfTheDay);
storeAction(mainWin.uiAboutCanorus);
storeAction(mainWin.uiAboutQt);
storeAction(mainWin.uiSplitHorizontally);
storeAction(mainWin.uiSplitVertically);
storeAction(mainWin.uiCloseCurrentView);
storeAction(mainWin.uiUnsplitAll);
storeAction(mainWin.uiNewView);
storeAction(mainWin.uiNewSheet);
storeAction(mainWin.uiNewContext);
storeAction(mainWin.uiPlayFromSelection);
storeAction(mainWin.uiAnimatedScroll);
storeAction(mainWin.uiLockScrollPlayback);
storeAction(mainWin.uiZoomToHeight);
storeAction(mainWin.uiZoomToFit);
storeAction(mainWin.uiZoomToSelection);
storeAction(mainWin.uiNewWindow);
storeAction(mainWin.uiCustomZoom);
storeAction(mainWin.uiScoreView);
storeAction(mainWin.uiLilyPondSource);
storeAction(mainWin.uiCanorusMLSource);
storeAction(mainWin.uiNewVoice);
storeAction(mainWin.uiDocumentProperties);
storeAction(mainWin.uiPrintDirectly);
storeAction(mainWin.uiExportToPdf);
storeAction(mainWin.uiNewDocumentWizard);
storeAction(mainWin.uiInsertPlayable);
storeAction(mainWin.uiInsertFM);
storeAction(mainWin.uiInsertClef);
storeAction(mainWin.uiRemoveVoice);
storeAction(mainWin.uiVoiceProperties);
storeAction(mainWin.uiAccsVisible);
storeAction(mainWin.uiHiddenRest);
storeAction(mainWin.uiRemoveContext);
storeAction(mainWin.uiContextProperties);
storeAction(mainWin.uiRemoveSheet);
storeAction(mainWin.uiSheetProperties);
storeAction(mainWin.uiTranspose);
storeAction(mainWin.uiFMEllipse);
storeAction(mainWin.uiInsertSyllable);
storeAction(mainWin.uiEditMode);
storeAction(mainWin.uiInsertMark);
storeAction(mainWin.uiInsertArticulation);
storeAction(mainWin.actionRecent_documents);
storeAction(mainWin.uiMidiRecorder);
storeAction(mainWin.uiResourceView);
storeAction(mainWin.uiInsertFBM);
storeAction(mainWin.uiShowRuler);
storeAction(mainWin.uiUndo->defaultAction());
storeAction(mainWin.uiRedo->defaultAction());
_actionDelegate = new CAActionDelegate(&mainWin);
}
void CAActionStorage::storeAction(QAction* action)
{
_actionWidget.addAction(action);
qWarning() << "Storage: Added new action, stored " << _actionWidget.actions().size();
}
void CAActionStorage::addWinActions()
{
_actionDelegate->addWinActions(_actionWidget);
_actionDelegate->updateMainWinActions();
}
| 4,235
|
C++
|
.cpp
| 113
| 33.185841
| 89
| 0.78561
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,401
|
jumptoview.cpp
|
canorusmusic_canorus/src/ui/jumptoview.cpp
|
/*!
Copyright (c) 2018, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "ui/jumptoview.h"
#include "ui/mainwin.h"
#include "widgets/scoreview.h"
#include "layout/drawablebarline.h"
CAJumpToView::CAJumpToView(CAMainWin* p)
: QDialog(p)
{
setupUi(this);
setupCustomUi();
}
CAJumpToView::~CAJumpToView()
{
}
void CAJumpToView::setupCustomUi()
{
}
void CAJumpToView::show()
{
// CAScoreView *v = static_cast<CAMainWin*>(parent())->currentScoreView();
// QDockWidget::show();
QDialog::show();
}
void CAJumpToView::accept()
{
int barNumber = uiJumpToBarNum->text().toInt();
if (dynamic_cast<CAMainWin*>(parent()) && static_cast<CAMainWin*>(parent())->currentScoreView()) {
CAScoreView* v = static_cast<CAMainWin*>(parent())->currentScoreView();
QMap<int, CADrawableBarline*> dBarlineMap = v->computeBarlinePositions();
if (!dBarlineMap.isEmpty()) {
// if barNumber is outside barlines enumeration, take the first/last barline available
if (barNumber < dBarlineMap.firstKey() || barNumber >= dBarlineMap.lastKey()) {
return;
}
// shift the view
v->setWorldX(dBarlineMap[barNumber]->xPos() - v->worldWidth() / 2.0);
v->repaint();
QDialog::accept();
}
}
}
| 1,474
|
C++
|
.cpp
| 45
| 27.666667
| 102
| 0.663842
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,402
|
rtmididevice.cpp
|
canorusmusic_canorus/src/interface/rtmididevice.cpp
|
/*!
Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QCoreApplication>
#include <QVector>
#include <sstream>
#include "../lib/rtmidi-4.0.0/RtMidi.h"
#include "interface/rtmididevice.h"
#ifndef SWIGCPP
#include "canorus.h"
#endif
/*!
\class CARtMidiDevice
\brief Canorus wrapper for RtMidi library
CARtMidiDevice is a Canorus wrapper class for a cross-platform MIDI library
RtMidi written by Gary P. Scavone (http://www.music.mcgill.ca/~gary/rtmidi/).
Usage:
1) When created, Input and Output MIDI devices get initialized.
2) Call getOutputPorts() and getInputPorts() to retreive a map of portNumber/portName.
3) Call openOutputPort(port) and/or openInputPort(port) to open an Output/Input port.
4) Send MIDI events (for midi output) using send(QVector<unsigned char>).
\todo Callback function implementation for retreiving MIDI-IN events. This should
probably be done by using Qt's signal-slot implementation. -Matevz
*/
CARtMidiDevice::CARtMidiDevice()
: CAMidiDevice()
{
_midiDeviceType = RtMidiDevice;
_out = nullptr;
_in = nullptr;
_outOpen = false;
_inOpen = false;
setRealTime(true);
// create midi client names which hold the current pid
_pid = QCoreApplication::applicationPid();
_midiNameOut << "Canorus Out (" << _pid << ")";
_midiNameIn << "Canorus In (" << _pid << ")";
try {
_out = new RtMidiOut(RtMidi::UNSPECIFIED, _midiNameOut.str());
_in = new RtMidiIn(RtMidi::UNSPECIFIED, _midiNameIn.str());
} catch (RtMidiError& error) {
error.printMessage();
}
}
bool CARtMidiDevice::openOutputPort(int port)
{
if (port == -1 || _outOpen)
return false;
if (_out && static_cast<int>(_out->getPortCount()) > port) { // check outputs
try {
_out->openPort(static_cast<unsigned int>(port));
} catch (RtMidiError& error) {
error.printMessage();
return false; // error when opening the port
}
_outOpen = true;
return true; // port opened successfully
} else {
std::cerr << "CARtMidiDevice::openOutputPort(): Port number " << port << " doesn't exist!" << std::endl;
return false; // wrong port number specified
}
}
bool CARtMidiDevice::openInputPort(int port)
{
if (port == -1 || _inOpen)
return false;
if (_in && static_cast<int>(_in->getPortCount()) > port) { // check outputs
try {
_in->openPort(static_cast<unsigned int>(port));
} catch (RtMidiError& error) {
error.printMessage();
return false; // error when opening the port
}
_in->setCallback(&rtMidiInCallback); // sets the callback function
_inOpen = true;
return true; // port opened successfully
} else {
std::cerr << "CARtMidiDevice::openInputPort(): Port number " << port << " doesn't exist!" << std::endl;
return false; // wrong port number specified
}
}
/*!
Callback function which gets called by RtMidi automatically when an information on MidiIn device has come.
*/
void rtMidiInCallback(double, std::vector<unsigned char>* message, void*)
{
(void)message; // Only used in with SWIGCPP
#ifndef SWIGCPP
emit CACanorus::midiDevice()->midiInEvent(QVector<unsigned char>::fromStdVector(*message));
#else
// call scripting callback?
#endif
}
void CARtMidiDevice::closeOutputPort()
{
try {
if (_outOpen)
_out->closePort();
} catch (RtMidiError& error) {
error.printMessage();
}
_outOpen = false;
}
void CARtMidiDevice::closeInputPort()
{
try {
if (_inOpen) {
_in->cancelCallback();
_in->closePort();
}
} catch (RtMidiError& error) {
error.printMessage();
}
_inOpen = false;
}
QMap<int, QString> CARtMidiDevice::getOutputPorts()
{
QMap<int, QString> outPorts;
try {
for (int i = 0; _out && i < static_cast<int>(_out->getPortCount()); i++)
outPorts.insert(i, QString::fromStdString(_out->getPortName(static_cast<unsigned int>(i))));
} catch (RtMidiError& error) {
error.printMessage();
}
return outPorts;
}
QMap<int, QString> CARtMidiDevice::getInputPorts()
{
QMap<int, QString> inPorts;
try {
for (int i = 0; _in && i < static_cast<int>(_in->getPortCount()); i++)
inPorts.insert(i, QString::fromStdString(_in->getPortName(static_cast<unsigned int>(i))));
} catch (RtMidiError& error) {
error.printMessage();
}
return inPorts;
}
CARtMidiDevice::~CARtMidiDevice()
{
closeOutputPort();
closeInputPort();
if (_out)
delete _out;
if (_in)
delete _in;
}
/*!
Sends the given \a message to the midi device. \a offset is ignored because CARtMidiDevice is a realtime device.
*/
void CARtMidiDevice::send(QVector<unsigned char> message, int)
{
std::vector<unsigned char> messageVector = message.toStdVector();
if (_outOpen)
_out->sendMessage(&messageVector);
}
| 5,207
|
C++
|
.cpp
| 157
| 28.133758
| 113
| 0.65745
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,403
|
playback.cpp
|
canorusmusic_canorus/src/interface/playback.cpp
|
/*!
Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QPen>
#include <QRect>
#include <QVector> // needed for RtMidi send message
#include <iostream>
#include "interface/mididevice.h"
#include "interface/playback.h"
#include "score/barline.h"
#include "score/context.h"
#include "score/dynamic.h"
#include "score/instrumentchange.h"
#include "score/keysignature.h"
#include "score/mark.h"
#include "score/note.h"
#include "score/sheet.h"
#include "score/staff.h"
#include "score/tempo.h"
#include "score/timesignature.h"
#include "score/voice.h"
/*!
\class CAPlayback
\brief Audio playback of the score.
This class creates playback events (usually MIDI events) for the music elements and sends these events to
one of the playback devices (usually CAMidiDevice).
To use the playback capabilities:
1) Create one of the CAMidiDevices (eg. CARtMidiDevice) and configure it (open output/input port).
2) Create CAPlayback object passing it the current score viewport (played notes will be painted red) or only
the sheet (usually used in scripting environment) and the midi device.
3) Optionally configure playback (setInitTimeStart() to start playback from the specific time. Default 0).
4) Call myPlaybackObject->run(). This will start playing in a new thread.
5) Call myPlaybackObject->stop() to stop the playback. Playback also stops automatically when finished.
6) Playback is also used for creating the events for midi file export. Therefore the music length time _curTime
is also transferred as a paramter in send() and sendMetaEvent() to export the music lengths independent of tempo.
The playbackFinished() signal is emitted once playback has finished or stopped.
If you want to immediately play only given elements (eg. when inserting notes), call playImmediately().
*/
CAPlayback::CAPlayback(CASheet* s, CAMidiDevice* m)
{
initPlayback();
_sheet = s;
_midiDevice = m;
_playSelectionOnly = false;
}
/*!
Plays the list of music elements simultaniously.
It only takes notes into account.
*/
CAPlayback::CAPlayback(CAMidiDevice* m)
{
initPlayback();
_midiDevice = m;
_playSelectionOnly = true;
}
/*!
Initializes all basic playback values to zero and connects the signals.
Usually called only once from the constructor.
*/
void CAPlayback::initPlayback()
{
_repeating = 0;
_lastRepeatOpenIdx = nullptr;
_curTime = 0;
_streamIdx = nullptr;
_stop = false;
_stopLock = false;
// override this settings in actual constructor
_sheet = nullptr;
_midiDevice = nullptr;
_playSelectionOnly = false;
_initTimeStart = 0;
_sleepFactor = 1.0; // set by tempo to determine the miliseconds for sleep
connect(this, SIGNAL(finished()), SLOT(stopNow()));
}
/*!
Destructor deletes the created arrays.
*/
CAPlayback::~CAPlayback()
{
if (isRunning()) {
terminate();
wait();
}
if (_lastRepeatOpenIdx)
delete[] _lastRepeatOpenIdx;
if (_streamIdx)
delete[] _streamIdx;
}
/*!
Immediately plays the given \a elts.
*/
void CAPlayback::playImmediately(QList<CAMusElement*> elts, int port)
{
_selection << elts;
midiDevice()->openOutputPort(port);
if (!isRunning()) {
start();
}
}
void CAPlayback::run()
{
if (_playSelectionOnly) {
playSelectionImpl();
return;
}
// list of all the music element lists (ie. streams) taken from all the contexts
QList<QList<CAMusElement*>> stream;
QVector<unsigned char> message; // midi 3-byte message sent to midi device
// initializes all the streams, indices, repeat barlines etc.
if (!streamList().size()) {
initStreams(sheet());
}
if (!streamList().size())
stop();
else
setStop(false);
int minLength = -1;
int mSeconds = 0; // actual song time, used when creating a midi file
while (!_stop || _curPlaying.size()) { // at stop true: enter to switch all notes off
for (int i = 0; i < _curPlaying.size(); i++) {
if (_stop || _curPlaying[i]->timeEnd() <= _curTime) {
// note off
CANote* note = dynamic_cast<CANote*>(_curPlaying[i]);
if (note) {
message << (128 + note->voice()->midiChannel()); // note off
message << static_cast<uchar>(CADiatonicPitch::diatonicPitchToMidiPitch(note->diatonicPitch()) + note->voice()->midiPitchOffset());
message << (127);
if ((note->musElementType() != CAMusElement::Rest) && // first because rest has no tie
!(note->tieStart() && note->tieStart()->noteEnd()))
midiDevice()->send(message, _curTime);
message.clear();
}
_curPlaying.removeAt(i--);
}
}
for (int i = 0; i < streamList().size(); i++) {
loopUntilPlayable(i);
}
if (_stop)
continue; // no notes on anymore
minLength = -1;
for (int i = 0; i < streamList().size(); i++) {
while (streamAt(i).size() > streamIdx(i) && streamAt(i).at(streamIdx(i))->timeStart() == _curTime) {
// check if a rest carries a tempo mark
CAMusElement* me = streamAt(i).at(streamIdx(i));
if (me->musElementType() == CAMusElement::Rest) {
for (int j = 0; j < me->markList().size(); j++) {
if (me->markList()[j]->markType() == CAMark::Tempo) {
CATempo* tempo = static_cast<CATempo*>(me->markList()[j]);
midiDevice()->sendMetaEvent(_curTime, CAMidiDevice::Meta_Tempo, static_cast<char>(tempo->bpm()), 0, 0);
}
}
}
// note on
CANote* note = dynamic_cast<CANote*>(streamAt(i).at(streamIdx(i)));
if (note) {
QVector<unsigned char> message;
// send dynamic information
for (int j = 0; j < note->markList().size(); j++) {
if (note->markList()[j]->markType() == CAMark::Dynamic) {
message << (176 + note->voice()->midiChannel()); // set volume
message << (CAMidiDevice::Midi_Ctl_Volume /* 7 */);
message << static_cast<uchar>(qRound(127 * static_cast<CADynamic*>(note->markList()[j])->volume() / 100.0));
midiDevice()->send(message, _curTime);
message.clear();
} else if (note->markList()[j]->markType() == CAMark::InstrumentChange) {
message << (192 + note->voice()->midiChannel()); // change program
message << static_cast<unsigned char>(static_cast<CAInstrumentChange*>(note->markList()[j])->instrument());
midiDevice()->send(message, _curTime);
message.clear();
} else if (note->markList()[j]->markType() == CAMark::Tempo) {
updateSleepFactor(static_cast<CATempo*>(note->markList()[j]));
CATempo* tempo = static_cast<CATempo*>(note->markList()[j]);
midiDevice()->sendMetaEvent(_curTime, CAMidiDevice::Meta_Tempo, tempo->bpm(), 0, 0);
}
}
message << (144 + note->voice()->midiChannel()); // note on
message << static_cast<uchar>(CADiatonicPitch::diatonicPitchToMidiPitch(note->diatonicPitch()) + note->voice()->midiPitchOffset());
message << (127);
if (!note->tieEnd())
midiDevice()->send(message, _curTime);
message.clear();
}
if (streamAt(i).at(streamIdx(i))->isPlayable()) {
_curPlaying << static_cast<CAPlayable*>(streamAt(i).at(streamIdx(i)));
}
int delta;
if ((delta = (streamAt(i).at(streamIdx(i))->timeEnd() - _curTime)) < minLength
|| minLength == -1)
minLength = delta;
streamIdx(i)++;
}
// calculate the pause needed by msleep
// last playables in the stream - _curPlaying is otherwise always set!
// pre-last pass, set minLength to their timeLengths to stop the notes
for (int j = 0; j < _curPlaying.size(); j++) {
if ((_curPlaying[j]->timeEnd() - _curTime) < minLength || minLength == -1)
minLength = _curPlaying[j]->timeEnd() - _curTime;
}
}
if (minLength == -1) {
// last pass, notes indices are at the ends and no notes are played anymore
setStop(true);
}
if (minLength != -1) {
mSeconds += qRound(minLength * _sleepFactor);
if (midiDevice()->isRealTime())
msleep(static_cast<ulong>(qRound(minLength * _sleepFactor)));
_curTime += minLength;
}
}
_curPlaying.clear();
stop();
}
/*!
Calculates the sleep factor for the given tempo \a t.
If \a t is null, it does nothing.
*/
void CAPlayback::updateSleepFactor(CATempo* t)
{
if (t) {
_sleepFactor = 60000.0f / (CAPlayableLength::playableLengthToTimeLength(t->beat()) * t->bpm());
}
}
/*!
Private function for immediately playing the music elements in _selection.
This function ends when all the notes in _selection queue are played.
_selection queue might be refilled during the playback by calling playImmediately().
This function is usually called when inserting new notes. If the first note is still playing,
the second note is played simultaniously - thus having two notes in _selection for eg.
*/
void CAPlayback::playSelectionImpl()
{
QVector<unsigned char> message;
QList<int> timeEnds; // time ends when the notes should turned off
int waitTime = 16;
int curTime = 0;
while (_selection.size() || _curPlaying.size()) {
while (_selection.size()) {
if (_selection[0]->musElementType() != CAMusElement::Note) {
_selection.takeFirst();
continue;
}
CANote* note = static_cast<CANote*>(_selection.takeFirst());
// Note ON
message << (192 + note->voice()->midiChannel()); // change program
message << (note->voice()->midiProgram());
midiDevice()->send(message, _curTime);
message.clear();
message << (176 + note->voice()->midiChannel()); // set volume
message << (7);
message << (100);
midiDevice()->send(message, _curTime);
message.clear();
message << (144 + note->voice()->midiChannel()); // note on
message << static_cast<uchar>(CADiatonicPitch::diatonicPitchToMidiPitch(note->diatonicPitch()) + note->voice()->midiPitchOffset());
message << (127);
midiDevice()->send(message, _curTime);
message.clear();
_curPlaying << note;
timeEnds << curTime + note->timeLength() * 4;
}
for (int i = 0; i < _curPlaying.size(); i++) {
if (curTime >= timeEnds[i] || _stop) {
// Note OFF
if (_curPlaying[i]->musElementType() == CAMusElement::Note) {
CANote* note = static_cast<CANote*>(_curPlaying[i]);
message << (128 + note->voice()->midiChannel()); // note off
message << static_cast<uchar>(CADiatonicPitch::diatonicPitchToMidiPitch(note->diatonicPitch()) + note->voice()->midiPitchOffset());
message << (127);
midiDevice()->send(message, _curTime);
message.clear();
}
timeEnds.removeAt(i);
_curPlaying.removeAt(i);
i--;
}
}
msleep(static_cast<ulong>(waitTime));
curTime += waitTime;
}
stop();
// output ports are closed in MainWin
}
/*!
The nice and the right way to stop the playback.
Returns immediately.
\sa stopNow()
*/
void CAPlayback::stop()
{
_stop = true;
}
/*!
Stop playback and clean up.
Blocks until all cleanups are done.
\sa stop()
*/
void CAPlayback::stopNow()
{
if (stopLock())
return;
setStopLock(true);
if (isRunning()) { // stopNow() was _not_ called by the finished() signal (i.e. it was called from another thread)
// stop playback and wait for the thread to finish.
stop();
wait(); // (QThread::finished() will be emitted here, so we need the lock flag)
}
setStopLock(false);
emit playbackFinished();
}
/*!
Generates streams (elements lists) of playable elements (notes, rests) from the given sheet.
*/
void CAPlayback::initStreams(CASheet* sheet)
{
for (int i = 0; i < sheet->contextList().size(); i++) {
if (sheet->contextList()[i]->contextType() == CAContext::Staff) {
CAStaff* staff = static_cast<CAStaff*>(sheet->contextList()[i]);
// add all the voices lists to the common list stream
for (int j = 0; j < staff->voiceList().size(); j++) {
_streamList << staff->voiceList()[j]->musElementList();
QVector<unsigned char> message;
message << (192 + staff->voiceList()[j]->midiChannel()); // change program
message << (staff->voiceList()[j]->midiProgram());
midiDevice()->send(message, _curTime);
message.clear();
message << (176 + staff->voiceList()[j]->midiChannel()); // set volume
message << (7);
message << (100);
midiDevice()->send(message, _curTime);
message.clear();
}
}
}
_streamIdx = new int[streamList().size()];
_lastRepeatOpenIdx = new int[streamList().size()];
// init streams indices, current times and last repeat barlines
for (int i = 0; i < streamList().size(); i++) {
_curTime = getInitTimeStart();
streamIdx(i) = 0;
lastRepeatOpenIdx(i) = -1;
_repeating = false;
loopUntilPlayable(i, true); // ignore repeats
}
if (_sheet) {
updateSleepFactor(_sheet->getTempo(getInitTimeStart()));
}
}
/*!
Loops from the stream with the given index \a i until the last element with smaller or equal start time of the current time.
This function also remembers any special signs like open repeat barlines.
*/
void CAPlayback::loopUntilPlayable(int i, bool ignoreRepeats)
{
for (int j = streamIdx(i);
j < streamAt(i).size() && streamAt(i).at(j)->timeStart() <= _curTime && (streamAt(i).at(j)->timeStart() != _curTime || !(streamAt(i).at(j)->musElementType() == CAMusElement::Note) || (static_cast<CANote*>(streamAt(i).at(j))->isFirstInChord()));
streamIdx(i) = j++) {
if (streamAt(i).at(j)->musElementType() == CAMusElement::TimeSignature) {
int beats = static_cast<CATimeSignature*>(streamAt(i).at(j))->beats();
int beat = static_cast<CATimeSignature*>(streamAt(i).at(j))->beat();
//std::cout<<" exportiere Time Signature "<<_curTime<<" mit "<<beats<<"/"<<beat<<std::endl;
midiDevice()->sendMetaEvent(_curTime, CAMidiDevice::Meta_Timesig, beats, beat, 0);
}
if (streamAt(i).at(j)->musElementType() == CAMusElement::KeySignature) {
//int key = (static_cast<CAKeySignature*>(streamAt(i).at(j)))->diatonicKey()->numberOfAccs();
CAKeySignature* ks = dynamic_cast<CAKeySignature*>(streamAt(i).at(j));
CADiatonicKey dk = ks->diatonicKey();
int key = dk.numberOfAccs();
int minor = dk.gender() == CADiatonicKey::Minor ? 1 : 0;
midiDevice()->sendMetaEvent(_curTime, CAMidiDevice::Meta_Keysig, key, minor, 0);
}
if (streamAt(i).at(j)->musElementType() == CAMusElement::Barline && static_cast<CABarline*>(streamAt(i).at(j))->barlineType() == CABarline::RepeatOpen) {
lastRepeatOpenIdx(i) = j;
}
if (streamAt(i).at(j)->musElementType() == CAMusElement::Barline && static_cast<CABarline*>(streamAt(i).at(j))->barlineType() == CABarline::RepeatClose && !ignoreRepeats) {
if (!_repeating) {
// set the new index in ALL streams
for (int k = 0; k < streamList().size(); k++) {
streamIdx(k) = lastRepeatOpenIdx(k) + 1;
}
_curTime = streamAt(i).at(streamIdx(i))->timeStart();
j = streamIdx(i);
_repeating = true;
}
}
}
// last element if non-playable is exception - increase the index counter
if (streamIdx(i) == streamAt(i).size() - 1 && !streamAt(i).at(streamIdx(i))->isPlayable())
streamIdx(i)++;
}
| 17,362
|
C++
|
.cpp
| 394
| 34.525381
| 253
| 0.581686
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,404
|
pyconsoleinterface.cpp
|
canorusmusic_canorus/src/interface/pyconsoleinterface.cpp
|
/*!
Copyright (c) 2006-2008, Štefan Sakalík, Reinhard Katzmann, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#ifdef USE_PYTHON
#include "interface/pyconsoleinterface.h"
#ifndef SWIGCPP
#include "widgets/pyconsole.h"
#endif
/*!
This class serves as a proxy, simple wrapper:
plugins/pycli <=> interface/pyconsoleinterface <=> ui/pyconsole
*/
#ifndef SWIGCPP
CAPyConsoleInterface::CAPyConsoleInterface(CAPyConsole* pyConsole)
{
_pycons = pyConsole;
}
#endif
void CAPyConsoleInterface::pluginInit(void)
{
#ifndef SWIGCPP
_pycons->asyncPluginInit();
#endif
}
#ifndef SWIGCPP
char* CAPyConsoleInterface::bufferedInput(char* prompt)
{
return (_pycons->asyncBufferedInput(QString(prompt))).toUtf8().data();
}
void CAPyConsoleInterface::bufferedOutput(char* str, bool bStdErr)
{
QString* q_str = new QString(str);
_pycons->asyncBufferedOutput(*q_str, bStdErr);
}
#endif
#endif
| 1,048
|
C++
|
.cpp
| 38
| 25.631579
| 101
| 0.77978
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,405
|
mididevice.cpp
|
canorusmusic_canorus/src/interface/mididevice.cpp
|
/*!
Copyright (c) 2007, Matevž Jekovec, Canorus development team
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include "interface/mididevice.h"
#include "score/diatonickey.h"
#include "score/diatonicpitch.h"
#include "score/sheet.h"
#include "score/voice.h"
QStringList CAMidiDevice::GM_INSTRUMENTS = QStringList() <<
// tr() function actually does nothing here, because translator is not initialized yet.
// However, this is needed for .ts files to be generated!
QObject::tr("Acoustic Grand Piano", "instrument") << QObject::tr("Bright Acoustic Piano", "instrument") << QObject::tr("Electric Grand Piano", "instrument") << QObject::tr("Honky-tonk Piano", "instrument") << QObject::tr("Electric Piano 1", "instrument") << QObject::tr("Electric Piano 2", "instrument") << QObject::tr("Harpsichord", "instrument") << QObject::tr("Clavi", "instrument") << QObject::tr("Celesta", "instrument") << QObject::tr("Glockenspiel", "instrument") << QObject::tr("Music Box", "instrument") << QObject::tr("Vibraphone", "instrument") << QObject::tr("Marimba", "instrument") << QObject::tr("Xylophone", "instrument") << QObject::tr("Tubular Bells", "instrument") << QObject::tr("Dulcimer", "instrument") << QObject::tr("Drawbar Organ", "instrument") << QObject::tr("Percussive Organ", "instrument") << QObject::tr("Rock Organ", "instrument") << QObject::tr("Church Organ", "instrument") << QObject::tr("Reed Organ", "instrument") << QObject::tr("Accordion", "instrument") << QObject::tr("Harmonica", "instrument") << QObject::tr("Tango Accordion", "instrument") << QObject::tr("Acoustic Guitar (nylon)", "instrument") << QObject::tr("Acoustic Guitar (steel)", "instrument") << QObject::tr("Electric Guitar (jazz)", "instrument") << QObject::tr("Electric Guitar (clean)", "instrument") << QObject::tr("Electric Guitar (muted)", "instrument") << QObject::tr("Overdriven Guitar", "instrument") << QObject::tr("Distortion Guitar", "instrument") << QObject::tr("Guitar harmonics", "instrument") << QObject::tr("Acoustic Bass", "instrument") << QObject::tr("Electric Bass (finger)", "instrument") << QObject::tr("Electric Bass (pick)", "instrument") << QObject::tr("Fretless Bass", "instrument") << QObject::tr("Slap Bass 1", "instrument") << QObject::tr("Slap Bass 2", "instrument") << QObject::tr("Synth Bass 1", "instrument") << QObject::tr("Synth Bass 2", "instrument") << QObject::tr("Violin", "instrument") << QObject::tr("Viola", "instrument") << QObject::tr("Cello", "instrument") << QObject::tr("Contrabass", "instrument") << QObject::tr("Tremolo Strings", "instrument") << QObject::tr("Pizzicato Strings", "instrument") << QObject::tr("Orchestral Harp", "instrument") << QObject::tr("Timpani", "instrument") << QObject::tr("String Ensemble 1", "instrument") << QObject::tr("String Ensemble 2", "instrument") << QObject::tr("SynthStrings 1", "instrument") << QObject::tr("SynthStrings 2", "instrument") << QObject::tr("Choir Aahs", "instrument") << QObject::tr("Voice Oohs", "instrument") << QObject::tr("Synth Voice", "instrument") << QObject::tr("Orchestra Hit", "instrument") << QObject::tr("Trumpet", "instrument") << QObject::tr("Trombone", "instrument") << QObject::tr("Tuba", "instrument") << QObject::tr("Muted Trumpet", "instrument") << QObject::tr("French Horn", "instrument") << QObject::tr("Brass Section", "instrument") << QObject::tr("SynthBrass 1", "instrument") << QObject::tr("SynthBrass 2", "instrument") << QObject::tr("Soprano Sax", "instrument") << QObject::tr("Alto Sax", "instrument") << QObject::tr("Tenor Sax", "instrument") << QObject::tr("Baritone Sax", "instrument") << QObject::tr("Oboe", "instrument") << QObject::tr("English Horn", "instrument") << QObject::tr("Bassoon", "instrument") << QObject::tr("Clarinet", "instrument") << QObject::tr("Piccolo", "instrument") << QObject::tr("Flute", "instrument") << QObject::tr("Recorder", "instrument") << QObject::tr("Pan Flute", "instrument") << QObject::tr("Blown Bottle", "instrument") << QObject::tr("Shakuhachi", "instrument") << QObject::tr("Whistle", "instrument") << QObject::tr("Ocarina", "instrument") << QObject::tr("Lead 1 (square)", "instrument") << QObject::tr("Lead 2 (sawtooth)", "instrument") << QObject::tr("Lead 3 (calliope)", "instrument") << QObject::tr("Lead 4 (chiff)", "instrument") << QObject::tr("Lead 5 (charang)", "instrument") << QObject::tr("Lead 6 (voice)", "instrument") << QObject::tr("Lead 7 (fifths)", "instrument") << QObject::tr("Lead 8 (bass + lead)", "instrument") << QObject::tr("Pad 1 (new age)", "instrument") << QObject::tr("Pad 2 (warm)", "instrument") << QObject::tr("Pad 3 (polysynth)", "instrument") << QObject::tr("Pad 4 (choir)", "instrument") << QObject::tr("Pad 5 (bowed)", "instrument") << QObject::tr("Pad 6 (metallic)", "instrument") << QObject::tr("Pad 7 (halo)", "instrument") << QObject::tr("Pad 8 (sweep)", "instrument") << QObject::tr("FX 1 (rain)", "instrument") << QObject::tr("FX 2 (soundtrack)", "instrument") << QObject::tr("FX 3 (crystal)", "instrument") << QObject::tr("FX 4 (atmosphere)", "instrument") << QObject::tr("FX 5 (brightness)", "instrument") << QObject::tr("FX 6 (goblins)", "instrument") << QObject::tr("FX 7 (echoes)", "instrument") << QObject::tr("FX 8 (sci-fi)", "instrument") << QObject::tr("Sitar", "instrument") << QObject::tr("Banjo", "instrument") << QObject::tr("Shamisen", "instrument") << QObject::tr("Koto", "instrument") << QObject::tr("Kalimba", "instrument") << QObject::tr("Bag pipe", "instrument") << QObject::tr("Fiddle", "instrument") << QObject::tr("Shanai", "instrument") << QObject::tr("Tinkle Bell", "instrument") << QObject::tr("Agogo", "instrument") << QObject::tr("Steel Drums", "instrument") << QObject::tr("Woodblock", "instrument") << QObject::tr("Taiko Drum", "instrument") << QObject::tr("Melodic Tom", "instrument") << QObject::tr("Synth Drum", "instrument") << QObject::tr("Reverse Cymbal", "instrument") << QObject::tr("Guitar Fret Noise", "instrument") << QObject::tr("Breath Noise", "instrument") << QObject::tr("Seashore", "instrument") << QObject::tr("Bird Tweet", "instrument") << QObject::tr("Telephone Ring", "instrument") << QObject::tr("Helicopter", "instrument") << QObject::tr("Applause", "instrument") << QObject::tr("Gunshot", "instrument");
/*!
\class CAMidiDevice
\brief Canorus<->Midi bridge.
This class represents generic Midiinterface to Canorus.
Any Midi wrapper class should extend this class.
Currently CARtMidi is one of the Midi libraries implemented. This class is an example
of the so called real-time Midi classes. This means that the midi event will be heard
at the moment it is sent.
Another example is CAMidiExport. This is a Midi file writer. The class is an example
of the non-real-time Midi classes. It needs also the time to write the
midi event to a file.
\warning MIDI INPUT is not available for Swig and therefore scripting languages yet.
*/
CAMidiDevice::CAMidiDevice()
: QObject()
{
}
/*!
This function returns translated instrument name for the given MIDI program.
\sa instrumentNames(), GM_INSTRUMENTS
*/
QString CAMidiDevice::instrumentName(int midiProgram)
{
return QObject::tr(CAMidiDevice::GM_INSTRUMENTS[midiProgram].toStdString().c_str(), "instrument");
}
/*!
This function returns a list of translated GM instruments.
\sa instrumentName(), GM_INSTRUMENTS
*/
QStringList CAMidiDevice::instrumentNames()
{
QStringList trInstruments;
for (int i = 0; i < CAMidiDevice::GM_INSTRUMENTS.size(); i++) {
trInstruments << QObject::tr(CAMidiDevice::GM_INSTRUMENTS[i].toStdString().c_str(), "instrument");
}
return trInstruments;
}
/*!
Returns the first midi channel that isn't occupied by voices in the given sheet \a s yet.
Returns 0, if all the channels are occupied.
\warning This function never returns midi channel 10 as it's reserved for percussion instruments only.
*/
unsigned char CAMidiDevice::freeMidiChannel(CASheet* s)
{
if (!s)
return 0;
QList<CAVoice*> voices = s->voiceList();
for (unsigned char i = 0; i < 16; i++) {
int j = 0;
while (j < voices.size() && voices[j]->midiChannel() != i)
j++;
if (j == voices.size() && i != 9)
return i;
}
return 0;
}
/*!
\var CAMidiDevice::GM_INSTRUMENTS
Original General Midi Instruments (program) names.
Call instrumentName() or instrumentNames() to get translated strings.
*/
| 8,501
|
C++
|
.cpp
| 75
| 110.16
| 5,770
| 0.67999
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,406
|
plugin.cpp
|
canorusmusic_canorus/src/interface/plugin.cpp
|
/** @file interface/plugin.cpp
*
* Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team
* All Rights Reserved. See AUTHORS for a complete list of authors.
*
* Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#ifdef USE_SWIG
// Python.h, which swigpython.h includes, must be included before any other headers
#include "scripting/swigpython.h"
#include "scripting/swigruby.h"
#endif
#include "interface/plugin.h"
#include "interface/pluginaction.h"
#ifndef SWIGCPP
#include "canorus.h"
#include "layout/drawablemuselement.h"
#include "ui/mainwin.h"
#include "widgets/scoreview.h"
#include "widgets/view.h"
#include "widgets/viewcontainer.h"
#else
#include "interface/plugins_swig.h"
#include <QMenu>
#endif
extern "C" void guiError(); // defined in canoruspython.i
CAPlugin::CAPlugin()
{
_name = "";
_author = "";
_version = "";
_date = "";
_dirName = "";
_homeUrl = "";
_updateUrl = "";
_enabled = false;
}
CAPlugin::CAPlugin(QString name, QString author, QString version, QString date, QString dirName, QString homeUrl, QString updateUrl)
{
_name = name;
_author = author;
_version = version;
_date = date;
_dirName = dirName;
_homeUrl = homeUrl;
_updateUrl = updateUrl;
_enabled = false;
}
CAPlugin::~CAPlugin()
{
QList<CAPluginAction*> pluginActions = _actionMap.values();
for (int i = 0; i < pluginActions.size(); i++)
delete pluginActions[i];
QList<QMenu*> menus = _menuMap.values();
for (int i = 0; i < menus.size(); i++)
delete menus[i];
}
bool CAPlugin::action(QString onAction, CAMainWin* mainWin, CADocument* document, QEvent* evt, QPoint* coords)
{
if (!_enabled)
return false;
QList<CAPluginAction*> actionList = _actionMap.values(onAction);
if (!actionList.size()) // action not found
return false;
bool error = false;
for (int i = 0; i < actionList.size(); i++)
error |= (!callAction(actionList[i], mainWin, document, evt, coords));
return (!error);
}
bool CAPlugin::callAction(CAPluginAction* action, CAMainWin* mainWin, CADocument* document, QEvent*, QPoint*, QString filename)
{
bool error = false;
#ifndef SWIGCPP
bool rebuildDocument = false;
#endif
#ifdef USE_RUBY
QList<VALUE> rubyArgs;
#endif
#ifdef USE_PYTHON
QList<PyObject*> pythonArgs;
#endif
// Convert arguments to its needed scripting language types
QList<QString> args = action->args();
for (int i = 0; i < args.size(); i++) {
QString val = args[i];
// Currently selected document
if (val == "document") {
#ifndef SWIGCPP
rebuildDocument = true;
#endif
#ifdef USE_RUBY
if (action->lang() == "ruby") {
rubyArgs << CASwigRuby::toRubyObject(document, CASwigRuby::Document);
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(document, CASwigPython::Document);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
}
#endif
} else
// Currently selected sheet
if (val == "sheet") {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
if (mainWin->currentSheet())
rubyArgs << CASwigRuby::toRubyObject(mainWin->currentSheet(), CASwigRuby::Sheet);
else {
error = true;
break;
}
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
if (mainWin->currentSheet()) {
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(mainWin->currentSheet(), CASwigPython::Sheet);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
} else {
error = true;
break;
}
}
#endif
} else
// Currently selected note
if (val == "note") {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
#ifndef SWIGCPP
if (mainWin->currentScoreView()) {
CAScoreView* v = mainWin->currentScoreView();
if (!v->selection().size() || v->selection().front()->drawableMusElementType() != CADrawableMusElement::DrawableNote) {
error = true;
break;
}
rubyArgs << CASwigRuby::toRubyObject(v->selection().front()->musElement(), CASwigRuby::Note);
} else {
error = true;
break;
}
#endif
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
#ifndef SWIGCPP
if (mainWin->currentScoreView()) {
CAScoreView* v = mainWin->currentScoreView();
if (!v->selection().size() || v->selection().front()->drawableMusElementType() != CADrawableMusElement::DrawableNote) {
error = true;
break;
}
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(v->selection().front()->musElement(), CASwigPython::MusElement);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
} else {
error = true;
break;
}
#endif
}
#endif
} else if (val == "chord") {
//TODO
} else
// Selection in the current score view
if (val == "selection") {
#ifdef USE_PYTHON
if (action->lang() == "python") {
#ifndef SWIGCPP
if (mainWin->currentScoreView()) {
QList<CAMusElement*> musElements = mainWin->currentScoreView()->musElementSelection();
PyObject* list = PyList_New(0);
PyEval_RestoreThread(CASwigPython::mainThreadState);
for (int i = 0; i < musElements.size(); i++) {
PyList_Append(list, CASwigPython::toPythonObject(musElements[i], CASwigPython::MusElement));
}
PyEval_ReleaseThread(CASwigPython::mainThreadState);
pythonArgs << list;
} else {
error = true;
break;
}
#endif
}
#endif
} else
// Directory of the plugin
if (val == "pluginDir") {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
rubyArgs << CASwigRuby::toRubyObject(&_dirName, CASwigRuby::String);
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(&_dirName, CASwigPython::String);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
}
#endif
} else
// File name selected in export/import dialogs
if (val == "export-filename" || val == "import-filename") {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
rubyArgs << CASwigRuby::toRubyObject(&filename, CASwigRuby::String);
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(&filename, CASwigPython::String);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
}
#endif
}
}
#ifdef USE_PYTHON
if (_name == "pyCLI") {
if (mainWin->pyConsoleIface) {
PyEval_RestoreThread(CASwigPython::mainThreadState);
pythonArgs << CASwigPython::toPythonObject(mainWin->pyConsoleIface, CASwigPython::PyConsoleInterface);
PyEval_ReleaseThread(CASwigPython::mainThreadState);
}
}
#endif
//add the plugin's path for the first time, so scripting languages can find their modules
if (action->onAction() == "onInit") {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
rb_eval_string((QString("$: << '") + dirName() + "'").toStdString().c_str());
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
PyEval_RestoreThread(CASwigPython::mainThreadState);
PyRun_SimpleString((QString("sys.path.append('") + dirName() + "')").toStdString().c_str());
PyEval_ReleaseThread(CASwigPython::mainThreadState);
}
#endif
}
if (!error) {
#ifdef USE_RUBY
if (action->lang() == "ruby") {
error = (!CASwigRuby::callFunction(_dirName + "/" + action->filename(), action->function(), rubyArgs));
}
#endif
#ifdef USE_PYTHON
if (action->lang() == "python") {
error = (!CASwigPython::callFunction(_dirName + "/" + action->filename(), action->function(), pythonArgs));
}
#endif
}
#ifndef SWIGCPP
if (action->refresh()) {
if (rebuildDocument == true)
CACanorus::rebuildUI(document);
else
CACanorus::rebuildUI(document, mainWin->currentSheet());
}
#endif
return (!error);
}
void CAPlugin::addAction(CAPluginAction* action)
{
if (!_actionMap.values(action->onAction()).contains(action))
_actionMap.insertMulti(action->onAction(), action);
}
| 9,695
|
C++
|
.cpp
| 273
| 26.6337
| 139
| 0.576919
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,407
|
keybdinput.cpp
|
canorusmusic_canorus/src/interface/keybdinput.cpp
|
/*!
Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team
Copyright (c) 2008, Georg Rudolph
All Rights Reserved. See AUTHORS for a complete list of authors.
Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#include <QObject>
#include <iostream> //debugging
#include "canorus.h"
#include "core/muselementfactory.h"
#include "core/settings.h"
#include "core/undo.h"
#include "interface/keybdinput.h"
#include "interface/mididevice.h"
#include "layout/drawablestaff.h"
#include "score/interval.h"
#include "widgets/menutoolbutton.h"
class CAMenuToolButton;
/*!
\class CAKeybdInput
\brief Music input per midi non realtime
This class adds score input capability through a connected midi keyboard in non realtime.
It allows to use simultaniously the computer mouse and the computer keyboard as usual.
To activate midi keyboard input you have to select in canorus settings, readable devices,
the alsa midi port of your midi keyboard. When in input mode, when a voice and a duration
is selected, notes can be entered with the midi keyboard too.
Key strockes within 100 ms will be combined into a chord.
Accents are set according the current key pitch. Automatic tracking of the scene is done too.
todo: User selectable (to be implemented) midi pitches can be set to be interpreted as rest input,
punctuation and so on. Inserting at the currently selected note.
*/
CAKeybdInput::CAKeybdInput(CAMainWin* mw)
{
_mw = mw;
// Initialize keyboad input chord timer
_midiInChordTimer.stop();
_midiInChordTimer.setSingleShot(true);
_tupPla = nullptr;
_tup = nullptr;
_lastMidiInVoice = nullptr;
_noteLayout.clear();
}
/*!
Destructor deletes the created arrays.
*/
CAKeybdInput::~CAKeybdInput()
{
}
void CAKeybdInput::onMidiInEvent(QVector<unsigned char> m)
{
unsigned char event, velocity;
std::cout << "MidiInEvent: ";
for (int i = 0; i < m.size(); i++)
std::cout << static_cast<int>(m[i]) << " ";
std::cout << std::endl;
if (m.size() < 3) // only note on/off here which are 3 bytes
return;
event = m[0];
velocity = m[2];
if (event == CAMidiDevice::Midi_Note_On && velocity != 0) {
//CADiatonicPitch x = CADiatonicPitch::diatonicPitchFromMidiPitch( m[1] );
midiInEventToScore(_mw->currentScoreView(), m);
}
}
/*!
This is the entry point the midi input device. All note on events are passed over here.
*/
void CAKeybdInput::midiInEventToScore(CAScoreView* v, QVector<unsigned char> m)
{
int i;
CADiatonicPitch p = CADiatonicPitch::diatonicPitchFromMidiPitch(m[1]);
CADiatonicPitch nonenharmonicPitch;
CAVoice* voice = _mw->currentVoice();
if (voice) {
int cpitch = m[1];
/*
// will publish this only when it's configurable. Have only a four octave keyboard ...
CAPlayableLength plength = CAPlayableLength::Undefined;
switch (cpitch) {
case 39: plength = CAPlayableLength::Whole; break;
case 40: plength = CAPlayableLength::Half; break;
case 41: plength = CAPlayableLength::Quarter; break;
case 42: plength = CAPlayableLength::Eighth; break;
case 43: plength = CAPlayableLength::Sixteenth; break;
default: ;
}
if (plength != CAPlayableLength::Undefined) {
_mw->uiPlayableLength->setCurrentId( plength.musicLength(), true );
_mw->musElementFactory()->playableLength().setDotted( 0 );
v->setShadowNoteLength( _mw->musElementFactory()->playableLength() );
v->updateHelpers();
v->repaint();
return;
}
*/
CADrawableContext* drawableContext = v->currentContext();
CAStaff* staff = nullptr;
//CADrawableStaff *drawableStaff = nullptr;
if (drawableContext) {
//drawableStaff = dynamic_cast<CADrawableStaff*>(drawableContext);
staff = dynamic_cast<CAStaff*>(drawableContext->context());
}
CANote* note = nullptr;
CARest* rest = nullptr;
switch (cpitch) {
// case 37: std::cout << " Pause" << std::endl;
// rest = new CARest( CARest::Normal, _mw->musElementFactory()->playableLength(), voice, 0, -1 );
// break;
// case 38: _mw->uiTupletType->defaultAction()->setChecked( !_mw->uiTupletType->isChecked() );
// return;
default:
nonenharmonicPitch = matchPitchToKey(voice, p);
note = new CANote(nonenharmonicPitch, _mw->musElementFactory()->playableLength(), voice, -1);
}
// if notes come in sufficiently close together we make a chord of them
bool appendToChord = _midiInChordTimer.isActive();
// we create undo only for chords as a whole
if (!appendToChord)
CACanorus::undo()->createUndoCommand(_mw->document(), QObject::tr("insert midi note", "undo"));
// If we are still in the processing of a tuplet, check if it's still there.
// Possibly editing on the GUI could have moved it around or away, and no crash please.
if (_tupPla && (!voice->musElementList().contains(_tupPla) || _tupPla->tuplet() != _tup))
_tupPla = nullptr;
// Where to put the note? When in a tuplet, do a chord in the tuplet or the nex not in the tuplet.
if (_tupPla && !appendToChord) {
_tupPla = _tup->nextTimed(_tupPla);
}
if (_tupPla) {
// next note in tuplet
if (note) {
_tupPla = voice->insertInTupletAndVoiceAt(_tupPla, note);
_tup = _tupPla->tuplet();
}
} else if (_mw->uiTupletType->isChecked()) {
// start a new tuplet
QList<CAPlayable*> elements;
if (note) {
elements << static_cast<CAPlayable*>(note);
} else
elements << static_cast<CAPlayable*>(rest);
for (int i = 1; i < _mw->uiTupletNumber->value(); i++) {
_mw->musElementFactory()->configureRest(voice, nullptr);
elements << static_cast<CAPlayable*>(_mw->musElementFactory()->musElement());
}
_tup = new CATuplet(_mw->uiTupletNumber->value(), _mw->uiTupletActualNumber->value(), elements);
_tupPla = _tup->firstNote();
} else {
// insert just a note
if (note) {
//voice->append( note, appendToChord );
if (appendToChord && _noteLayout.size()) {
CANote* prevNote = nullptr;
for (i = 0; i < _noteLayout.size(); i++) {
note = new CANote(nonenharmonicPitch, static_cast<CAPlayable*>(_noteLayout[i])->playableLength(), voice, -1);
voice->insert(_noteLayout[i], note, appendToChord);
if (i > 0) {
_mw->musElementFactory()->configureSlur(staff, prevNote, note);
}
prevNote = note;
}
} else {
if (note) {
delete note;
}
//CAMusElement *elt = voice->lastMusElement();
CABarline* b = static_cast<CABarline*>(voice->previousByType(CAMusElement::Barline,
voice->lastMusElement()));
//CABarline *b = static_cast<CABarline*>(
// voice->lastPlayableElt()->voice()->previousByType( CAMusElement::Barline, voice->lastMusElement() ));
CATimeSignature* ts = static_cast<CATimeSignature*>(
voice->previousByType(CAMusElement::TimeSignature, voice->lastPlayableElt()));
QList<CAPlayableLength> lll;
CAPlayableLength px;
lll << px.matchToBars(_mw->musElementFactory()->playableLength(), voice->lastTimeEnd(), b, ts);
CANote* prevNote = nullptr;
_noteLayout.clear();
for (i = 0; i < lll.size(); i++) {
note = new CANote(nonenharmonicPitch, lll[i], voice, -1);
voice->append(note, appendToChord);
_noteLayout.append(voice->lastMusElement());
std::cout << " -- " << lll[i].musicLength() << "." << lll[i].dotted();
CAStaff::placeAutoBar(note);
if (i > 0) {
_mw->musElementFactory()->configureSlur(staff, prevNote, note);
}
prevNote = note;
}
std::cout << " -- " << std::endl;
}
} else {
delete rest;
CABarline* b = static_cast<CABarline*>(voice->previousByType(CAMusElement::Barline,
voice->lastMusElement()));
CATimeSignature* ts = static_cast<CATimeSignature*>(
voice->previousByType(CAMusElement::TimeSignature, voice->lastPlayableElt()));
CAPlayableLength pr;
QList<CAPlayableLength> rests;
rests << pr.matchToBars(_mw->musElementFactory()->playableLength(), voice->lastTimeEnd(), b, ts);
for (i = 0; i < rests.size(); i++) {
rest = new CARest(CARest::Normal, rests[i], voice, 0, -1);
voice->append(rest, false);
}
}
}
// We make shure not to try to place a barline inside a chord or inside a tuplet
if (CACanorus::settings()->autoBar() && !appendToChord && (!_tupPla || _tupPla->isFirstInTuplet())) {
if (note)
CAStaff::placeAutoBar(note);
else
CAStaff::placeAutoBar(rest);
}
voice->synchronizeMusElements(); // probably not needed
CACanorus::undo()->pushUndoCommand();
// now we try to highlight the inserted note/chord by selection:
if (!appendToChord) {
v->clearSelection(); // remove old note/chord from selection
}
QList<CAPlayable*> lp = voice->getChord(voice->lastMusElement()->timeStart());
QList<CAMusElement*> lme;
for (int i = 0; i < lp.size(); i++)
lme << static_cast<CAMusElement*>(lp[i]);
_mw->currentScoreView()->addToSelection(lme);
// When I looking the last appended note is note showing up. Where goes it missing?
// Still without a clue. georg
// QList<CADrawableMusElement*> list = v->selection();
// std::cout << " Selektierte Elemente: " << list.size() << " Stück, oben "<<lp.size()<<" und "<<lme.size() << std::endl;
// scene tracking
QRectF scene = v->worldCoords();
double xlast = v->timeToCoordsSimpleVersion(voice->lastTimeStart());
if (((xlast + 50) > scene.right())) { // the magic number 50 should be defined, ist the width of an element
scene.translate(scene.width() / 2, 0);
v->setWorldCoords(scene, false, true);
}
v->updateHelpers();
v->repaint();
CACanorus::rebuildUI(_mw->document(), _mw->currentSheet());
// start timer eventually for chord detection
if (!_midiInChordTimer.isActive()) {
_midiInChordTimer.start(100); // Notes max 100 ms apart will form a chord
}
}
}
/*!
This function looks up the current key signiture. Then it computes the proper accidentials
for the note.
This function should be somewhere else, maybe in \a CADiatonicPitch ?
*/
CADiatonicPitch CAKeybdInput::matchPitchToKey(CAVoice* voice, CADiatonicPitch p)
{
// Default actual Key Signature is C
_actualKeySignature = CADiatonicPitch(CADiatonicPitch::C);
int i;
for (i = 0; i < 7; i++)
_actualKeySignatureAccs[i] = 0;
_actualKeyAccidentalsSum = 0;
// Trace which Key Signature might be in effect.
// We make a local copy for later optimisation by only updating at a non
// linear input
QList<CAMusElement*> keyList = voice->getPreviousByType(
CAMusElement::KeySignature, voice->lastTimeEnd());
if (keyList.size()) {
// set the note name and its accidental and the accidentals of the scale
CAKeySignature* effSig = static_cast<CAKeySignature*>(keyList.last());
_actualKeySignature = effSig->diatonicKey().diatonicPitch();
_actualKeyAccidentalsSum = 0;
for (i = 0; i < 7; i++) {
_actualKeySignatureAccs[i] = (effSig->accidentals())[i];
_actualKeyAccidentalsSum += _actualKeySignatureAccs[i];
}
}
// f and s (flat/sharp) are enharmonic pitches for p
CADiatonicPitch f = p + CAInterval(CAInterval::Diminished, CAInterval::Second);
CADiatonicPitch s = p - CAInterval(CAInterval::Diminished, CAInterval::Second);
// If the pitch appears in the keys scale we are done
if (p.accs() == _actualKeySignatureAccs[p.noteName() % 7]) {
return p;
}
// When the key is with flats we don't want sharps
if (_actualKeyAccidentalsSum < 0) {
if (f.accs() == _actualKeySignatureAccs[f.noteName() % 7])
return f;
if (p.accs() > 0)
return f;
}
// When the key is with sharps we don't want flats
if (_actualKeyAccidentalsSum > 0) {
if (s.accs() == _actualKeySignatureAccs[s.noteName() % 7]) {
return s;
}
if (p.accs() < 0) {
return s;
}
}
return p;
}
| 13,541
|
C++
|
.cpp
| 295
| 36.244068
| 133
| 0.600318
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,408
|
pluginmanager.cpp
|
canorusmusic_canorus/src/interface/pluginmanager.cpp
|
/** @file interface/pluginmanager.cpp
*
* Copyright (c) 2006-2020 Matevž Jekovec, Canorus development team
* All Rights Reserved. See AUTHORS for a complete list of authors.
*
* Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details.
*/
#ifndef SWIGCPP
#include "canorus.h"
#else
#include "interface/plugins_swig.h"
#endif
#include "interface/plugin.h"
#include "interface/pluginaction.h"
#include "interface/pluginmanager.h"
#include <QDir>
#include <QFile>
#include <QMenu>
#include <QXmlInputSource>
// define static members
QList<CAPlugin*> CAPluginManager::_pluginList;
QMultiHash<QString, CAPlugin*> CAPluginManager::_actionMap;
QHash<QString, CAPluginAction*> CAPluginManager::_exportFilterMap;
QHash<QString, CAPluginAction*> CAPluginManager::_importFilterMap;
/*!
\class CAPluginManager
This class is the backend for loading, unloading, installing, removing and executing plugins.
It's consists of two parts:
- Static members
Used globally to read, install/remove and enable/disable plugins.
- Non-static members
Inherits the QXml facilities and is used for parsing the plugin's descriptor file.
A plugin is installed or uninstalled using installPlugin() or removePlugin() methods. installMethod()
unpacks the compressed plugin into default user's plugins directory. removePlugin() deletes the plugin
directory from the disk.
After plugins are installed readPlugins() method should be called. This creates a list of available plugin
objects and stores their location paths.
To parse plugins descriptor files and enable plugins, call enablePlugins() to enable plugins marked as
auto-load in Canorus config file or enablePlugin() to load a specific plugin. These methods use Qt's XML
facilities to parse plugins descriptor files and use the non-static part of the class. They also require
an already created main window as the parser creates menu structures, toolbars and other elements
the plugin might offer.
An action (eg. when a user moves mouse in score viewport) is triggered by calling action() method and
pass the action type (eg. "onMouseMove") and other parameters. actionExport() and actionImport() are
separated and are called when Canorus user wants to export/import a document.
\todo Frontend window for plugin manipulation.
\sa CAPlugin, CAPluginManagerWin
*/
/*!
Used if parsing plugin's descriptor file.
It uses the given \a mainWin in order to create new menus and toolbars the plugin might include.
If the plugin has already been created (eg. using the same plugin in multiple main windows)
\a plugin is the existing plugin.
*/
CAPluginManager::CAPluginManager(CAMainWin* mainWin, CAPlugin* plugin)
{
_mainWin = mainWin;
_curPlugin = plugin;
_curPluginCanorusVersion = CANORUS_VERSION; /// \todo This should be read from the descriptor file as well
}
CAPluginManager::~CAPluginManager()
{
}
/*!
Reads the system and user's plugins directories and adds all the plugins to the internal plugins list.
\warning This function doesn't enable or initialize any of the plugins - use enablePlugins() for this.
\todo Add support for a user plugins directory.
\sa enablePlugin(), enablePlugins()
*/
void CAPluginManager::readPlugins()
{
if (QDir::searchPaths("plugins").size() > 0) {
QString systemPluginsPath = QDir::searchPaths("plugins")[0];
QList<QString> pluginPaths;
// search the plugins paths and creates a list of directories for each plugin
QDir curDir(systemPluginsPath);
for (int j = 0; j < static_cast<int>(curDir.count()); j++) {
pluginPaths << curDir.absolutePath() + "/" + curDir[j];
}
for (int i = 0; i < pluginPaths.size(); i++) {
QXmlSimpleReader reader;
QFile* file = new QFile(pluginPaths[i] + "/canorusplugin.xml");
file->open(QIODevice::ReadOnly);
// test if the descriptor file can be opened
if (!file->isOpen()) {
delete file;
continue;
}
delete file;
CAPlugin* plugin = new CAPlugin();
plugin->setDirName(pluginPaths[i]);
_pluginList << plugin;
}
}
}
/*!
Enables and initializes all plugins, which are marked as auto-load in Canorus config file.
Returns true if all the plugins were successfully loaded, otherwise False.
\todo auto-load not yet implemented. It currently enables all the plugins.
\sa enablePlugin(), disablePlugins()
*/
bool CAPluginManager::enablePlugins(CAMainWin* mainWin)
{
bool res = true;
for (int i = 0; i < _pluginList.size(); i++) {
if (!enablePlugin(_pluginList[i], mainWin))
res = false;
}
return res;
}
/*!
Disable and deinitializes all plugins.
Return True, if all the plugins were successfully loaded, otherwise False.
\sa disablePlugin(), enablePlugins()
*/
bool CAPluginManager::disablePlugins()
{
bool res = true;
for (int i = 0; i < _pluginList.size(); i++) {
if (!disablePlugin(_pluginList[i]))
res = false;
}
return res;
}
/*!
Enables the plugin \a plugin and initializes it (action "onInit").
Returns True, if the plugin was loaded successfully, otherwise False.
\sa disablePlugin()
*/
bool CAPluginManager::enablePlugin(CAPlugin* plugin, CAMainWin* mainWin)
{
CAPluginManager* pm;
QFile* file = new QFile(plugin->dirName() + "/canorusplugin.xml");
file->open(QIODevice::ReadOnly);
QXmlInputSource in(file);
QXmlSimpleReader reader;
reader.setContentHandler(pm = new CAPluginManager(mainWin, plugin));
reader.parse(in);
delete file;
delete pm;
if (plugin->isEnabled())
// plugin was enabled before
return true;
// plugin wasn't enabled before, add its actions to local list
QList<QString> actions = plugin->actionList();
for (int i = 0; i < actions.size(); i++) {
_actionMap.insertMulti(actions[i], plugin);
}
plugin->setEnabled(true);
return plugin->action("onInit", mainWin);
}
/*!
Deinitializes the given \a plugin and remove any menus, toolbars and other GUI elements the plugin might
have created from all the main windows.
Plugin is unloaded, but still remains on the list - it's only disabled.
Returns True, if plugin was unloaded successfully, otherwise False.
*/
bool CAPluginManager::disablePlugin(CAPlugin* plugin)
{
if (!plugin->isEnabled())
return true;
bool res = true;
for (int i = 0; i < CACanorus::mainWinList().size(); i++) {
if (!plugin->action("onExit", CACanorus::mainWinList()[i])) {
res = false;
}
}
plugin->setEnabled(false);
// remove plugin specific actions from generic plugins actions list
QList<QString> actions = plugin->actionList();
for (int i = 0; i < actions.size(); i++) { // QMultiHash doesn't support remove(key, value) or remove(value), only remove(key) - we have to do this manually now
QList<CAPlugin*> plugList;
while (CAPlugin* val = _actionMap.take(actions[i])) {
if (val != plugin) { // while val exists and != plugin
plugList << val; // remember deleted values which don't belong to the disabled plugin
}
}
for (int j = 0; j < plugList.size(); j++) // restore the hash - add deleted non-disabled actions of the other plugins back to the hash
_actionMap.insertMulti(actions[i], plugList[j]);
}
return res;
}
/*!
Extracts the plugin package at \a path to user's plugins directory.
Returns True, if plugin was installed and loaded successfully, otherwise False.
\sa removePlugin()
*/
bool CAPluginManager::installPlugin(QString)
{
// Note Reinhard: zlib is there
/// \todo zlib needed
return false;
}
/*!
Disables and deletes the directory containing the given \a plugin.
\sa installPlugin(), disablePlugin()
*/
bool CAPluginManager::removePlugin(CAPlugin* plugin)
{
disablePlugin(plugin);
bool res = QFile::remove(plugin->dirName());
delete plugin;
return res;
}
bool CAPluginManager::startElement(const QString&, const QString&, const QString& qName, const QXmlAttributes& attributes)
{
_tree.push(qName);
if (qName == "plugin") {
}
if (_curPlugin) {
if (qName == "description") {
_curPluginLocale = attributes.value("lang");
} else if (qName == "text") {
_curActionLocale = attributes.value("lang");
} else if (qName == "title") {
_curMenuLocale = attributes.value("lang");
} else if (qName == "export-filter") {
} else if (qName == "import-filter") {
} else if (qName == "action") {
_curActionLang = "python";
_curActionFunction.clear();
_curActionFilename.clear();
_curActionArgs.clear();
_curActionText.clear();
_curActionLocale.clear();
_curActionName.clear();
_curActionExportFilter.clear();
_curActionImportFilter.clear();
_curActionOnAction.clear();
_curActionParentMenu.clear();
_curActionParentToolbar.clear();
_curActionRefresh = false;
} else if (qName == "menu") {
_curMenuTitle.clear();
_curMenuName.clear();
_curMenuLocale.clear();
_curMenuParentMenu.clear();
} else if (qName == "toolbar") {
}
}
return true;
}
bool CAPluginManager::endElement(const QString&, const QString&, const QString& qName)
{
_tree.pop();
if (_curPlugin) {
// top-level tags
if (qName == "canorus-version") {
_curPluginCanorusVersion = _curChars;
} else if (qName == "name") {
if (_tree.back() == "plugin")
_curPlugin->setName(_curChars);
else if (_tree.back() == "action")
_curActionName = _curChars;
else if (_tree.back() == "menu")
_curMenuName = _curChars;
} else if (qName == "version") {
_curPlugin->setVersion(_curChars);
} else if (qName == "author") {
_curPlugin->setAuthor(_curChars);
} else if (qName == "home-url") {
_curPlugin->setHomeUrl(_curChars);
} else if (qName == "update-url") {
_curPlugin->setUpdateUrl(_curChars);
} else if (qName == "description") {
_curPlugin->setDescription(_curChars, _curPluginLocale);
} else if (qName == "separator") {
_curPlugin->menu(_curActionParentMenu)->addSeparator();
} else if (qName == "action") {
CAPluginAction* action = new CAPluginAction(_curPlugin, _curActionName, _curActionLang, _curActionFunction, _curActionArgs, _curActionFilename);
if (!_curActionParentMenu.isEmpty()) {
#ifndef SWIGCPP
action->setParent(_mainWin);
#else
#endif
_curPlugin->menu(_curActionParentMenu)->addAction(action);
}
action->setOnAction(_curActionOnAction);
action->setExportFilters(_curActionExportFilter);
action->setImportFilters(_curActionImportFilter);
action->setTexts(_curActionText);
action->setRefresh(_curActionRefresh);
if (!_curActionParentToolbar.isEmpty())
;
// TODO: add action to toolbar
// Add import and export filters to the generic list for faster lookup
QList<QString> filters;
filters = _curActionExportFilter.values();
for (int i = 0; i < filters.size(); i++) {
_exportFilterMap[filters[i]] = action;
#ifndef SWIGCPP
_mainWin->exportDialog()->setNameFilters(_mainWin->exportDialog()->nameFilters() << filters[i]);
#else
// TODO
#endif
}
filters = _curActionImportFilter.values();
for (int i = 0; i < filters.size(); i++) {
_importFilterMap[filters[i]] = action;
#ifndef SWIGCPP
_mainWin->importDialog()->setNameFilters(_mainWin->importDialog()->nameFilters() << filters[i]);
#else
// TODO
#endif
}
_curPlugin->addAction(action);
} else if (qName == "menu") {
#ifndef SWIGCPP
QMenu* menu;
if (_curMenuParentMenu.isEmpty()) {
// no parefnt menu set, add it to the top-level mainwindow's menu before the Help menu
menu = new QMenu(_mainWin->menuBar());
_mainWin->menuBar()->insertMenu(_mainWin->menuBar()->actions().last(), menu);
} else {
// parent menu set, find it and add a new submenu to it
menu = new QMenu(_curPlugin->menu(_curMenuParentMenu));
_curPlugin->menu(_curMenuParentMenu)->addMenu(menu);
}
menu->setObjectName(_curMenuName);
if (_curMenuTitle.contains(QLocale::system().name()))
menu->setTitle(_curMenuTitle[QLocale::system().name()]);
else
menu->setTitle(_curMenuTitle[""]);
_curPlugin->addMenu(_curMenuName, menu);
#else
#endif
} else
// action level
if (qName == "on-action") {
_curActionOnAction = _curChars;
} else if (qName == "lang") {
if (_tree.back() == "action")
_curActionLocale = _curChars;
else if (_tree.back() == "menu")
_curMenuLocale = _curChars;
} else if (qName == "function") {
_curActionFunction = _curChars;
} else if (qName == "filename") {
_curActionFilename = _curChars;
} else if (qName == "text") {
_curActionText[_curActionLocale] = _curChars;
} else if (qName == "args") {
_curActionArgs << _curChars;
} else if (qName == "parent-menu") {
_curActionParentMenu = _curChars;
} else if (qName == "export-filter") {
_curActionExportFilter[_curActionLocale] = _curChars;
} else if (qName == "import-filter") {
_curActionImportFilter[_curActionLocale] = _curChars;
} else if (qName == "refresh") {
_curActionRefresh = true;
} else
// menu level
if (qName == "title") {
_curMenuTitle[_curMenuLocale] = _curChars;
}
}
return true;
}
bool CAPluginManager::fatalError(const QXmlParseException&)
{
return false;
}
bool CAPluginManager::characters(const QString& ch)
{
_curChars = ch;
return true;
}
/*!
\fn bool CACanorus::exportFilterExists(const QString filter)
Returns True if a plugin with the given filter in export dialog exists.
Returns False if a plugin with such a filter doesn't exist. Internal LilyPond export code is usually
used instead.
\sa importFilterExists(const QString filter)
*/
/*!
Finds the appropriate action having the given export \a filter and calls it using the given \a document and
\a fileName.
\sa importAction()
*/
void CAPluginManager::exportAction(QString filter, CADocument* document, QString filename)
{
_exportFilterMap[filter]->plugin()->callAction(_exportFilterMap[filter], nullptr, document, nullptr, nullptr, filename);
}
/*!
\fn bool CACanorus::importFilterExists(const QString filter)
Returns True if a plugin with the given filter in import dialog exists.
Returns False if a plugin with such a filter doesn't exist. Internal LilyPond import code is usually
used instead.
\sa exportFilterExists(const QString filter)
*/
/*!
Finds the appropriate action having the given import \a filter and calls it using the given \a document and
\a fileName. The given \a document should already be created before calling this method.
\sa exportAction()
*/
void CAPluginManager::importAction(QString filter, CADocument* document, QString filename)
{
_importFilterMap[filter]->plugin()->callAction(_importFilterMap[filter], nullptr, document, nullptr, nullptr, filename);
}
/*!
Gathers all the plugins actions having the given \a val <action> <name> tag in its descriptor file and
calls them.
This method is usually triggered automatically by Canorus signals (like mouseClick on score viewport or
a menu action).
\sa importAction(), exportAction()
*/
void CAPluginManager::action(QString val, CADocument* document, QEvent* evt, QPoint* coords, CAMainWin* mainWin)
{
QList<CAPlugin*> list = _actionMap.values(val);
for (int i = 0; i < list.size(); i++) {
list[i]->action(val, mainWin, document, evt, coords);
}
}
/*!
\var CACanorus::_pluginList
List of both enabled and disabled plugins installed.
*/
/*!
\var CACanorus::_actionMap
Map of all the plugins actions names and actual plugins.
This is used for faster (constant time) plugin look-up when running a specific action.
\sa _exportActionMap, _importActionMap
*/
/*!
\var CACanorus::_exportActionMap
Map of all the plugins export actions names and actual plugins.
This is used for faster (constant time) plugin look-up when running a specific action.
\sa _actionMap, _importActionMap
*/
/*!
\var CACanorus::_importActionMap
Map of all the plugins import actions names and actual plugins.
This is used for faster (constant time) plugin look-up when running a specific action.
\sa _actionMap, _exportActionMap
*/
/*!
\var CACanorus::_depth
Hierarchy track of the current node.
*/
| 17,503
|
C++
|
.cpp
| 440
| 33.506818
| 164
| 0.663741
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,409
|
plugins_swig.cpp
|
canorusmusic_canorus/src/interface/plugins_swig.cpp
|
#include "plugins_swig.h"
//some comments and maybe code one day
QList<CAMainWin*> CACanorus::_mainWinList;
| 109
|
C++
|
.cpp
| 3
| 35
| 42
| 0.790476
|
canorusmusic/canorus
| 34
| 14
| 92
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.