-
Notifications
You must be signed in to change notification settings - Fork 4
/
Echoes.cs
4232 lines (3935 loc) · 164 KB
/
Echoes.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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using SuperM3U;
using Un4seen.Bass;
using Un4seen.Bass.Misc;
using Un4seen.Bass.AddOn.Midi;
using Un4seen.Bass.AddOn.Flac;
using Un4seen.Bass.AddOn.Wma;
using Un4seen.Bass.AddOn.Mix;
namespace Echoes
{
/* add more formats,
* make background worker not overflow,
* add customizable columns,
* make options window,
* allow tag edit while playing,
* loopTrack on mods not working
* stereo/mono thing not working, probably gotta use mixer
* playlist doesnt renumber correctly after adding
* tags wont load if nowplaying is the song (re-entering playlist)
* make ui get smaller/lightweight
* add choice to insta-save playlist after deletion/insertion or need to click save*/
/*options:
* add new track to top/bottom,
* hardware mixing,
* different hotkeys with different params
* load next playlist after this one finishes*/
// Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
// Compute the addition of each combination of the keys you want to be pressed
// ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
#region Enums
public enum Hotkey
{
ADVANCEPLAYER, PREVIOUSPLAYER, PLAYPAUSE, VOLUMEUP, VOLUMEDOWN, TRANSPOSEUP, TRANSPOSEDOWN, DELETE, GLOBAL_VOLUMEUP, GLOBAL_VOLUMEDOWN, NEXTLIST, PREVLIST, SHUFFLE, REWIND, SKIPFORWARD, SKIPBACKWARD
}
public enum ItemType
{
Playlist, Track
}
public enum Modifier
{
NONE, CTRL, ALT, SHIFT
}
#endregion
public partial class Echoes : Form
{
/*#region DLL libraries used to manage hotkeys
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion*/
//public int[] modValues = { 0, 1, 2, 4, 8 };
#region Settings values
/*To add a new setting value:
* 1. define here;
* 2. define a default in Program class;
* 3. set it to default in SetDefaults() and equivalent;
* 4. load it in LoadXmlConfig();
* 5. save it in SaveXmlConfig();
* 6. add a control of it to Options form;
*/
Settings settings;
//colors
public Color backgroundColor;
public Color controlBackColor;
public Color controlForeColor;
public Color highlightBackColor;
public Color highlightForeColor;
public Color seekBarBackColor;
public Color seekBarForeColor;
public Color volBarBackColor;
public Color volBarForeColor;
public Color trackTitleColor;
public Color trackArtistColor;
public Color trackAlbumColor;
public Color spectrumColor;
//general settings
public Font font1;
public Font font2;
public int fontSizePercentage = 100;
public int visualisationStyle;
public int visualfps;
public int repeat;
public int converterSelectedBitrateIndex;
public float volume;
public float hotkeyVolumeIncrement;
public float hotkeyTransposeIncrement;
public bool saveTranspose;
public bool autoShuffle;
public bool autoAdvance;
public bool reshuffleAfterListLoop;
public bool trackChangePopup;
public bool showWaveform;
public bool normalize;
public bool suppressHotkeys;
public List<ColumnInfo> currentColumnInfo;
public string midiSfLocation;
//hotkey settings
public bool hotkeysAllowed;
public List<HotkeyData> hotkeys;
#endregion
#region Vars
public string playlistDbLocation = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "known_playlists.dat");
public string tagsCacheLocation = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "track_cache.xml");
public string configXmlFileLocation = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "config.xml");
public string lameExeLocation = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "lame.exe");
public string lameExeDownloadSite = "http://www.rarewares.org/mp3-lame-bundle.php";
public XmlCacher xmlCacher;
public int stream;
public int mixer;
public bool confirmSaveFlag = false;
public bool streamLoaded = false;
bool reinitTagLoader = false;
public SYNCPROC endSync, stallSync;
public BASS_MIDI_FONT[] midiFonts;
public Visuals vs = new Un4seen.Bass.Misc.Visuals();
int[] _fxEQ = { 0, 0, 0 };
bool playlistChanged = false;
public bool eqEnabled = false;
int peak = 0;
public float normGain = 0;
public float[] eqGains = { 8f, -8f, 14f };
bool normalizerRestart = false;
public DSP_Gain DSPGain;
Track toNormalize;
System.Timers.Timer normalizeSmoother;
bool normalizeSmoothingStop = false;
float normalizeSmoothingTickSize;
public Track nowPlaying = null;
private Track trackToLoad;
Track trackToReload;
public List<Track> playlist = new List<Track>();
public List<string> supportedModuleTypes = new List<string>() { ".mo3", ".it", ".xm", ".s3m", ".mtm", ".mod", ".umx" };
public List<string> supportedAudioTypes = new List<string>() { ".mp3", ".mp2", ".mp1", ".wav", ".ogg", ".wma", ".m4a", ".flac" };
public List<string> supportedWaveformTypes = new List<String>() { ".mp3", ".mp2", ".mp1", ".wav" };
public List<string> supportedMidiTypes = new List<string>() { ".midi", ".mid" };
Converter theConverter;
TagEditor te;
DupeFinder df;
Statistics stats;
Options opts;
Equalizer eqWindow;
FloatingOSDWindow popupWindow = new FloatingOSDWindow();
KeyboardHook kh;
DataGridViewRow highlightedRow;
DataGridViewColumn highlightedColumn;
Stopwatch timeListenedTracker = new Stopwatch();
public WaveForm wf;
public Bitmap waveformImage;
ItemType displayedItems;
List<string> knownPlaylists = new List<string>();
List<string> playlistNames = new List<string>();
List<int> savedSelectionForSort;
string currentPlaylist = null;
string gridSearchWord = "";
bool draggingSeek = false;
bool draggingVolume = false;
bool wasPlaying = false;
bool advanceFlag = false;
bool gridSearchFirstStroke = true;
bool sortingAllowed = true;
bool showingPlayIcon = true;
bool reloadTagsFlag = false;
public IntPtr theHandle;
int gridSearchTimerRemaining = 0;
int gridSearchReset = 30;
public int waveformCompleted = 0;
public short[] waveform;
private AutoResetEvent ResetEvent = new AutoResetEvent(false);
public DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle();
public DataGridViewCellStyle alternatingCellStyle = new DataGridViewCellStyle();
public DataGridViewCellStyle highlightedCellStyle = new DataGridViewCellStyle();
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
readonly string[] COLUMN_PROPERTIES = { "num", "title", "artist", "length", "album", "listened", "filename", "year", "genre", "comment", "bitrate", "trackNumber", "lastOpened", "size", "format", "trueBitrate", "timesListened" };
readonly string[] COLUMN_HEADERS = { "#", "Title", "Artist", "Length", "Album", "Listened", "File", "Year", "Genre", "Comment", "Bitrate", "Track #", "Last opened", "Size", "Format", "True Bitrate", "Times listened" };
readonly string[] COLUMN_HEADERS_ALLOWED_CUSTOM = { "Title", "Artist", "Length", "Album", "Year", "Genre", "Comment", "Bitrate", "Format" };
#endregion
public Echoes()
{
vs.MaxFrequencySpectrum = Utils.FFTFrequency2Index(19200, 2047, 44100);
xmlCacher = new XmlCacher(tagsCacheLocation);
/*List<Track> trx = xmlCacher.GetAllTracks();
xmlCacher.AddOrUpdate(trx);*/
InitializeComponent();
kh = new KeyboardHook();
kh.Install();
kh.KeyDown += kh_KeyDown;
new ToolTip().SetToolTip(openBtn, "Open file");
new ToolTip().SetToolTip(exportBtn, "Export playlist");
new ToolTip().SetToolTip(optionsBtn, "Options");
new ToolTip().SetToolTip(repeatBtn, "Loop (none/list/track)");
new ToolTip().SetToolTip(shuffleBtn, "Shuffle");
theHandle = Handle;
supportedAudioTypes.AddRange(supportedModuleTypes);
supportedAudioTypes.AddRange(supportedMidiTypes);
DoubleBuffered = true;
seekBar.Minimum = 0;
seekBar.Maximum = 400;
trackGrid.AutoGenerateColumns = false;
trackGrid.ScrollBars = ScrollBars.Both;
trackGrid.Font = font1;
trackGrid.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
trackGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
trackGrid.RowTemplate.Height = 18;
trackGrid.DoubleBuffered(true);
Form1_Resize(null, null);
LoadXmlConfig();
if (visualfps < 1) visualfps = 1;
progressRefreshTimer.Interval = 1000 / visualfps;
progressRefreshTimer.Start();
RepositionControls();
SetColors();
LoadPlaylistDb();
StartupLoadProcedure();
}
void AddHeaderContextMenu()
{
ContextMenuStrip headerContextMenu = new ContextMenuStrip();
for (int i = 0; i < COLUMN_HEADERS.Length; i++)
{
ToolStripMenuItem mi = new ToolStripMenuItem(COLUMN_HEADERS[i]);
if (currentColumnInfo.Where(x => x.id == i).Count() > 0) mi.Checked = true;
mi.Name = i + "";
mi.Click += (theSender, eventArgs) =>
{
if (mi.Checked)
{
currentColumnInfo.Remove(currentColumnInfo.First(x => x.id == Int32.Parse(mi.Name)));
}
else
{
currentColumnInfo.Add(new ColumnInfo(Int32.Parse(mi.Name), 100));
}
RefreshPlaylistGrid();
mi.Checked = !mi.Checked;
};
headerContextMenu.Items.Add(mi);
}
ToolStripMenuItem mit = new ToolStripMenuItem("<Restore default>");
mit.Click += (theSender, eventArgs) =>
{
currentColumnInfo = Program.defaultColumnInfo;
RefreshPlaylistGrid();
};
headerContextMenu.Items.Add(mit);
foreach (DataGridViewColumn clmn in trackGrid.Columns)
{
clmn.HeaderCell.ContextMenuStrip = headerContextMenu;
}
}
public void RemoveEQ()
{
foreach (int i in _fxEQ)
{
Bass.BASS_ChannelRemoveFX(stream, i);
}
}
public void DefineEQ()
{
if (!eqEnabled) return;
BASS_DX8_PARAMEQ eq = new BASS_DX8_PARAMEQ();
_fxEQ[0] = Bass.BASS_ChannelSetFX(stream, BASSFXType.BASS_FX_DX8_PARAMEQ, 0);
_fxEQ[1] = Bass.BASS_ChannelSetFX(stream, BASSFXType.BASS_FX_DX8_PARAMEQ, 0);
_fxEQ[2] = Bass.BASS_ChannelSetFX(stream, BASSFXType.BASS_FX_DX8_PARAMEQ, 0);
eq.fBandwidth = 18f;
eq.fCenter = 100f;
eq.fGain = 0f;
Bass.BASS_FXSetParameters(_fxEQ[0], eq);
eq.fCenter = 1000f;
Bass.BASS_FXSetParameters(_fxEQ[1], eq);
eq.fCenter = 8000f;
Bass.BASS_FXSetParameters(_fxEQ[2], eq);
}
public void ApplyEQ()
{
if (!eqEnabled) return;
for (int i = 0; i < eqGains.Length; i++)
{
UpdateEQ(i, eqGains[i]);
}
}
void UpdateEQ(int band, float gain)
{
BASS_DX8_PARAMEQ eq = new BASS_DX8_PARAMEQ();
if (Bass.BASS_FXGetParameters(_fxEQ[band], eq))
{
eq.fGain = gain;
Bass.BASS_FXSetParameters(_fxEQ[band], eq);
}
}
void kh_KeyDown(KeyEventArgs e)
{
//System.Media.SystemSounds.Beep.Play();
//if (e == null) return;
foreach (HotkeyData hk in hotkeys)
{
if (hk.key == e.KeyCode && hk.ctrl == e.Control && hk.alt == e.Alt && hk.shift == e.Shift)
{
DoHotkeyEvent(hk.hotkey);
}
}
}
void PointToMissingFile(Track t)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Audio files|";
foreach (string s in supportedAudioTypes)
{
dlg.Filter += "*" + s + ";";
}
if (dlg.ShowDialog(this) == DialogResult.OK)
{
if (supportedAudioTypes.Contains(Path.GetExtension(dlg.FileName).ToLower()))
{
xmlCacher.ChangeFilename(t.filename, dlg.FileName);
t.filename = dlg.FileName;
t.GetTags();
if (MessageBox.Show("Do you want to look for other missing files in this directory?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
FindMissingFilesIn(Path.GetDirectoryName(dlg.FileName), false);
}
}
else
{
MessageBox.Show("File type not supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
void FindMissingFilesIn(string path, bool inclSubdirs)
{
List<Track> missingTracks = playlist.Where(x => !File.Exists(x.filename)).ToList();
SearchOption opt;
if (inclSubdirs) opt = SearchOption.AllDirectories;
else opt = SearchOption.TopDirectoryOnly;
var files = Directory.EnumerateFiles(path, "*", opt);
int foundFiles = 0;
foreach (Track t in missingTracks)
{
string match = files.FirstOrDefault(x => Path.GetFileName(x) == Path.GetFileName(t.filename));
if (match != null)
{
xmlCacher.ChangeFilename(t.filename, match);
t.filename = match;
t.GetTags();
foundFiles++;
}
}
MessageBox.Show(foundFiles + "/" + missingTracks.Count + " missing tracks found." + Environment.NewLine + "Save the playlist.");
}
public void SetDefaultColors()
{
backgroundColor = Program.backgroundColorDefault.Copy();
controlBackColor = Program.controlBackColorDefault.Copy();
controlForeColor = Program.controlForeColorDefault.Copy();
highlightBackColor = Program.highlightBackColorDefault.Copy();
highlightForeColor = Program.highlightForeColorDefault.Copy();
seekBarBackColor = Program.seekBarBackColorDefault.Copy();
seekBarForeColor = Program.seekBarForeColorDefault.Copy();
volBarBackColor = Program.volBarBackColorDefault.Copy();
volBarForeColor = Program.volBarForeColorDefault.Copy();
trackTitleColor = Program.trackTitleColorDefault.Copy();
trackArtistColor = Program.trackArtistColorDefault.Copy();
trackAlbumColor = Program.trackAlbumColorDefault.Copy();
spectrumColor = Program.spectrumColorDefault.Copy();
Refresh();
}
public void SetDefaultGeneral()
{
font1 = Program.font1Default.Copy();
font2 = Program.font2Default.Copy();
fontSizePercentage = 100;
SetFonts();
hotkeyVolumeIncrement = Program.hotkeyVolumeIncrementDefault;
hotkeyTransposeIncrement = Program.hotkeyTransposeIncrementDefault;
SetVolume(Program.volumeDefault);
autoAdvance = Program.autoAdvanceDefault;
autoShuffle = Program.autoShuffleDefault;
trackChangePopup = Program.trackChangePopupDefault;
currentColumnInfo = Program.defaultColumnInfo.Copy();
saveTranspose = Program.saveTransposeDefault;
repeat = Program.repeatDefault;
normalize = Program.normalizeDefault;
visualisationStyle = Program.visualisationStyleDefault;
visualfps = Program.visualfpsDefault;
midiSfLocation = Program.midiSfLocationDefault;
reshuffleAfterListLoop = Program.reshuffleAfterListLoopDefault;
}
public void SetDefaults()
{
//colors
SetDefaultColors();
//general
SetDefaultGeneral();
//hotkey settings
hotkeysAllowed = Program.hotkeysAllowedDefault;
suppressHotkeys = Program.suppressHotkeysDefault;
hotkeys = Program.defaultHotkeys.Copy();
SetHotkeySuppression();
}
void DoHotkeyEvent(Hotkey k)
{
if (k == Hotkey.ADVANCEPLAYER) AdvancePlayer();
else if (k == Hotkey.PREVIOUSPLAYER) PlayerPrevious();
else if (k == Hotkey.PLAYPAUSE)
{
if (IsPlaying())
{
PausePlayer();
}
else
{
Play();
}
}
else if (k == Hotkey.VOLUMEUP) SetVolume(volume + hotkeyVolumeIncrement);
else if (k == Hotkey.VOLUMEDOWN) SetVolume(volume - hotkeyVolumeIncrement);
else if (k == Hotkey.TRANSPOSEUP)
{
if (transposeChangerNum.Value <= 11)
{
transposeChangerNum.Value += (decimal)hotkeyTransposeIncrement;
}
}
else if (k == Hotkey.TRANSPOSEDOWN)
{
if (transposeChangerNum.Value >= -11)
{
transposeChangerNum.Value -= (decimal)hotkeyTransposeIncrement;
}
}
else if (k == Hotkey.DELETE)
{
if (nowPlaying != null)
{
int currRow = FindTrackRow(nowPlaying).Index;
if (trackGrid.Rows[currRow] == null) return;
DeleteTrack(new List<int> { nowPlaying.num });
if (trackGrid.Rows.Count - 1 >= currRow)
{
Track t = (Track)trackGrid.Rows[currRow].DataBoundItem;
LoadAudio(t);
}
}
}
else if (k == Hotkey.GLOBAL_VOLUMEUP) AdjustGlobalVolume(0.01f);
else if (k == Hotkey.GLOBAL_VOLUMEDOWN) AdjustGlobalVolume(-0.01f);
else if (k == Hotkey.NEXTLIST && !tagsLoaderWorker.IsBusy)
{
if (playlistSelectorCombo.SelectedIndex < playlistSelectorCombo.Items.Count - 1)
{
playlistSelectorCombo.SelectedIndex++;
}
else
{
playlistSelectorCombo.SelectedIndex = 0;
}
comboBox1_SelectionChangeCommitted(null, null);
if (displayedItems != ItemType.Playlist) PlayFirst();
}
else if (k == Hotkey.PREVLIST && !tagsLoaderWorker.IsBusy)
{
if (playlistSelectorCombo.SelectedIndex > 0)
{
playlistSelectorCombo.SelectedIndex--;
}
else
{
playlistSelectorCombo.SelectedIndex = playlistSelectorCombo.Items.Count - 1;
}
comboBox1_SelectionChangeCommitted(null, null);
if (displayedItems != ItemType.Playlist) PlayFirst();
}
else if (k == Hotkey.SHUFFLE) Shuffle();
else if (k == Hotkey.REWIND) SetPosition(0);
else if (k == Hotkey.SKIPFORWARD) SkipSeconds(5);
else if (k == Hotkey.SKIPBACKWARD) SkipSeconds(-5);
}
void RepositionControls()
{
trackText.Location = new Point(trackText.Location.X, playBtn.Location.Y + playBtn.Height + 5);
seekBar.Location = new Point(seekBar.Location.X, trackText.Location.Y + trackText.Height + 5);
searchBox.Location = new Point(searchBox.Location.X, seekBar.Location.Y + seekBar.Height + 5);
playlistInfoTxt.Location = new Point(searchBox.Location.X + searchBox.Width + 20, seekBar.Location.Y + seekBar.Height + 5);
playlistInfoTxt.Width = playlistSelectorCombo.Location.X - 10 - playlistInfoTxt.Location.X;
playlistInfoTxt.Height = playlistSelectorCombo.Height;
playlistSelectorCombo.Location = new Point(playlistSelectorCombo.Location.X, seekBar.Location.Y + seekBar.Height + 5);
volumeBar.Location = new Point(volumeBar.Location.X, seekBar.Location.Y + seekBar.Height + 5);
volumeBar.Height = playlistSelectorCombo.Height;
trackGrid.Location = new Point(trackGrid.Location.X, searchBox.Location.Y + searchBox.Height + 5);
//Form1_Resize(null, null);
//Refresh();
}
public void SkipSeconds(double sekonds)
{
bool negative = false;
if (sekonds < 0)
{
negative = true;
sekonds = -sekonds;
}
if (!streamLoaded) return;
long secsInBytes = Bass.BASS_ChannelSeconds2Bytes(stream, sekonds);
if (negative) secsInBytes = -secsInBytes;
if (GetPosition() + secsInBytes > GetLength())
{
SetPosition(GetLength());
}
else if (GetPosition() + secsInBytes < 0)
{
SetPosition(0);
}
else
{
SetPosition(GetPosition() + secsInBytes);
}
}
public void SetFonts()
{
trackText.Font = new Font(font1.FontFamily, 12 * (float)fontSizePercentage / 100, font1.Style);
searchBox.Font = new Font(font1.FontFamily, 8.25f * (float)fontSizePercentage / 100, font1.Style);
playlistInfoTxt.Font = new Font(font1.FontFamily, 8.25f * (float)fontSizePercentage / 100, font1.Style);
playlistSelectorCombo.Font = new Font(font1.FontFamily, 8.25f * (float)fontSizePercentage / 100, font1.Style);
//trackGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
trackGrid.Font = new Font(font1.FontFamily, 8.25f * (float)fontSizePercentage / 100, font1.Style);
trackGrid.RowTemplate.Height = (int)(trackGrid.Font.Height * 1.5);
foreach (DataGridViewRow rw in trackGrid.Rows)
{
rw.Height = trackGrid.RowTemplate.Height;
}
trackGrid.Invalidate();
//trackGrid.RowTemplate.Height = (int)(trackGrid.Font.Height*1.5f);
//trackGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
/*foreach (Control ctrl in this.Controls)
{
if (!(ctrl is Button) && !(ctrl is NumericUpDown) && ctrl.Name != "transposeTxt")
{
ctrl.Font = new Font(mainFont.FontFamily, ctrl.Font.Size*(float)fontSizePercentage/100, mainFont.Style);
}
}*/
RepositionControls();
DisplayTrackInfo(nowPlaying);
this.Refresh();
}
public void SetColors()
{
this.BackColor = backgroundColor;
foreach (Control ctrl in this.Controls)
{
if (ctrl is Label || ctrl is PictureBox || ctrl is TextBox && ctrl.Name != "searchBox")
{
ctrl.BackColor = backgroundColor;
}
else
{
ctrl.BackColor = controlBackColor;
}
if (ctrl is ModifiedControls.ModifiedComboBox)
{
((ModifiedControls.ModifiedComboBox)ctrl).HighlightColor = seekBarForeColor;
}
ctrl.ForeColor = controlForeColor;
ctrl.Refresh();
}
//dgv
defaultCellStyle.BackColor = controlBackColor;
defaultCellStyle.ForeColor = controlForeColor;
defaultCellStyle.SelectionBackColor = controlForeColor;
defaultCellStyle.SelectionForeColor = controlBackColor;
alternatingCellStyle.BackColor = controlBackColor.Darken();
alternatingCellStyle.ForeColor = controlForeColor.Darken();
alternatingCellStyle.SelectionBackColor = controlForeColor.Darken();
alternatingCellStyle.SelectionForeColor = controlBackColor.Darken();
highlightedCellStyle.ForeColor = highlightForeColor;
highlightedCellStyle.BackColor = highlightBackColor;
highlightedCellStyle.SelectionBackColor = controlForeColor.Darken().Darken();
highlightedCellStyle.SelectionForeColor = highlightForeColor;
trackGrid.ColumnHeadersDefaultCellStyle.BackColor = controlBackColor.Lighten();
trackGrid.ColumnHeadersDefaultCellStyle.ForeColor = controlForeColor;
trackGrid.BackgroundColor = controlBackColor;
trackGrid.DefaultCellStyle = defaultCellStyle;
trackGrid.AlternatingRowsDefaultCellStyle = alternatingCellStyle;
trackGrid.Refresh();
}
void WaveFormCallback(int framesDone, int framesTotal, TimeSpan elapsedTime, bool finished)
{
if (finished && wf.FileName == nowPlaying.filename)
{
Invoke((MethodInvoker)delegate
{
wf.SyncPlayback(stream);
if (showWaveform)
{
waveformImage = wf.CreateBitmap(Screen.FromControl(this).WorkingArea.Width * 2, this.seekBar.Height, -1, -1, true);
waveformImage = waveformImage.SetOpacity(0.5d);
}
if (normalize) Normalize();
volumeBar.Refresh();
});
// if your playback stream uses a different resolution than the WF
// use this to sync them
}
else
{
if (showWaveform)
{
Invoke((MethodInvoker)delegate
{
waveformImage = wf.CreateBitmap(Screen.FromControl(this).WorkingArea.Width * 2, this.seekBar.Height, -1, -1, true);
waveformImage = waveformImage.SetOpacity(0.5d);
});
}
}
}
public void CreateWaveform()
{
if (wf != null && wf.IsRenderingInProgress) wf.RenderStop();
waveformImage = null;
if (nowPlaying == null) { return; }
wf = new Un4seen.Bass.Misc.WaveForm();
wf.FileName = nowPlaying.filename;
wf.CallbackFrequency = 1000;
var handler = new WAVEFORMPROC(WaveFormCallback);
wf.NotifyHandler = handler;
wf.ColorBackground = Color.Transparent;
wf.DrawWaveForm = WaveForm.WAVEFORMDRAWTYPE.Mono;
wf.ColorLeft = wf.ColorLeft2 = wf.ColorLeftEnvelope = Color.Black;
// it is important to use the same resolution flags as for the playing stream
// e.g. if an already playing stream is 32-bit float, so this should also be
// or use 'SyncPlayback' as shown below
int strm;
if (!LoadStream(wf.FileName, out strm, BASSFlag.BASS_MUSIC_STOPBACK | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MUSIC_DECODE)) return;
wf.RenderStart(strm, true);
volumeBar.Refresh();
}
public bool IsPlaying()
{
return Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING;
}
/*protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312) {
Hotkey k=(Hotkey)m.WParam.ToInt32();
DoHotkeyEvent(k);
}
base.WndProc(ref m);
}*/
int PitchFreq(int cents, int freq)
{
return (int)(Math.Pow(2, (double)cents / 1200d) * freq);
}
public void SetFrequency()
{
if (streamLoaded) Bass.BASS_ChannelSetAttribute(stream, BASSAttribute.BASS_ATTRIB_FREQ, (float)(PitchFreq((int)(transposeChangerNum.Value * 100), Bass.BASS_ChannelGetInfo(stream).freq)));
seekBar.Refresh();
}
public void SetChannels(bool stereo)
{
if (!streamLoaded) return;
if (stereo) Bass.BASS_ChannelFlags(stream, BASSFlag.BASS_DEFAULT, BASSFlag.BASS_SAMPLE_MONO);
else Bass.BASS_ChannelFlags(stream, BASSFlag.BASS_SAMPLE_MONO, BASSFlag.BASS_SAMPLE_MONO);
}
public void UpdateCache(List<Track> trs)
{
xmlCacher.AddOrUpdate(trs);
}
public void UpdateCache()
{
UpdateCache(playlist);
}
void SetListenedTime(Track track, int time)
{
track.listened = time;
xmlCacher.AddOrUpdate(new List<Track> { track });
}
void LoadFiles(List<string> files)
{
//tag loader stuff
if (tagsLoaderWorker.IsBusy)
{
tagsLoaderWorker.CancelAsync();
LoadFiles(files);
return;
}
//
var loadingPlaylist = new List<Track>();
string lastList = null;
foreach (string file in files)
{
if (supportedAudioTypes.Contains(Path.GetExtension(file).ToLower()))
{
loadingPlaylist.Add(new Track(file, Path.GetFileName(file)));
}
else if (Path.GetExtension(file).ToLower() == ".m3u")
{
AddKnownPlaylist(file);
lastList = file;
}
}
if (loadingPlaylist.Count == 0)
{
//there were no valid track files, load m3u if any
if (lastList != null) ImportM3u(lastList);
return;
}
//there were track files
if (displayedItems != ItemType.Track)
{
//in playlist list mode, create new playlist
LoadCustomPlaylist(loadingPlaylist);
displayedItems = ItemType.Track;
tagsLoaderWorker.RunWorkerAsync();
}
else
{
//in a created playlist, add tracks to it
loadingPlaylist.Reverse();
bool addDupes = false;
bool askToAddDupes = true;
foreach (Track t in loadingPlaylist)
{
if (!addDupes && playlist.Where(x => x.filename == t.filename).Count() > 0)
{
if (askToAddDupes)
{
addDupes = MessageBox.Show("There are duplicates. Add them?", "Dupes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes;
askToAddDupes = false;
if (addDupes)
{
playlist.Insert(0, t);
}
}
}
else playlist.Insert(0, t);
}
FixPlaylistNumbers(playlist);
RefreshPlaylistGrid();
if (tagsLoaderWorker.IsBusy)
{
reinitTagLoader = true;
tagsLoaderWorker.CancelAsync();
}
else
{
tagsLoaderWorker.RunWorkerAsync();
}
playlistChanged = true;
}
RefreshTotalTimeLabel();
}
bool AskToQuitWorker()
{
if (!tagsLoaderWorker.IsBusy) return true;
if (MessageBox.Show("Tag loading in progress. Any loaded tags will not be saved if you quit. Do you wish to quit?", "Loading", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
{
return false;
}
return true;
}
void AskToSavePlaylistChanges()
{
if (!playlistChanged || displayedItems != ItemType.Track) return;
if (MessageBox.Show("Playlist has unsaved changes. Save now?", "Playlist", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
SavePlaylist();
}
}
void StartupLoadProcedure()
{
string lastList = null;
playlist = new List<Track>();
foreach (string file in Program.filesToOpen)
{
if (supportedAudioTypes.Contains(Path.GetExtension(file).ToLower()))
{
playlist.Add(new Track(file, Path.GetFileName(file)));
}
else if (Path.GetExtension(file).ToLower() == ".m3u")
{
AddKnownPlaylist(file);
lastList = file;
}
}
PopulatePlaylistList();
if (playlist.Count > 0)
{
LoadCustomPlaylist(playlist);
displayedItems = ItemType.Track;
tagsLoaderWorker.RunWorkerAsync();
Play();
}
else if (lastList != null) ImportM3u(lastList);
else DisplayPlaylistsInGrid();
}
public void OpenFile(Track t)
{
if (Path.GetExtension(t.filename).ToLower() == ".m3u")
{
ImportM3u(t.filename);
}
else
{
LoadAudio(t);
}
}
void OpenFile(string filename)
{
var match = playlist.First(x => x.filename == filename);
if (match == null) OpenFile(new Track(filename, filename));
else OpenFile(match);
}
private void RefreshPlaylistGrid()
{
trackGrid.Columns.Clear();
List<DataGridViewTextBoxColumn> columns = new List<DataGridViewTextBoxColumn>();
for (int i = 0; i < currentColumnInfo.Count; i++)
{
columns.Add(new DataGridViewTextBoxColumn()
{
Width = currentColumnInfo[i].width,
DataPropertyName = COLUMN_PROPERTIES[currentColumnInfo[i].id],
Name = COLUMN_PROPERTIES[currentColumnInfo[i].id],
HeaderText = COLUMN_HEADERS[currentColumnInfo[i].id],
Tag = currentColumnInfo[i].id
});
}
foreach (DataGridViewTextBoxColumn clmn in columns)
{
trackGrid.Columns.Add(clmn);
}
//filter with searchbox
SortableBindingList<Track> source;
string searchWord = searchBox.Text;
if (String.IsNullOrEmpty(searchWord))
{
source = new SortableBindingList<Track>(playlist);
}
else
{
List<Track> tracksWithDupes = new List<Track>();
var searchOrKeywords = searchWord.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string or in searchOrKeywords)
{
var sourceList = new List<Track>(playlist);
var searchKeywords = or.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in searchKeywords)
{
bool invertSearch = false;
string searchWrd = s.TrimStart();
if (searchWrd.StartsWith("!"))
{
searchWrd = searchWrd.Substring(1);
invertSearch = true;
}
searchWrd = searchWrd.Trim();
//process special keywords
switch (searchWrd)
{
case "%monthago":
sourceList = sourceList.Where(x => x.lastOpened < DateTime.Now.AddDays(-30)).ToList();
break;
case "%weekago":
sourceList = sourceList.Where(x => x.lastOpened < DateTime.Now.AddDays(-7)).ToList();
break;
case "%dayago":
sourceList = sourceList.Where(x => x.lastOpened < DateTime.Now.AddDays(-1)).ToList();
break;
case "%never":
sourceList = sourceList.Where(x => x.lastOpened == DateTime.MinValue).ToList();
break;
default:
//process keywords with =variable
if (searchWrd.StartsWith("%daysago="))
{
searchWrd = searchWrd.Split('=').Last();
try
{
int dayNumber = Int32.Parse(searchWrd);
sourceList = sourceList.Where(x => x.lastOpened < DateTime.Now.AddDays(dayNumber * -1)).ToList();
}
catch (Exception) { }
break;
}
else if (searchWord.StartsWith("%artist="))
{
searchWrd = searchWrd.Split('=').Last().ToLower();
sourceList = sourceList.Where(x => x.artist.ToLower() == searchWrd).ToList();
break;
}
else if (searchWord.StartsWith("%title="))
{
searchWrd = searchWrd.Split('=').Last().ToLower();
sourceList = sourceList.Where(x => x.title.ToLower() == searchWrd).ToList();
break;
}
else if (searchWord.StartsWith("%album="))
{
searchWrd = searchWrd.Split('=').Last().ToLower();
sourceList = sourceList.Where(x => x.album.ToLower().ToLower() == searchWrd).ToList();
break;
}
else if (searchWord.StartsWith("%top="))
{
searchWrd = searchWrd.Split('=').Last().ToLower();
int searchInt;