-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.cs
940 lines (821 loc) · 30.6 KB
/
MainForm.cs
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using NAudio.Midi;
using NAudio.Wave;
using Ephemera.NBagOfTricks;
using Ephemera.NBagOfTricks.Slog;
using Ephemera.NBagOfUis;
using Ephemera.MidiLib;
namespace Midifrier
{
public partial class MainForm : Form
{
#region Types
public enum ExplorerState { Stop, Play, Rewind, Complete }
#endregion
#region Fields
/// <summary>My logger.</summary>
readonly Logger _logger = LogManager.CreateLogger("MainForm");
/// <summary>Current file.</summary>
string _fn = "";
/// <summary>Current global user settings.</summary>
readonly UserSettings _settings;
/// <summary>Where to put things.</summary>
readonly string _outPath = "";
/// <summary>Midi output.</summary>
readonly IOutputDevice _outputDevice = new NullOutputDevice();
/// <summary>All the channels - key is user assigned name.</summary>
readonly Dictionary<string, Channel> _channels = new();
/// <summary>All the channel controls.</summary>
readonly List<ChannelControl> _channelControls = new();
/// <summary>The fast timer.</summary>
readonly MmTimerEx _mmTimer = new();
/// <summary>Midi events from the input file.</summary>
MidiDataFile _mdata = new();
#endregion
#region Lifecycle
/// <summary>
/// Constructor.
/// </summary>
public MainForm()
{
// Must do this first before initializing.
string appDir = MiscUtils.GetAppDataDir("Midifrier", "Ephemera");
_settings = (UserSettings)UserSettings.Load(appDir, typeof(UserSettings));
// Tell the libs about their settings.
MidiSettings.LibSettings = _settings.MidiSettings;
InitializeComponent();
// Init logging.
LogManager.MinLevelFile = _settings.FileLogLevel;
LogManager.MinLevelNotif = _settings.NotifLogLevel;
LogManager.LogMessage += LogManager_LogMessage;
LogManager.Run(Path.Join(appDir, "log.txt"), 100000);
// Init main form from settings
WindowState = FormWindowState.Normal;
StartPosition = FormStartPosition.Manual;
Location = new Point(_settings.FormGeometry.X, _settings.FormGeometry.Y);
Size = new Size(_settings.FormGeometry.Width, _settings.FormGeometry.Height);
KeyPreview = true; // for routing kbd strokes through OnKeyDown
SetText();
// The text output.
txtViewer.Font = Font;
txtViewer.WordWrap = true;
txtViewer.MatchText.Add("ERR", Color.LightPink);
txtViewer.MatchText.Add("WRN:", Color.Plum);
// Other UI configs.
toolStrip.Renderer = new Ephemera.NBagOfUis.CheckBoxRenderer() { SelectedColor = _settings.ControlColor };
btnAutoplay.Checked = _settings.Autoplay;
btnLoop.Checked = _settings.Loop;
sldVolume.DrawColor = _settings.ControlColor;
sldVolume.Value = _settings.Volume;
barBar.ProgressColor = _settings.ControlColor;
// FilTree settings.
ftree.RootDirs = _settings.RootDirs;
var s = MidiLibDefs.MIDI_FILE_TYPES + MidiLibDefs.STYLE_FILE_TYPES;
ftree.FilterExts = s.SplitByTokens("|;*");
ftree.IgnoreDirs = _settings.IgnoreDirs;
ftree.SplitterPosition = _settings.SplitterPosition;
ftree.SingleClickSelect = _settings.SingleClickSelect;
ftree.RecentFiles = _settings.RecentFiles;
ftree.InitTree();
sldBPM.Resolution = _settings.TempoResolution;
sldBPM.DrawColor = _settings.ControlColor;
sldBPM.Value = _settings.MidiSettings.DefaultTempo;
// Init channels and selectors.
cmbDrumChannel1.Items.Add("NA");
cmbDrumChannel2.Items.Add("NA");
for (int i = 1; i <= MidiDefs.NUM_CHANNELS; i++)
{
cmbDrumChannel1.Items.Add(i);
cmbDrumChannel2.Items.Add(i);
}
cmbDrumChannel1.SelectedIndex = MidiDefs.DEFAULT_DRUM_CHANNEL;
cmbDrumChannel2.SelectedIndex = 0;
// Hook up some simple handlers.
btnRewind.Click += (_, __) => UpdateState(ExplorerState.Rewind);
btnKillMidi.Click += (_, __) => _channels.Values.ForEach(ch => ch.Kill());
btnLogMidi.Click += (_, __) => _outputDevice.LogEnable = btnLogMidi.Checked;
sldBPM.ValueChanged += (_, __) => SetTimer();
btnAutoplay.Click += (_, __) => _settings.Autoplay = btnAutoplay.Checked;
btnLoop.Click += (_, __) => _settings.Loop = btnLoop.Checked;
btnPlay.Click += Play_Click;
MenuStrip.MenuActivate += (_, __) => UpdateUi();
// Set up output device.
foreach (var dev in _settings.MidiSettings.OutputDevices)
{
// Try midi.
_outputDevice = new MidiOutput(dev.DeviceName);
if (_outputDevice.Valid)
{
break;
}
}
// Run timer.
SetTimer();
}
/// <summary>
/// Form is legal now. Init things that want to log.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
{
//_logger.Info($"OK to log now!!");
if (!_outputDevice.Valid)
{
_logger.Error($"Invalid midi output device:{_outputDevice.DeviceName}");
}
// Initialize tree from user settings.
InitNavigator();
base.OnLoad(e);
}
/// <summary>
/// Clean up on shutdown. Dispose() will get the rest.
/// </summary>
protected override void OnFormClosing(FormClosingEventArgs e)
{
LogManager.Stop();
UpdateState(ExplorerState.Stop);
SaveSettings();
base.OnFormClosing(e);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
// Stop and destroy mmtimer.
Stop();
// Resources.
_mmTimer.Stop();
_mmTimer.Dispose();
_outputDevice.Dispose();
// Wait a bit in case there are some lingering events.
System.Threading.Thread.Sleep(100);
if (disposing)
{
components?.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region State management
/// <summary>
/// General state management.
/// </summary>
void UpdateState(ExplorerState state)
{
if (_outputDevice.Valid)
{
// Unhook.
btnPlay.CheckedChanged -= Play_Click;
switch (state)
{
case ExplorerState.Complete:
Rewind();
if (btnLoop.Checked)
{
btnPlay.Checked = true;
Play();
}
else
{
btnPlay.Checked = false;
Stop();
}
break;
case ExplorerState.Play:
btnPlay.Checked = true;
Play();
break;
case ExplorerState.Stop:
btnPlay.Checked = false;
Stop();
break;
case ExplorerState.Rewind:
Rewind();
break;
}
// Rehook.
btnPlay.CheckedChanged += Play_Click;
}
}
/// <summary>
/// Play button handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Play_Click(object? sender, EventArgs e)
{
UpdateState(btnPlay.Checked ? ExplorerState.Play : ExplorerState.Stop);
}
#endregion
#region File handling
/// <summary>
/// Common file opener.
/// </summary>
/// <param name="fn">The file to open.</param>
/// <returns>Status.</returns>
public bool OpenFile(string fn)
{
bool ok = true;
UpdateState(ExplorerState.Stop);
_logger.Info($"Opening file: {fn}");
try
{
if (!File.Exists(fn))
{
throw new InvalidOperationException($"Invalid file: {fn}");
}
var ext = Path.GetExtension(fn).ToLower();
if (!MidiLibDefs.MIDI_FILE_TYPES.Contains(ext) && !MidiLibDefs.STYLE_FILE_TYPES.Contains(ext))
{
throw new InvalidOperationException($"Invalid file type: {fn}");
}
using (new WaitCursor())
{
// Reset stuff.
cmbDrumChannel1.SelectedIndex = MidiDefs.DEFAULT_DRUM_CHANNEL;
cmbDrumChannel2.SelectedIndex = 0;
_mdata = new MidiDataFile();
// Process the file. Set the default tempo from preferences.
_mdata.Read(fn, _settings.MidiSettings.DefaultTempo, false);
// Init new stuff with contents of file/pattern.
lbPatterns.Items.Clear();
var pnames = _mdata.GetPatternNames();
if (pnames.Count > 0)
{
pnames.ForEach(pn => { lbPatterns.Items.Add(pn); });
}
else
{
throw new InvalidOperationException($"Invalid file: {fn}");
}
Rewind();
// Pick first.
lbPatterns.SelectedIndex = 0;
// Set up timer default.
sldBPM.Value = 100;
ExportMidiMenuItem.Enabled = _mdata.IsStyleFile;
// All good so far.
_fn = fn;
_settings.UpdateMru(fn);
if (_settings.Autoplay)
{
UpdateState(ExplorerState.Rewind);
UpdateState(ExplorerState.Play);
}
}
}
catch (Exception ex)
{
_logger.Error($"Couldn't open the file: {fn} because: {ex.Message}");
_fn = "";
ok = false;
}
SetText();
btnPlay.Enabled = ok;
return ok;
}
/// <summary>
/// Initialize tree from user settings.
/// </summary>
void InitNavigator()
{
try
{
ftree.InitTree();
}
catch (DirectoryNotFoundException)
{
_logger.Warn("No tree directories");
}
}
/// <summary>
/// Tree has selected a file to play.
/// </summary>
/// <param name="sender"></param>
/// <param name="fn"></param>
void Navigator_FileSelected(object? sender, string fn)
{
OpenFile(fn);
}
/// <summary>
/// Organize the file menu item drop down.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void File_DropDownOpening(object? sender, EventArgs e)
{
RecentMenuItem.DropDownItems.Clear();
_settings.RecentFiles.ForEach(f =>
{
ToolStripMenuItem menuItem = new(f, null, new EventHandler(Recent_Click));
RecentMenuItem.DropDownItems.Add(menuItem);
});
}
/// <summary>
/// The user has asked to open a recent file.
/// </summary>
void Recent_Click(object? sender, EventArgs e)
{
if (sender is not null)
{
string fn = sender.ToString()!;
OpenFile(fn);
}
}
/// <summary>
/// Allows the user to select an audio clip or midi from file system.
/// </summary>
void Open_Click(object? sender, EventArgs e)
{
var fileTypes = $"Midi Files|{MidiLibDefs.MIDI_FILE_TYPES}|Style Files|{MidiLibDefs.STYLE_FILE_TYPES}";
using OpenFileDialog openDlg = new()
{
Filter = fileTypes,
Title = "Select a file"
};
if (openDlg.ShowDialog() == DialogResult.OK && openDlg.FileName != _fn)
{
OpenFile(openDlg.FileName);
_fn = openDlg.FileName;
}
}
#endregion
#region Play functions
/// <summary>
///
/// </summary>
public void Play()
{
_mmTimer.Start();
}
/// <summary>
///
/// </summary>
public void Stop()
{
_mmTimer.Stop();
// Send midi stop all notes just in case.
_channels.Values.ForEach(ch => ch.Kill());
}
/// <summary>
///
/// </summary>
public void Rewind()
{
barBar.Current = new(0);
}
#endregion
#region User settings
/// <summary>
/// Collect and save user settings.
/// </summary>
void SaveSettings()
{
_settings.FormGeometry = new Rectangle(Location.X, Location.Y, Width, Height);
_settings.Volume = sldVolume.Value;
_settings.Autoplay = btnAutoplay.Checked;
_settings.Loop = btnLoop.Checked;
_settings.TempoResolution = (int)sldBPM.Resolution;
_settings.Volume = sldVolume.Value;
_settings.Save();
}
/// <summary>
/// Edit the common options in a property grid.
/// </summary>
void Settings_Click(object? sender, EventArgs e)
{
var changes = SettingsEditor.Edit(_settings, "User Settings", 500);
// Detect changes of interest.
bool navChange = false;
bool restart = false;
foreach (var (name, cat) in changes)
{
switch (name)
{
case "InputDevice":
case "OutputDevice":
case "ControlColor":
case "TempoResolution":
case "FileLogLevel":
case "NotifLogLevel":
restart = true;
break;
}
}
if (restart)
{
MessageBox.Show("Restart required for device changes to take effect");
}
if (navChange)
{
InitNavigator();
}
SaveSettings();
}
#endregion
#region Midi send
/// <summary>
/// Multimedia timer callback. Synchronously outputs the next midi events.
/// </summary>
void MmTimerCallback(double totalElapsed, double periodElapsed)
{
try
{
// Bump time. Check for end of play.
if (DoNextStep())
{
this.InvokeIfRequired(_ => { UpdateState(ExplorerState.Complete); });
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Synchronously outputs the next midi events. Does solo/mute.
/// This is running on the background thread.
/// </summary>
/// <returns>True if sequence completed.</returns>
public bool DoNextStep()
{
// Any soloes?
bool anySolo = _channels.AnySolo();
// Process each channel.
foreach (var ch in _channels.Values)
{
// Look for events to send. Any explicit solos?
if (ch.State == ChannelState.Solo || (!anySolo && ch.State == ChannelState.Normal))
{
// Process any sequence steps.
var playEvents = ch.GetEvents(barBar.Current.TotalSubs);
foreach (var mevt in playEvents)
{
switch (mevt)
{
case NoteOnEvent evt:
if (ch.IsDrums && evt.Velocity == 0)
{
// Skip drum noteoffs as windows GM doesn't like them.
}
else
{
// Adjust volume. Redirect drum channel to default.
NoteOnEvent ne = new(
evt.AbsoluteTime,
ch.IsDrums ? MidiDefs.DEFAULT_DRUM_CHANNEL : evt.Channel,
evt.NoteNumber,
Math.Min((int)(evt.Velocity * sldVolume.Value * ch.Volume), MidiDefs.MAX_MIDI),
evt.OffEvent is null ? 0 : evt.NoteLength); // Fix NAudio NoteLength bug.
ch.SendEvent(ne);
}
break;
case NoteEvent evt: // aka NoteOff
if (ch.IsDrums)
{
// Skip drum noteoffs as windows GM doesn't like them.
}
else
{
ch.SendEvent(evt);
}
break;
default:
// Everything else as is.
ch.SendEvent(mevt);
break;
}
}
}
}
// Bump time. Check for end of play.
bool done = barBar.IncrementCurrent(1);
return done;
}
#endregion
#region UI event handlers
/// <summary>
/// Do some global key handling. Space bar is used for stop/start playing.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Space:
// Toggle.
UpdateState(btnPlay.Checked ? ExplorerState.Stop : ExplorerState.Play);
e.Handled = true;
break;
}
base.OnKeyDown(e);
}
/// <summary>
/// The user clicked something in one of the player controls.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Control_ChannelChange(object? sender, ChannelChangeEventArgs e)
{
Channel channel = ((ChannelControl)sender!).BoundChannel;
if (e.StateChange)
{
switch (channel.State)
{
case ChannelState.Normal:
break;
case ChannelState.Solo:
// Mute any other non-solo channels.
_channels.Values.ForEach(ch =>
{
if (channel.ChannelNumber != ch.ChannelNumber && channel.State != ChannelState.Solo)
{
channel.Kill();
}
});
break;
case ChannelState.Mute:
channel.Kill();
break;
}
}
if (e.PatchChange && channel.Patch >= 0)
{
channel.SendPatch();
}
}
/// <summary>
/// All about me.
/// </summary>
void About_Click(object? sender, EventArgs e)
{
MiscUtils.ShowReadme("Midifrier");
}
/// <summary>
/// Set UI item enables according to system states.
/// </summary>
void UpdateUi()
{
btnRewind.Enabled = true;
btnPlay.Enabled = _mdata.GetPatternNames().Count > 0;
OpenMenuItem.Enabled = true;
AboutMenuItem.Enabled = true;
SettingsMenuItem.Enabled = true;
}
#endregion
#region Process patterns
/// <summary>
/// Load the requested pattern and create controls.
/// </summary>
/// <param name="pinfo"></param>
void LoadPattern(PatternInfo pinfo)
{
Stop();
// Clean out our current elements.
_channelControls.ForEach(c =>
{
Controls.Remove(c);
c.Dispose();
});
_channelControls.Clear();
_channels.Clear();
// Load the new one.
if (pinfo is null)
{
_logger.Error($"Invalid pattern!");
}
else
{
// Create the new controls.
int x = lblChLoc.Left;
int y = lblChLoc.Top;
lblChLoc.Hide();
// For scaling subdivs to internal.
MidiTimeConverter mt = new(_mdata.DeltaTicksPerQuarterNote, _settings.MidiSettings.DefaultTempo);
sldBPM.Value = pinfo.Tempo;
foreach (var (number, patch) in pinfo.GetChannels(true, true))
{
// Get events for the channel.
var chEvents = pinfo.GetFilteredEvents(new List<int>() { number });
// Is this channel pertinent?
if (chEvents.Any())
{
// Make new channel.
Channel channel = new()
{
ChannelName = $"chan{number}",
ChannelNumber = number,
Device = _outputDevice,
DeviceId = _outputDevice.DeviceName,
Volume = MidiLibDefs.VOLUME_DEFAULT,
State = ChannelState.Normal,
Patch = patch,
IsDrums = number == MidiDefs.DEFAULT_DRUM_CHANNEL,
Selected = false,
};
_channels.Add(channel.ChannelName, channel);
channel.SetEvents(chEvents);
// Make new control and bind to channel.
ChannelControl control = new()
{
Location = new(x, y),
BorderStyle = BorderStyle.FixedSingle,
BoundChannel = channel,
SelectedColor = _settings.ControlColor
};
control.ChannelChange += Control_ChannelChange;
Controls.Add(control);
_channelControls.Add(control);
// Good time to send initial patch.
channel.SendPatch();
// Adjust positioning.
y += control.Height + 5;
}
}
// Set timer.
sldBPM.Value = pinfo.Tempo;
}
// Update bar.
var tot = _channels.TotalSubs();
barBar.Start = new(0);
barBar.End = new(tot - 1);
barBar.Length = new(tot);
barBar.Current = new(0);
UpdateDrumChannels();
}
/// <summary>
/// Load pattern selection.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Patterns_SelectedIndexChanged(object? sender, EventArgs e)
{
var pinfo = _mdata.GetPattern(lbPatterns.SelectedItem.ToString()!);
LoadPattern(pinfo!);
Rewind();
if (_settings.Autoplay)
{
Play();
}
}
/// <summary>
/// Pattern selection.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void AllOrNone_Click(object? sender, EventArgs e)
{
bool check = sender == btnAllPatterns;
for (int i = 0; i < lbPatterns.Items.Count; i++)
{
lbPatterns.SetItemChecked(i, check);
}
}
#endregion
#region Drum channel
/// <summary>
/// User changed the drum channel.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DrumChannel_SelectedIndexChanged(object? sender, EventArgs e)
{
UpdateDrumChannels();
}
/// <summary>
/// Update all channels based on current UI.
/// </summary>
void UpdateDrumChannels()
{
_channelControls.ForEach(ctl => ctl.IsDrums =
(ctl.ChannelNumber == cmbDrumChannel1.SelectedIndex) ||
(ctl.ChannelNumber == cmbDrumChannel2.SelectedIndex));
}
#endregion
#region Export
/// <summary>
/// Export current file to human readable or midi.
/// </summary>
void Export_Click(object? sender, EventArgs e)
{
var stext = ((ToolStripMenuItem)sender!).Text;
try
{
// Get selected patterns.
List<string> patternNames = new();
if (lbPatterns.Items.Count == 1)
{
patternNames.Add(lbPatterns.Items[0].ToString()!);
}
else if (lbPatterns.CheckedItems.Count > 0)
{
foreach (var p in lbPatterns.CheckedItems)
{
patternNames.Add(p.ToString()!);
}
}
else
{
_logger.Warn("Please select at least one pattern");
return;
}
List<PatternInfo> patterns = new();
patternNames.ForEach(p => patterns.Add(_mdata.GetPattern(p)!));
// Get selected channels.
List<Channel> channels = new();
_channelControls.Where(cc => cc.Selected).ForEach(cc => channels.Add(cc.BoundChannel));
if (!channels.Any()) // grab them all.
{
_channelControls.ForEach(cc => channels.Add(cc.BoundChannel));
}
switch (stext.ToLower())
{
case "export csv":
{
var newfn = MiscUtils.MakeExportFileName(_outPath, _mdata.FileName, "export", "csv");
MidiExport.ExportCsv(newfn, patterns, channels, _mdata.GetGlobal());
_logger.Info($"Exported to {newfn}");
}
break;
case "export midi":
foreach (var pattern in patterns)
{
var newfn = MiscUtils.MakeExportFileName(_outPath, _mdata.FileName, pattern.PatternName, "mid");
MidiExport.ExportMidi(newfn, pattern, channels, _mdata.GetGlobal());
_logger.Info($"Export midi to {newfn}");
}
break;
default:
_logger.Error($"Ooops: {stext}");
break;
}
}
catch (Exception ex)
{
_logger.Error($"{ex.Message}");
}
}
#endregion
#region Misc functions
/// <summary>
/// Show log events.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void LogManager_LogMessage(object? sender, LogMessageEventArgs e)
{
// Usually come from a different thread.
if (IsHandleCreated)
{
this.InvokeIfRequired(_ => { txtViewer.AppendLine($"{e.Message}"); });
}
}
/// <summary>
/// Convert tempo to period and set mm timer accordingly.
/// </summary>
void SetTimer()
{
MidiTimeConverter mt = new(_mdata.DeltaTicksPerQuarterNote, sldBPM.Value);
double period = mt.RoundedInternalPeriod();
_mmTimer.SetTimer((int)Math.Round(period), MmTimerCallback);
}
/// <summary>
/// Utility for header.
/// </summary>
void SetText()
{
var s = _fn == "" ? "No file loaded" : _fn;
Text = $"Midifrier {MiscUtils.GetVersionString()} - {s}";
}
/// <summary>
/// Debug stuff.
/// </summary>
void DumpDevices()
{
for (int id = -1; id < WaveOut.DeviceCount; id++)
{
var cap = WaveOut.GetCapabilities(id);
_logger.Info($"WaveOut {id} {cap.ProductName}");
}
for (int id = -1; id < WaveIn.DeviceCount; id++)
{
var cap = WaveIn.GetCapabilities(id);
_logger.Info($"WaveIn {id} {cap.ProductName}");
}
}
#endregion
}
}