1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
/**********************************************************************
Audacity: A Digital Audio Editor
@file BeatsNumericConverterFormatter.cpp
Dmitry Vedenko
**********************************************************************/
#include "BeatsNumericConverterFormatter.h"
#include <algorithm>
#include <array>
#include <cmath>
#include "NumericConverterRegistry.h"
#include "NumericConverterFormatterContext.h"
#include "SampleCount.h"
#include "Project.h"
#include "ProjectTimeSignature.h"
namespace
{
// This function will return 10^pow
// No overflow checks are performed, it is assumed that 10^pow
// does not overflow
constexpr size_t Get10Pow (size_t pow)
{
return pow > 0 ? 10 * Get10Pow(pow - 1) : 1;
}
/* i18n-hint: The music theory "bar" */
const auto BarString = XO("bar");
/* i18n-hint: The music theory "beat" */
const auto BeatString = XO("beat");
class BeatsFormatter final :
public NumericConverterFormatter,
public PrefsListener
{
public:
static constexpr std::array<size_t, 3> MIN_DIGITS { 3, 2, 2 };
static constexpr std::array<size_t, 3> UPPER_BOUNDS {
Get10Pow(MIN_DIGITS[0] - 1) + 1, Get10Pow(MIN_DIGITS[1] - 1) + 1,
Get10Pow(MIN_DIGITS[2] - 1) + 1
};
BeatsFormatter(const FormatterContext& context, int fracPart, bool timeFormat)
: mContext { context }
, mFracPart { fracPart }
, mFieldValueOffset { timeFormat ? 1 : 0 }
{
auto project = mContext.GetProject();
if (!project)
return;
mBarString = BarString.Translation();
mBeatString = BeatString.Translation();
UpdateFormat(*project);
// Subscribing requires non-const reference
mTimeSignatureChangedSubscription =
const_cast<ProjectTimeSignature&>(ProjectTimeSignature::Get(*project))
.Subscribe(
[this](const auto&)
{
// Receiving this message means that project is
// alive and well
UpdateFormat(*mContext.GetProject());
Publish({});
});
}
//! Check that field exists and has enough digits to fit the value
bool CheckField(size_t fieldIndex, int value) const noexcept
{
if (fieldIndex >= mFields.size())
return false;
const auto digitsCount = mFields[fieldIndex].digits;
// Format always allows at least two digits
const auto lowerRange =
digitsCount > MIN_DIGITS[fieldIndex] ? Get10Pow(digitsCount - 1) : 0;
const auto upperRange = Get10Pow(digitsCount);
return value >= int(lowerRange) && value < int(upperRange);
}
bool CheckFracField (int newLts) const noexcept
{
if (mFracPart > newLts)
return CheckField(2, mFracPart / mLowerTimeSignature);
else
return mFields.size() == 2;
}
void UpdateFields (size_t barsDigits)
{
mFields.clear();
mDigits.clear();
// Range is assumed to allow 999 bars.
auto& barsField =
mFields.emplace_back(NumericField::WithDigits(barsDigits));
barsField.label = L" " + mBarString + L" ";
// Beats format is 1 based. For the time point "0" the expected output is
// "1 bar 1 beat [1]" For this reason we use (uts + 1) as the "range". On
// top of that, we want at least two digits to be shown. NumericField
// accepts range as in [0, range), so add 1.
auto& beatsField = mFields.emplace_back(NumericField::ForRange(
std::max<size_t>(UPPER_BOUNDS[1], mUpperTimeSignature + 1)));
beatsField.label = L" " + mBeatString;
const auto hasFracPart = mFracPart > mLowerTimeSignature;
if (hasFracPart)
{
beatsField.label += L" ";
// See the reasoning above about the range
auto& fracField = mFields.emplace_back(NumericField::ForRange(
std::max(11, mFracPart / mLowerTimeSignature + 1)));
}
// Fill the aux mDigits structure
size_t pos = 0;
for (size_t i = 0; i < mFields.size(); i++)
{
mFields[i].pos = pos;
for (size_t j = 0; j < mFields[i].digits; j++)
{
mDigits.push_back(DigitInfo { i, j, pos });
pos++;
}
pos += mFields[i].label.length();
}
}
void UpdateFormat(const AudacityProject& project)
{
auto& timeSignature = ProjectTimeSignature::Get(project);
const double newTempo = timeSignature.GetTempo();
const int newUts = timeSignature.GetUpperTimeSignature();
const int newLts = timeSignature.GetLowerTimeSignature();
if (newTempo == mTempo && newUts == mUpperTimeSignature && newLts == mLowerTimeSignature)
return ;
const bool formatOk = CheckField(1, newUts) && CheckFracField(newLts);
mTempo = newTempo;
mUpperTimeSignature = newUts;
mLowerTimeSignature = newLts;
// 1/4 = BPM is used for now
const auto quarterLength = 60.0 / mTempo;
const auto beatLength = quarterLength * 4.0 / mLowerTimeSignature;
const auto barLength = mUpperTimeSignature * beatLength;
mFieldLengths[0] = barLength;
mFieldLengths[1] = beatLength;
const auto hasFracPart = mFracPart > mLowerTimeSignature;
if (hasFracPart)
{
const auto fracLength = beatLength * mLowerTimeSignature / mFracPart;
mFieldLengths[2] = fracLength;
}
if (formatOk)
return ;
UpdateFields(MIN_DIGITS[0]);
}
void UpdateFormatForValue(double value, bool canShrink) override
{
// Beats formatter does not support negative values
value = std::max(0.0, value);
// ForRange has a preserved weird behavior
const auto barsCount =
// Range is not inclusive
1 +
// Bars can start from 1
mFieldValueOffset +
static_cast<int>(std::floor(value / mFieldLengths[0]));
const auto barsField = NumericField::ForRange(
barsCount, true, MIN_DIGITS[0]);
const auto oldDigits = mFields[0].digits;
const bool updateNeeded = canShrink ? oldDigits != barsField.digits :
oldDigits < barsField.digits;
if (!updateNeeded)
return;
UpdateFields(barsField.digits);
Publish({ value, oldDigits > mFields[0].digits });
}
void UpdateResultString(ConversionResult& result) const
{
for (size_t fieldIndex = 0; fieldIndex < mFields.size(); ++fieldIndex)
{
result.valueString +=
result.fieldValueStrings[fieldIndex] + mFields[fieldIndex].label;
}
}
ConversionResult ValueToString(double value, bool) const override
{
ConversionResult result;
result.fieldValueStrings.resize(mFields.size());
if (value < 0)
{
for (size_t fieldIndex = 0; fieldIndex < mFields.size (); ++fieldIndex)
{
const auto digitsCount = mFields[fieldIndex].digits;
auto& fieldValue = result.fieldValueStrings[fieldIndex];
for (int digitIndex = 0; digitIndex < digitsCount; ++digitIndex)
fieldValue += L"-";
}
UpdateResultString(result);
return result;
}
// Calculate the epsilon only once, so the total loss of precision is addressed.
// This is a "multiplicative" epsilon, so there is no need to calculate 1 + eps every time.
const auto eps =
1.0 + std::max(1.0, value) * std::numeric_limits<double>::epsilon();
for (size_t fieldIndex = 0; fieldIndex < mFields.size(); ++fieldIndex)
{
const auto fieldLength = mFieldLengths[fieldIndex];
const auto fieldValue = std::max(
0, static_cast<int>(std::floor(value * eps / fieldLength)));
result.fieldValueStrings[fieldIndex] = wxString::Format(
mFields[fieldIndex].formatStr, fieldValue + mFieldValueOffset);
value = value - fieldValue * fieldLength;
}
UpdateResultString(result);
return result;
}
std::optional<double> StringToValue(const wxString& valueString) const override
{
if (
mFields.size() > 0 &&
valueString.Mid(mFields[0].pos, 1) == wxChar('-'))
return std::nullopt;
double t = 0.0;
size_t lastIndex = 0;
for (size_t i = 0; i < mFields.size(); i++)
{
const auto& field = mFields[i];
const size_t labelIndex = field.label.empty() ?
wxString::npos :
valueString.find(field.label, lastIndex);
long val;
const auto fieldStringValue = valueString.Mid(
lastIndex,
labelIndex == wxString::npos ? labelIndex : labelIndex - lastIndex);
if (!fieldStringValue.ToLong(&val))
return std::nullopt;
t += (val - mFieldValueOffset) * mFieldLengths[i];
lastIndex = labelIndex + field.label.Length();
}
return t;
}
double SingleStep(double value, int digitIndex, bool upwards) const override
{
if (digitIndex < 0 || size_t(digitIndex) >= mDigits.size())
return value;
const auto& digit = mDigits[digitIndex];
const auto& fieldIndex = digit.field;
const auto& field = mFields[fieldIndex];
const auto stepSize = mFieldLengths[fieldIndex] *
std::pow(10, field.digits - digit.index - 1);
return upwards ? value + stepSize : value - stepSize;
}
void UpdatePrefs() override
{
auto project = mContext.GetProject();
if (!project)
return;
auto barString = BarString.Translation();
auto beatString = BeatString.Translation();
if (barString == mBarString && beatString == mBeatString)
return;
mBarString = barString;
mBeatString = beatString;
UpdateFormat(*project);
}
private:
const FormatterContext mContext;
Observer::Subscription mTimeSignatureChangedSubscription;
double mTempo { 0.0 };
int mUpperTimeSignature { 0 };
int mLowerTimeSignature { 0 };
const int mFracPart;
const int mFieldValueOffset;
std::array<double, 3> mFieldLengths {};
wxString mBarString;
wxString mBeatString;
};
class BeatsNumericConverterFormatterFactory final :
public NumericConverterFormatterFactory
{
public:
BeatsNumericConverterFormatterFactory (int fracPart, bool timeFormat)
: mFracPart { fracPart }
, mTimeFormat { timeFormat }
{
}
std::unique_ptr<NumericConverterFormatter>
Create(const FormatterContext& context) const override
{
if (!IsAcceptableInContext(context))
return {};
return std::make_unique<BeatsFormatter>(context, mFracPart, mTimeFormat);
}
bool IsAcceptableInContext(const FormatterContext& context) const override
{
return context.HasProject();
}
private:
const int mFracPart;
const bool mTimeFormat;
};
auto BuildBeatsGroup(bool timeFormat)
{
return NumericConverterFormatterGroup(
timeFormat ? "beatsTime" : "beatsDuration",
timeFormat ? NumericConverterType_TIME() : NumericConverterType_DURATION(),
NumericConverterFormatterItem(
/* i18n-hint: "bar" and "beat" are musical notation elements. */
"beats", XO("bar:beat"),
std::make_unique<BeatsNumericConverterFormatterFactory>(0, timeFormat)),
NumericConverterFormatterItem(
/* i18n-hint: "bar" and "beat" are musical notation elements. "tick"
corresponds to a 16th note. */
"beats16", XO("bar:beat:tick"),
std::make_unique<BeatsNumericConverterFormatterFactory>(16, timeFormat)));
}
NumericConverterItemRegistrator beatsTime {
BuildBeatsGroup(true),
Registry::Placement { "parsed", { Registry::OrderingHint::After, L"parsedTime" } }
};
NumericConverterItemRegistrator beatsDuration {
BuildBeatsGroup(false),
Registry::Placement { "parsed", { Registry::OrderingHint::After, L"parsedDuration" } }
};
} // namespace
std::unique_ptr<NumericConverterFormatter> CreateBeatsNumericConverterFormatter(
const FormatterContext& context, int fracPart /*= 0*/,
bool timeFormat /*= true*/)
{
return std::make_unique<BeatsFormatter>(context, fracPart, timeFormat);
}
|