Skip to content

Commit

Permalink
Cleanup (#210)
Browse files Browse the repository at this point in the history
  • Loading branch information
wbaldoumas authored Dec 8, 2024
1 parent 3af48e5 commit ff6dd12
Show file tree
Hide file tree
Showing 18 changed files with 52 additions and 186 deletions.
21 changes: 9 additions & 12 deletions src/BaroquenMelody.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ namespace BaroquenMelody.App;
/// </summary>
public partial class App : Application
{
private const string Title = "Baroquen Melody";

private const string IsDarkModeKey = "IsDarkMode";

private readonly IThemeProvider _themeProvider;

public App(IThemeProvider themeProvider)
Expand All @@ -15,25 +19,18 @@ public App(IThemeProvider themeProvider)

_themeProvider = themeProvider;

_themeProvider.IsDarkMode = Preferences.Default.Get("IsDarkMode", defaultValue: true);

MainPage = new MainPage
{
Title = "Baroquen Melody"
};
_themeProvider.IsDarkMode = Preferences.Default.Get(IsDarkModeKey, defaultValue: true);
}

protected override Window CreateWindow(IActivationState? activationState)
{
var window = base.CreateWindow(activationState) ?? throw new InvalidOperationException("Window is null");

window.Title = "Baroquen Melody";

window.Destroying += (_, _) =>
var window = new Window(new MainPage { Title = Title })
{
Preferences.Default.Set("IsDarkMode", _themeProvider.IsDarkMode);
Title = Title
};

window.Destroying += (_, _) => { Preferences.Default.Set(IsDarkModeKey, _themeProvider.IsDarkMode); };

return window;
}
}
3 changes: 2 additions & 1 deletion src/BaroquenMelody.Library/Choices/ChordChoice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public override int GetHashCode()
{
return NoteChoices.Aggregate(
HashCodeGeneration.Seed,
(current, noteChoice) => current * HashCodeGeneration.Multiplier ^ noteChoice.GetHashCode());
(current, noteChoice) => current * HashCodeGeneration.Multiplier ^ noteChoice.GetHashCode()
);
}
}
}
14 changes: 5 additions & 9 deletions src/BaroquenMelody.Library/Choices/DuetChordChoiceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ internal sealed class DuetChordChoiceRepository : IChordChoiceRepository

private readonly LazyCartesianProduct<NoteChoice, NoteChoice> _noteChoices;

public DuetChordChoiceRepository(CompositionConfiguration compositionConfiguration, INoteChoiceGenerator noteChoiceGenerator)
public DuetChordChoiceRepository(CompositionConfiguration configuration, INoteChoiceGenerator noteChoiceGenerator)
{
if (compositionConfiguration.Instruments.Count != NumberOfInstruments)
if (configuration.Instruments.Count != NumberOfInstruments)
{
throw new ArgumentException(
"The composition configuration must contain exactly two instrument configurations.",
nameof(compositionConfiguration)
nameof(configuration)
);
}

var noteChoicesForInstruments = compositionConfiguration.Instruments
.OrderBy(static instrument => instrument)
var noteChoicesForInstruments = configuration.Instruments
.Order()
.Select(noteChoiceGenerator.GenerateNoteChoices)
.ToList();

Expand All @@ -36,8 +36,4 @@ [.. noteChoicesForInstruments[1]]
public BigInteger Count => _noteChoices.Size;

public ChordChoice GetChordChoice(BigInteger id) => _noteChoices[id].ToChordChoice();

public BigInteger GetChordChoiceId(ChordChoice chordChoice) => _noteChoices.IndexOf(
(chordChoice.NoteChoices[0], chordChoice.NoteChoices[1])
);
}
7 changes: 0 additions & 7 deletions src/BaroquenMelody.Library/Choices/IChordChoiceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,4 @@ internal interface IChordChoiceRepository
/// <param name="id"> The ID of the <see cref="ChordChoice"/> to get. </param>
/// <returns> The <see cref="ChordChoice"/> for the given ID. </returns>
public ChordChoice GetChordChoice(BigInteger id);

/// <summary>
/// Get the ID of the given <see cref="ChordChoice"/>.
/// </summary>
/// <param name="chordChoice"> The <see cref="ChordChoice"/> to get the ID of. </param>
/// <returns> The ID of the given <see cref="ChordChoice"/>. </returns>
BigInteger GetChordChoiceId(ChordChoice chordChoice);
}
4 changes: 2 additions & 2 deletions src/BaroquenMelody.Library/Choices/NoteChoiceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ namespace BaroquenMelody.Library.Choices;
/// <inheritdoc cref="INoteChoiceGenerator"/>
internal sealed class NoteChoiceGenerator(byte minScaleStepChange = 1, byte maxScaleStepChange = CompositionConfiguration.MaxScaleStepChange) : INoteChoiceGenerator
{
private readonly NoteMotion[] noteMotions = [NoteMotion.Ascending, NoteMotion.Descending];
private readonly NoteMotion[] _noteMotions = [NoteMotion.Ascending, NoteMotion.Descending];

public ISet<NoteChoice> GenerateNoteChoices(Instrument instrument) => Enumerable
.Range(minScaleStepChange, maxScaleStepChange - minScaleStepChange + 1)
.Select(static scaleStepChange => (byte)scaleStepChange)
.SelectMany(scaleStepChange => noteMotions.Select(noteMotion => new NoteChoice(instrument, noteMotion, scaleStepChange)))
.SelectMany(scaleStepChange => _noteMotions.Select(noteMotion => new NoteChoice(instrument, noteMotion, scaleStepChange)))
.Append(new NoteChoice(instrument, NoteMotion.Oblique, 0))
.ToFrozenSet();
}
15 changes: 3 additions & 12 deletions src/BaroquenMelody.Library/Choices/QuartetChordChoiceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ public QuartetChordChoiceRepository(
);
}

var noteChoicesForInstruments = configuration.InstrumentConfigurations
.OrderBy(static instrumentConfiguration => instrumentConfiguration.Instrument)
.Select(instrumentConfiguration => noteChoiceGenerator.GenerateNoteChoices(instrumentConfiguration.Instrument))
var noteChoicesForInstruments = configuration.Instruments
.Order()
.Select(noteChoiceGenerator.GenerateNoteChoices)
.ToList();

_noteChoices = new LazyCartesianProduct<NoteChoice, NoteChoice, NoteChoice, NoteChoice>(
Expand All @@ -40,13 +40,4 @@ [.. noteChoicesForInstruments[3]]
public BigInteger Count => _noteChoices.Size;

public ChordChoice GetChordChoice(BigInteger id) => _noteChoices[id].ToChordChoice();

public BigInteger GetChordChoiceId(ChordChoice chordChoice) => _noteChoices.IndexOf(
(
chordChoice.NoteChoices[0],
chordChoice.NoteChoices[1],
chordChoice.NoteChoices[2],
chordChoice.NoteChoices[3]
)
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,4 @@ public SoloChordChoiceRepository(CompositionConfiguration compositionConfigurati
public BigInteger Count => _noteChoices.Count;

public ChordChoice GetChordChoice(BigInteger id) => _noteChoices[(int)id].ToChordChoice();

public BigInteger GetChordChoiceId(ChordChoice chordChoice) => _noteChoices.IndexOf(chordChoice.NoteChoices[0]);
}
14 changes: 3 additions & 11 deletions src/BaroquenMelody.Library/Choices/TrioChordChoiceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ public TrioChordChoiceRepository(CompositionConfiguration configuration, INoteCh
);
}

var noteChoicesForInstruments = configuration.InstrumentConfigurations
.OrderBy(static instrumentConfiguration => instrumentConfiguration.Instrument)
.Select(instrumentConfiguration => noteChoiceGenerator.GenerateNoteChoices(instrumentConfiguration.Instrument))
var noteChoicesForInstruments = configuration.Instruments
.Order()
.Select(noteChoiceGenerator.GenerateNoteChoices)
.ToList();

_noteChoices = new LazyCartesianProduct<NoteChoice, NoteChoice, NoteChoice>(
Expand All @@ -37,12 +37,4 @@ [.. noteChoicesForInstruments[2]]
public BigInteger Count => _noteChoices.Size;

public ChordChoice GetChordChoice(BigInteger id) => _noteChoices[id].ToChordChoice();

public BigInteger GetChordChoiceId(ChordChoice chordChoice) => _noteChoices.IndexOf(
(
chordChoice.NoteChoices[0],
chordChoice.NoteChoices[1],
chordChoice.NoteChoices[2]
)
);
}
5 changes: 2 additions & 3 deletions src/BaroquenMelody.Library/Composers/Composer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,15 @@ private Composition ApplyPhrasing(Composition initialComposition, BaroquenTheme

compositionPhraser.AddTheme(theme);

var currentMeasureIndex = 0;
var phrasedMeasures = new List<Measure>();

foreach (var measure in initialComposition.Measures)
foreach (var (currentMeasureIndex, measure) in initialComposition.Measures.Index())
{
cancellationToken.ThrowIfCancellationRequested();

phrasedMeasures.Add(measure);

if (currentMeasureIndex++ % compositionConfiguration.PhrasingConfiguration.MinPhraseLength == 0)
if (currentMeasureIndex % compositionConfiguration.PhrasingConfiguration.MinPhraseLength == 0)
{
compositionPhraser.AttemptPhraseRepetition(phrasedMeasures);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public IEnumerable<SevenBitNumber> GetPrecedingVelocities(FixedSizeList<Beat> pr
{
Validate(precedingBeats, instrument);

return precedingBeats.TakeLast(count)
return precedingBeats
.TakeLast(count)
.Reverse()
.Select(beat =>
{
Expand Down
6 changes: 3 additions & 3 deletions src/BaroquenMelody.Library/MusicTheory/NoteOnsetCalculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ internal sealed class NoteOnsetCalculator(
CompositionConfiguration compositionConfiguration
) : INoteOnsetCalculator
{
private static readonly MusicalTimeSpan _resolution = MusicalTimeSpan.ThirtySecond;
private static readonly MusicalTimeSpan Resolution = MusicalTimeSpan.ThirtySecond;

public BitArray CalculateNoteOnsets(OrnamentationType ornamentationType)
{
var bitArray = InitializeNoteOnsetBitArray(compositionConfiguration.Meter);
var primaryNoteDuration = musicalTimeSpanCalculator.CalculatePrimaryNoteTimeSpan(ornamentationType, compositionConfiguration.Meter);
var ornamentationCount = ornamentationType.OrnamentationCount();
var noteOnsetCursor = primaryNoteDuration.DivideBy(_resolution);
var noteOnsetCursor = primaryNoteDuration.DivideBy(Resolution);

for (var ornamentationStep = 0; ornamentationStep < ornamentationCount; ornamentationStep++)
{
var ornamentationDuration = musicalTimeSpanCalculator.CalculateOrnamentationTimeSpan(ornamentationType, compositionConfiguration.Meter, ornamentationStep);
var cursorProgressionValue = ornamentationDuration.DivideBy(_resolution);
var cursorProgressionValue = ornamentationDuration.DivideBy(Resolution);

bitArray[noteOnsetCursor] = true;

Expand Down
30 changes: 15 additions & 15 deletions src/BaroquenMelody.Library/Phrasing/CompositionPhraser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ internal sealed class CompositionPhraser(
CompositionConfiguration compositionConfiguration
) : ICompositionPhraser
{
private readonly List<RepeatedPhrase> phrasesToRepeat = [];
private readonly List<RepeatedPhrase> _phrasesToRepeat = [];

private readonly Queue<RepeatedPhrase> coolOffPhrases = new();
private readonly Queue<RepeatedPhrase> _coolOffPhrases = new();

private List<RepeatedPhrase> themePhrasesToRepeat = [];
private List<RepeatedPhrase> _themePhrasesToRepeat = [];

private RepeatedPhrase? themeCoolOffPhrase;
private RepeatedPhrase? _themeCoolOffPhrase;

public void AttemptPhraseRepetition(List<Measure> measures)
{
Expand All @@ -39,24 +39,24 @@ public void AttemptPhraseRepetition(List<Measure> measures)

public void AddTheme(BaroquenTheme theme)
{
themePhrasesToRepeat = themeSplitter.SplitThemeIntoPhrases(theme);
_themePhrasesToRepeat = themeSplitter.SplitThemeIntoPhrases(theme);

foreach (var themePhraseToRepeat in themePhrasesToRepeat.ToList())
foreach (var themePhraseToRepeat in _themePhrasesToRepeat.ToList())
{
ResetPhraseEndOrnamentation(themePhraseToRepeat.Phrase[^1], compositionConfiguration.DefaultNoteTimeSpan);
}
}

private bool AttemptToRepeatExistingThemePhrase(List<Measure> measures)
{
foreach (var themePhraseToRepeat in themePhrasesToRepeat.Where(themePhraseToRepeat => themePhraseToRepeat != themeCoolOffPhrase).OrderBy(static _ => ThreadLocalRandom.Next()))
foreach (var themePhraseToRepeat in _themePhrasesToRepeat.Where(themePhraseToRepeat => themePhraseToRepeat != _themeCoolOffPhrase).OrderBy(static _ => ThreadLocalRandom.Next()))
{
if (!TryRepeatPhrase(measures, themePhraseToRepeat))
{
continue;
}

themeCoolOffPhrase = themePhraseToRepeat;
_themeCoolOffPhrase = themePhraseToRepeat;

logger.LogInfoMessage("Repeated main theme phrase.");

Expand All @@ -70,24 +70,24 @@ private bool AttemptToRepeatExistingPhrase(List<Measure> measures)
{
var minPhraseRepetitionPoolSize = compositionConfiguration.PhrasingConfiguration.MinPhraseRepetitionPoolSize;

if (phrasesToRepeat.Count < minPhraseRepetitionPoolSize)
if (_phrasesToRepeat.Count < minPhraseRepetitionPoolSize)
{
return false;
}

foreach (var repeatedPhrase in phrasesToRepeat.OrderBy(static _ => ThreadLocalRandom.Next()).Where(repeatedPhrase => TryRepeatPhrase(measures, repeatedPhrase)))
foreach (var repeatedPhrase in _phrasesToRepeat.OrderBy(static _ => ThreadLocalRandom.Next()).Where(repeatedPhrase => TryRepeatPhrase(measures, repeatedPhrase)))
{
phrasesToRepeat.Remove(repeatedPhrase);
_phrasesToRepeat.Remove(repeatedPhrase);

if (coolOffPhrases.Count >= minPhraseRepetitionPoolSize && coolOffPhrases.TryDequeue(out var coolOffPhrase))
if (_coolOffPhrases.Count >= minPhraseRepetitionPoolSize && _coolOffPhrases.TryDequeue(out var coolOffPhrase))
{
phrasesToRepeat.Add(coolOffPhrase);
_phrasesToRepeat.Add(coolOffPhrase);
}

// If the phrase has not reached the maximum number of repetitions, add it to the cool off queue.
if (repeatedPhrase.RepetitionCount < compositionConfiguration.PhrasingConfiguration.MaxPhraseRepetitions)
{
coolOffPhrases.Enqueue(repeatedPhrase);
_coolOffPhrases.Enqueue(repeatedPhrase);
}

logger.LogInfoMessage("Repeated non-theme phrase.");
Expand Down Expand Up @@ -120,7 +120,7 @@ private void AttemptToCreateAndRepeatNewPhrase(List<Measure> measures)
RepetitionCount = 1
};

phrasesToRepeat.Add(repeatedPhrase);
_phrasesToRepeat.Add(repeatedPhrase);

ResetPhraseEndOrnamentation(measures[^1], compositionConfiguration.DefaultNoteTimeSpan);

Expand Down
4 changes: 2 additions & 2 deletions src/BaroquenMelody.Library/Phrasing/ThemeSplitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace BaroquenMelody.Library.Phrasing;
/// <inheritdoc cref="IThemeSplitter"/>
internal sealed class ThemeSplitter : IThemeSplitter
{
private static readonly List<(int PhraseLength, int MaxStartIndex)> _phraseSplits =
private static readonly List<(int PhraseLength, int MaxStartIndex)> PhraseSplits =
[
(2, 2),
(3, 1),
Expand All @@ -18,7 +18,7 @@ public List<RepeatedPhrase> SplitThemeIntoPhrases(BaroquenTheme theme)
.Select(static measure => new RepeatedPhrase { Phrase = [new Measure(measure)] })
.ToList();

foreach (var (phraseLength, maxStartIndex) in _phraseSplits)
foreach (var (phraseLength, maxStartIndex) in PhraseSplits)
{
if (theme.Recapitulation.Count < phraseLength)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void Add_WhenBelowCapacity_AddsItemToEnd()
2
};

list.Should().Equal([1, 2]);
list.Should().Equal(1, 2);
}

[Test]
Expand All @@ -48,7 +48,7 @@ public void Add_WhenAtCapacity_RemovesFirstItemAndAddsNewItemToEnd()
3
};

list.Should().Equal([2, 3]);
list.Should().Equal(2, 3);
}

[Test]
Expand All @@ -63,7 +63,7 @@ public void GetEnumerator_EnumeratesAllItems()

var items = list.ToList();

items.Should().Equal([1, 2, 3]);
items.Should().Equal(1, 2, 3);
}

[Test]
Expand Down Expand Up @@ -118,6 +118,6 @@ public void NonGenericGetEnumerator_EnumeratesAllItems()
items.Add(item);
}

items.Should().Equal([1, 2, 3]);
items.Should().Equal(1, 2, 3);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,29 +85,4 @@ public void WhenInvalidCompositionConfigurationIsPassedToDuetChordChoiceReposito
// assert
act.Should().Throw<ArgumentException>();
}

[Test]
public void GetChordChoiceId_ReturnsExpectedId()
{
// arrange
var compositionConfiguration = TestCompositionConfigurations.Get(2);

var duetChordChoiceRepository = new DuetChordChoiceRepository(
compositionConfiguration,
_mockNoteChoiceGenerator
);

// act
var id = duetChordChoiceRepository.GetChordChoiceId(
new ChordChoice(
[
new NoteChoice(Instrument.One, NoteMotion.Ascending, 2),
new NoteChoice(Instrument.Two, NoteMotion.Descending, 3)
]
)
);

// assert
id.Should().Be(5);
}
}
Loading

0 comments on commit ff6dd12

Please sign in to comment.