-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
4339 lines (3752 loc) · 180 KB
/
script.js
File metadata and controls
4339 lines (3752 loc) · 180 KB
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
const { SamBA, Device, Flasher } = window.bossa;
let midiAccess;
let lastMessage = [];
let loops = [];
let remotes = [];
let patchName;
let patchesNames = [];
let currentBankLetter = null;
let activePatch = null;
let isProcessingPatch = false; // Flag para impedir cliques multiplos
let loopsNames = [];
let loopsNamesChars = [];
let remoteNames = [];
let remoteNamesChars = [];
let midiChannelNames = [];
let midiChannelNamesChars = [];
let midiChannelMap = {};
let midiChannelNames2 = [];
let midiChannelNamesChars2 = [];
let midiChannelMap2 = {};
let midiChannelNames3 = [];
let midiChannelNamesChars3 = [];
let midiChannelMap3 = {};
let selectedButtonIndices = {
'midi-table': 0,
'midi-table-2': 0,
'midi-table-3': 0
};
let advanced1 = [];
let advanced2 = [];
let advanced3 = [];
let usb1 = [];
let usb2 = [];
let air1 = [];
let air2 = [];
let air3 = [];
let savePresetAux = 0;
let presetFileCreationArray = [];
let saveBackupAux = 0;
let backupFileCreationArray = [];
let dispositivoConectado;
let precisaAtualizar;
let deviceVersion;
let versions;
let latestVersion;
let ignorarDesconexao = false;
let nomeControladora = "timespace"
//updateDevice()
// Função base da inicialização do site
async function initializeSite() {
//updateDevice()
nomeControladora = null;
let response = await fetch('https://editor.saturnopedais.com.br/versions.json');
versions = await response.json();
await setupMidiListener();
let lim = 0;
while (nomeControladora === null) {
console.log('Aguardando nomeControladora...');
sendMessage([0xF0,0x01,0x00,0xF7])
// Aqui você pode aguardar algum tempo antes de verificar novamente
await new Promise(resolve => setTimeout(resolve, 400));
lim++;
if (lim > 10) location.reload();
}
lastMessage = [];
if (nomeControladora !== 'titan' && nomeControladora !== 'supernova') {
console.log("Dispositivo não é uma Controladora, carregando o script dos pedais");
let fallbackScript = document.createElement('script');
fallbackScript.src = 'pedalScript.js';
document.body.appendChild(fallbackScript);
return;
}
sendMessage([0xF0,0x1B,0x00,0xF7])
sendMessage([0xF0,0x1C,0x00,0xF7])
sendMessage([0xF0,0x1D,0x00,0xF7])
sendMessage([0xF0,0x1E,0x00,0xF7])
sendMessage([0xF0,0x1F,0x00,0xF7])
const sidebar = document.getElementById('sidebar');
for (let i = 65; i <= 90; i++) {
const letter = String.fromCharCode(i);
const bank = createBank(letter, i);
const bankDetails = createBankPatches(letter, i);
bankSelect(bank, bankDetails, i);
sidebar.appendChild(bank);
sidebar.appendChild(bankDetails);
}
const mainContent = document.getElementById("mainContent");
mainContent.addEventListener("dragover", (e) => {
e.preventDefault();
mainContent.classList.add("drag-over");
});
mainContent.addEventListener("dragleave", () => {
mainContent.classList.remove("drag-over");
});
mainContent.addEventListener("drop", async (e) => {
e.preventDefault();
mainContent.classList.remove("drag-over");
const content = e.dataTransfer.getData("application/json");
const fileName = e.dataTransfer.getData("text/plain");
const fromSaturnRepo = e.dataTransfer.getData("isSaturnRepo") === "true";
if (!content || !fileName.endsWith(".stnpreset") || fromSaturnRepo) {
console.log("Invalid drop or file not from manager.");
return;
}
const result = await Swal.fire({
title: "Load backup?",
text: `Do you want to load the backup? The current settings will be lost.`,
icon: "question",
background: "#2a2a40",
color: "white",
width: "500px",
showCancelButton: true,
confirmButtonText: "Yes, load backup",
cancelButtonText: "Cancel",
cancelButtonColor: "red",
confirmButtonColor: "#53bfeb",
});
if (!result.isConfirmed) return;
Swal.fire({
toast: true,
position: "bottom-end",
background: "#2a2a40",
color: "rgb(83, 191, 235)",
icon: "info",
title: "Loading backup...",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true
});
const parsed = JSON.parse(content);
const fullArray = new Uint8Array(parsed);
const originalArray = decode(fullArray.slice(1));
console.log(`Backup content of ${fileName}:`, originalArray);
const header = [...originalArray.slice(0, 9)];
let resto = originalArray.slice(9);
const partes = [];
const command = 0x4D;
while (resto.length > 0) {
const parte = resto.slice(0, 42);
partes.push(parte);
resto = resto.slice(42);
}
document.getElementById("loading-overlay").style.display = "flex";
// Header
sendMessage([0xF0, command, 0x00, 0x00, ...header, 0xF7]);
// Resto
for (let index = 0; index < partes.length; index++) {
const parte = partes[index];
await delay(1);
sendMessage([0xF0, command, (index + 1) % 128, Math.floor((index + 1) / 128), ...parte, 0xF7]);
}
});
return
}
// Cria um banco
let swapping = false;
function createBank(letter, index) {
const bank = document.createElement('div');
bank.className = 'bank';
bank.dataset.letter = letter; // Define o atributo data-letter
const ball = document.createElement('span');
ball.textContent = '\u2B24';
ball.style.marginRight = '10px';
bank.appendChild(ball);
const bankText = document.createTextNode(`Bank ${letter}`);
bank.appendChild(bankText);
// Criar um contêiner para os botões do Bank
const buttonContainer = document.createElement('div');
buttonContainer.className = 'bank-button-container';
buttonContainer.style.display = 'inline-flex';
buttonContainer.style.gap = '8px';
buttonContainer.style.marginLeft = '10px';
// Botão copy
const copyIcon = document.createElement('i');
copyIcon.className = 'fa-regular fa-copy bank-copy-icon';
copyIcon.title = 'Copy Bank';
copyIcon.style.display = 'none';
copyIcon.style.cursor = 'pointer';
copyIcon.style.marginTop = '4px';
// Botão de colar
const pasteIcon = document.createElement('i');
pasteIcon.className = 'fa-regular fa-paste bank-paste-icon';
pasteIcon.title = 'Paste Bank';
pasteIcon.style.display = 'none';
pasteIcon.style.cursor = 'pointer';
// Ao clicar no copyIcon, salva o bank copiado e exibe todos os botões de paste
copyIcon.onclick = () => {
event.stopPropagation();
copiedBank = `Bank ${letter}`;
notify(`Bank ${letter} copied!`);
// Esconder todos os botões Swap ao copiar
document.querySelectorAll('.bank-swap-icon').forEach(icon => {
const bankElement = icon.closest('.bank'); // Encontra o bank mais próximo
if (bankElement && bankElement.dataset.letter == currentBankLetter) {
icon.style.display = 'inline-block';
} else {
icon.style.display = 'none';
}
});
// Exibir botões Paste em todos os outros Banks
document.querySelectorAll('.bank-paste-icon').forEach(icon => {
const bankElement = icon.closest('.bank'); // Encontra o bank mais próximo
if (bankElement && bankElement.dataset.letter !== currentBankLetter) {
icon.style.display = 'inline-block';
} else {
icon.style.display = 'none';
}
});
};
// Ao clicar no pasteIcon, envia mensagem, exibe alerta e oculta todos os botões de paste
pasteIcon.onclick = () => {
sendMessage([0xF0, 0x17, letter.charCodeAt(0) - 65, 0xF7]);
notify(`Bank ${letter} updated with the content from ${copiedBank}`, 'success');
document.querySelectorAll('.bank-paste-icon').forEach(icon => {
icon.style.display = 'none';
});
};
// Criar ícone de Swap para os Banks
const swapIcon = document.createElement('i');
swapIcon.className = 'fa-solid fa-rotate bank-swap-icon';
swapIcon.title = 'Swap Bank';
swapIcon.style.display = 'none';
swapIcon.style.cursor = 'pointer';
swapIcon.style.marginTop = '4px';
// Evento de clique no Swap (seleciona um banco para troca)
swapIcon.onclick = () => {
if (swapping) {
swapping = false;
notify(`Switching Bank ${swapBank} with Bank ${letter}`, 'success');
sendMessage([0xF0,0x18,letter-65,0xF7])
// Esconder todos os botões Swap após a troca
document.querySelectorAll('.bank-swap-icon').forEach(icon => {
const bankElement = icon.closest('.bank'); // Encontra o bank mais próximo
if (bankElement && bankElement.dataset.letter !== currentBankLetter) {
icon.style.display = 'inline-block';
} else {
icon.style.display = 'none';
}
});
} else {
event.stopPropagation();
swapping = true;
swapBank = letter; // Armazena apenas a letra para facilitar a lógica
notify(`Bank ${swapBank} selected for a swap`);
// Esconder todos os botões Paste ao selecionar Swap
document.querySelectorAll('.bank-paste-icon').forEach(icon => {
icon.style.display = 'none';
});
// Exibir botões Swap em todos os outros Banks
document.querySelectorAll('.bank-swap-icon').forEach(icon => {
const bankElement = icon.closest('.bank'); // Encontra o bank mais próximo
if (bankElement && bankElement.dataset.letter !== currentBankLetter) {
icon.style.display = 'inline-block';
} else {
//icon.style.display = 'none';
}
});
}
};
// Criar ícone de Clear (Resetar Bank)
const clearIcon = document.createElement('i');
clearIcon.className = 'fa-solid fa-xmark bank-clear-icon';
clearIcon.title = 'Clear Bank';
clearIcon.style.display = 'none';
clearIcon.style.cursor = 'pointer';
clearIcon.style.fontSize = '23px';
clearIcon.style.marginLeft = '8px';
// Evento de clique no Clear (resetar o Bank)
clearIcon.onclick = () => {
Swal.fire({
title: "Are you sure?",
text: `All settings of Bank ${letter} will be lost!`,
icon: "warning",
color: "white",
width: "600px",
background: "#2a2a40",
showCancelButton: true,
confirmButtonText: "Yes, reset!",
cancelButtonText: "Cancel",
confirmButtonColor: "red",
cancelButtonColor: "#53bfeb"
}).then((result) => {
if (result.isConfirmed) {
notify(`Bank ${letter} has been reset!`, 'success');
sendMessage([0xF0, 0x19, 0x00, 0xF7]); // Send reset command
}
});
};
buttonContainer.appendChild(copyIcon);
buttonContainer.appendChild(pasteIcon);
buttonContainer.appendChild(swapIcon);
buttonContainer.appendChild(clearIcon);
// Agora, adicionamos o container ao Bank
bank.appendChild(buttonContainer);
const arrow = document.createElement('span');
arrow.textContent = '\u276E';
arrow.style.transform = 'rotate(-90deg) scale(1.8)';
bank.appendChild(arrow);
setBankColor(bank, ball, arrow, index);
return bank;
}
// Calcula a cor do banco
function setBankColor(bank, ball, arrow, index) {
const color = index % 2 === 0 ? '#53bfeb' : '#9f18fd';
ball.style.color = color;
arrow.style.color = color;
bank.dataset.color = color;
}
let copiedBank = null; // Variável global para armazenar o banco copiado
let swapBank = null;
// Lida com a seleção de um banco
function bankSelect(bank, bankDetails, index) {
bank.addEventListener('click', () => {
activePatch = null;
const patchCopyIcon = document.getElementById('patch-copy-icon');
if (patchCopyIcon) {
patchCopyIcon.remove();
}
const patchSwapIcon = document.getElementById('patch-swap-icon');
if (patchSwapIcon) {
patchSwapIcon.remove();
}
const patchClearIcon = document.getElementById('patch-clear-icon');
if (patchClearIcon) {
patchClearIcon.remove();
}
const isActive = bank.classList.contains('active');
document.querySelectorAll('.table-section').forEach(table => {
table.style.display = 'none';
});
document.getElementById('patchTitle').style.display = 'none';
document.getElementById('saveButton').style.display = 'none';
document.getElementById('cancelButton').style.display = 'none';
// Atualiza a variável global com a letra do banco atual
if (!isActive) {
currentBankLetter = bank.dataset.letter; // Atribui a letra do banco atual
console.log(`Banco selecionado: ${currentBankLetter}`);
// Remove a configuração antiga se existir
const existingConfig = document.getElementById('bnkCfg');
if (existingConfig) existingConfig.remove();
// Chama createBnkCfg passando a letra do banco
createBnkCfg(currentBankLetter);
} else {
//currentBankLetter = null; // Nenhum banco ativo
}
//alert([0xF0, 0x0B, currentBankLetter.charCodeAt(0) - 65, 0xF7])
// Envia mensagens MIDI relacionadas ao banco
sendMessage([0xF0, 0x09, index - 65, 0, 0xF7]);
sendMessage([0xF0, 0x0A, index - 65, 0xF7]);
sendMessage([0xF0, 0x10, currentBankLetter.charCodeAt(0) - 65, 0xF7]);
sendMessage([0xF0, 0x0B, currentBankLetter.charCodeAt(0) - 65, 0xF7]);
// Remove o estado ativo e oculta o ícone de copiar de todos os bancos
document.querySelectorAll('.bank').forEach(b => {
b.classList.remove('active');
b.style.backgroundColor = '';
const copyIcon = b.querySelector('.bank-copy-icon');
if (copyIcon) {
copyIcon.style.display = 'none';
}
const pasteIcon = b.querySelector('.bank-paste-icon');
if (pasteIcon) {
pasteIcon.style.display = 'none';
}
const swapIcon = b.querySelector('.bank-swap-icon');
if (swapIcon) {
swapIcon.style.display = 'none';
}
const clearIcon = b.querySelector('.bank-clear-icon');
if (clearIcon) {
clearIcon.style.display = 'none';
}
const arrow = b.querySelector('span:last-child');
arrow.style.transform = 'rotate(-90deg) scale(1.8)';
});
document.querySelectorAll('.bank-details').forEach(details => details.style.display = 'none');
if (!isActive) {
bank.style.backgroundColor = index % 2 === 0
? 'rgba(83, 191, 235, 0.5)'
: 'rgba(159, 24, 253, 0.5)';
bank.classList.add('active');
const arrow = bank.querySelector('span:last-child');
arrow.style.transform = 'rotate(90deg) scale(1.8)';
bankDetails.style.display = 'block';
// Exibe o ícone de copiar para o banco selecionado
const copyIcon = bank.querySelector('.bank-copy-icon');
if (copyIcon) {
copyIcon.style.display = 'inline-block';
}
const swapIcon = bank.querySelector('.bank-swap-icon');
if (swapIcon) {
swapIcon.style.display = 'inline-block';
}
const clearIcon = bank.querySelector('.bank-clear-icon');
if (clearIcon) {
clearIcon.style.display = 'inline-block';
}
}
swapping = false;
});
}
function createBnkCfg(letter) {
const bnkCfg = document.createElement('div');
bnkCfg.id = 'bnkCfg';
//bnkCfg.style.position = 'absolute';
//bnkCfg.style.right = '20px';
//bnkCfg.style.top = '50%';
//bnkCfg.style.transform = 'translateY(-50%)';
//bnkCfg.style.backgroundColor = 'rgba(159, 24, 253, 0.5)';
bnkCfg.style.backgroundColor = '#3a3a57';
bnkCfg.style.borderRadius = '0px 0px 8px 8px';
bnkCfg.style.padding = '20px';
bnkCfg.style.color = '#fff';
bnkCfg.style.width = '257px';
bnkCfg.style.height = '110px';
bnkCfg.style.textAlign = 'center';
bnkCfg.style.zIndex = '0';
bnkCfg.style.marginTop = '-10px';
// Criar título
const titleRow = document.createElement('div');
titleRow.innerHTML = `<span style="color: #53bfeb;">Bank ${letter}</span> <span style="color: white;">Configuration</span>`;
titleRow.style.fontSize = '14px';
titleRow.style.fontWeight = '600';
titleRow.style.marginBottom = '10px';
titleRow.style.marginTop = '-6px';
bnkCfg.appendChild(titleRow);
// Criar botões
const labels = ['Reclick', 'Hold', 'BnkUp', 'BnkDown'];
labels.forEach((label, i) => {
const row = document.createElement('div');
row.style.display = 'flex';
row.style.justifyContent = 'space-between';
row.style.alignItems = 'center';
//row.style.marginBottom = '10px';
const rowLabel = document.createElement('span');
rowLabel.textContent = label;
rowLabel.style.fontSize = '14px';
row.appendChild(rowLabel);
const rowButton = document.createElement('button');
rowButton.textContent = 'OFF';
rowButton.style.backgroundColor = 'transparent';
rowButton.style.color = 'red';
rowButton.style.fontSize = '14px';
rowButton.style.border = 'none';
rowButton.style.cursor = 'pointer';
rowButton.style.padding = '5px 10px';
//rowButton.style.fontWeight = 'bold';
rowButton.addEventListener('click', (e) => {
e.stopPropagation();
const options = [];
options.push('OFF');
if (i <= 1) {
for (let letterAux = 65; letterAux <= 90; letterAux++) {
if (String.fromCharCode(letterAux) != letter){
options.push(`Load from ${String.fromCharCode(letterAux)}`);
}
}
} else {
options.push('Locked');
for (let letterAux = 65; letterAux <= 90; letterAux++) {
if (String.fromCharCode(letterAux) != letter){
options.push(`Load from ${String.fromCharCode(letterAux)}`);
for (let num = 1; num <= 8; num++) {
options.push(`Load from ${String.fromCharCode(letterAux)}${num}`);
}
}
}
}
createConfigPopup(rowButton, null, null, (selectedValue) => {
rowButton.textContent = selectedValue;
rowButton.style.color = selectedValue === 'OFF' ? 'red' : 'lime';
}, options);
});
row.appendChild(rowButton);
bnkCfg.appendChild(row);
});
const details = document.querySelector(`.bank[data-letter="${letter}"] + .bank-details`);
// Insere depois dos detais
if (details && details.parentNode) {
details.parentNode.insertBefore(bnkCfg, details.nextSibling);
}
// Insere antes dos detais
/*if (details && details.parentNode) {
details.parentNode.insertBefore(bnkCfg, details);
}*/
}
function createConfigPopup(detailButton, rangeStart, rangeEnd, onSelectCallback, customOptions = null) {
// Fecha popups abertos
const existingPopup = document.querySelector('.value-popup');
if (existingPopup) existingPopup.remove();
// Cria o popup
const valuePopup = document.createElement('div');
valuePopup.className = 'value-popup';
valuePopup.style.position = 'absolute';
valuePopup.style.backgroundColor = '#242424';
valuePopup.style.borderRadius = '5px';
valuePopup.style.maxHeight = '200px';
valuePopup.style.overflowY = 'auto';
valuePopup.style.scrollbarWidth = 'none';
valuePopup.style.width = '100px';
valuePopup.style.textAlign = 'center';
// Impede popup de "sair" da tela
const rect = detailButton.getBoundingClientRect();
const popupHeight = 200;
let top = rect.bottom;
let left = rect.left;
if (top + popupHeight > window.innerHeight) {
top = Math.max(rect.top - popupHeight, 0);
}
valuePopup.style.top = `${top}px`;
valuePopup.style.left = `${left}px`;
// Adiciona valores personalizados, se fornecidos
if (customOptions) {
customOptions.forEach((option) => {
const valueButton = document.createElement('button');
valueButton.textContent = option;
valueButton.style.display = 'block';
valueButton.style.width = '100%';
valueButton.style.marginBottom = '5px';
valueButton.style.padding = '5px';
valueButton.style.cursor = 'pointer';
valueButton.addEventListener('click', () => {
onSelectCallback(option);
const selectedValues = Array.from(document.querySelectorAll('#bnkCfg button'))
.map(btn => btn.textContent)
//alert(`Valores atuais: ${selectedValues}`);
let data = []; // Cria um array vazio
selectedValues.forEach((value, index) => {
if (value == 'OFF'){
data.push(0)
} else if (value == 'Locked'){
data.push(1)
} else if (index < 2){
let aux = value.slice(-1).charCodeAt(0);
data.push(aux - 64)
} else {
let aux = value.replace("Load from ", "");
if (aux.length === 1) {
aux = (aux.charCodeAt(0) - 65) * 9 + 2;
} else {
aux = (aux.charCodeAt(0) - 65) * 9 + parseInt(aux[1]) + 2;
}
data.push(aux)
}
});
//alert(data[2])
//alert([...data].map(num => Number(num).toString(2).padStart(8, '0')).join(' '))
sendMessage([0xF0,0x0C, currentBankLetter.charCodeAt(0)-65,data[0],data[1],
data[2]&0b00001111,((data[2] & 0b11110000) >> 4),data[3]&0b00001111,((data[3]&0b11110000)>>4) ,0xF7])
valuePopup.remove();
});
valuePopup.appendChild(valueButton);
});
}
// Adiciona popup ao documento
document.body.appendChild(valuePopup);
// Fecha o popup ao clicar fora
document.addEventListener(
'click',
(e) => {
if (!valuePopup.contains(e.target)) {
valuePopup.remove();
}
},
{ once: true }
);
}
// Base para a criação dos patches
let copiedPatchId = null; // Armazena o ID do patch copiado
let swapPatchId = null; // Armazena o ID do patch para troca (swap)
function createBankPatches(letter, index) {
const bankDetails = document.createElement('div');
bankDetails.className = 'bank-details';
const patchList = document.createElement('ul');
let size = 8;
if (nomeControladora === 'supernova') {
size = 5;
}
for (let j = 1; j <= size; j++) {
const patchId = `${letter}${j}`; // Identificador do patch
const patchItem = createPatch(letter, j, index);
const inputElement = patchItem.querySelector('input');
patchItem.dataset.patchId = patchId;
// Botão de colar (inicialmente oculto)
const pasteButton = document.createElement('button');
pasteButton.className = 'paste-button';
pasteButton.style.display = 'none'; // Oculto por padrão
// Usando o ícone de paste da Font Awesome
const pasteIcon = document.createElement('i');
pasteIcon.className = 'fa-regular fa-paste';
pasteIcon.style.fontSize = '20px';
pasteButton.appendChild(pasteIcon);
pasteButton.onclick = async () => {
if (copiedPatchId) {
sendMessage([0xF0,0x09,copiedPatchId.charCodeAt(0)-65,copiedPatchId.slice(-1),0xF7])
//alert(copiedPatchId)
sendMessage([0xF0, 0x15, letter.charCodeAt(0)-65, j, 0xF7])
// Esconde todos os botões "Paste" ao clicar em um
document.querySelectorAll('.paste-button').forEach(button => {
button.style.display = 'none';
});
}
};
patchItem.appendChild(pasteButton);
const swapButton = document.createElement('button');
swapButton.className = 'swap-button';
swapButton.style.display = 'none';
const swapIcon = document.createElement('i');
//swapIcon.className = 'fa-solid fa-rotate';
swapIcon.className = 'fa-solid fa-arrows-rotate';
swapIcon.style.fontSize = '20px';
swapButton.appendChild(swapIcon);
swapButton.onclick = () => {
if (swapPatchId) {
sendMessage([0xF0,0x09,swapPatchId.charCodeAt(0)-65,swapPatchId.slice(-1),0xF7])
notify(`Switching ${swapPatchId} with ${patchId}`, 'success');
document.querySelectorAll('.swap-button').forEach(button => {
button.style.display = 'none';
});
//sendMessage([0xF0,0x16,swapPatchId.charCodeAt(0)-65,swapPatchId.slice(1),0xF7])
sendMessage([0xF0,0x16,patchId.charCodeAt(0)-65,patchId.slice(1),0xF7])
}
};
patchItem.appendChild(swapButton);
patchItem.addEventListener('click', async () => {
if (isProcessingPatch || activePatch === patchId) return;
isProcessingPatch = true;
activePatch = letter + j;
document.getElementById('patchTitle').style.display = 'flex';
selectedButtonIndices = {
'midi-table': 0,
'midi-table-2': 0,
'midi-table-3': 0
};
const patchNameValue = inputElement.value || `Patch ${patchId}`;
const selectedPatchText = document.getElementById('selectedPatch');
const selectedPatchType = document.getElementById('patchType');
selectedPatchText.textContent = inputElement.value
? `${patchId} - ${patchNameValue}`
: `Patch ${patchId}`;
const type = localStorage.getItem(`${letter}${j}_type`) || 'Preset';
selectedPatchType.textContent = `(${type})`;
// Remove ícone de cópia para ser recriado pertencendo a esse patch
const existingCopyIcon = document.getElementById('patch-copy-icon');
const existingSwapIcon = document.getElementById('patch-swap-icon');
const existingClearIcon = document.getElementById('patch-clear-icon');
if (existingCopyIcon) existingCopyIcon.remove();
if (existingSwapIcon) existingSwapIcon.remove();
if (existingClearIcon) existingClearIcon.remove();
// Cria um novo ícone de cópia
const patchCopyIcon = document.createElement('i');
patchCopyIcon.id = 'patch-copy-icon';
patchCopyIcon.className = 'fa-regular fa-copy';
patchCopyIcon.title = 'Copy Patch';
patchCopyIcon.style.position = 'absolute';
patchCopyIcon.style.cursor = 'pointer';
patchCopyIcon.style.fontSize = '20px';
patchCopyIcon.onclick = () => {
copiedPatchId = patchId;
notify(`Patch ${patchId} Copied!`);
document.querySelectorAll('.swap-button').forEach(button => {
button.style.display = 'none';
});
document.querySelectorAll('.paste-button').forEach(button => {
if (button.parentNode.dataset.patchId !== copiedPatchId) {
button.style.display = 'inline-block';
} else {
button.style.display = 'none';
}
});
};
// Cria um novo ícone de swap
const patchSwapIcon = document.createElement('i');
patchSwapIcon.id = 'patch-swap-icon';
//patchSwapIcon.className = 'fa-solid fa-rotate';
patchSwapIcon.className = 'fa-solid fa-arrows-rotate';
patchSwapIcon.title = 'Swap Patch';
patchSwapIcon.style.position = 'absolute';
patchSwapIcon.style.cursor = 'pointer';
patchSwapIcon.style.fontSize = '20px';
patchSwapIcon.style.marginLeft = '30px';
patchSwapIcon.onclick = () => {
swapPatchId = patchId;
notify(`${patchId} selected for a swap`);
document.querySelectorAll('.paste-button').forEach(button => {
button.style.display = 'none';
});
document.querySelectorAll('.swap-button').forEach(button => {
if (button.parentNode.dataset.patchId !== swapPatchId) {
button.style.display = 'inline-block';
} else {
button.style.display = 'none';
}
});
};
// Cria um novo ícone de clear
const patchClearIcon = document.createElement('i');
patchClearIcon.id = 'patch-clear-icon';
patchClearIcon.className = 'fa-solid fa-xmark';
patchClearIcon.title = 'Clear Patch';
patchClearIcon.style.position = 'absolute';
patchClearIcon.style.cursor = 'pointer';
patchClearIcon.style.fontSize = '25px';
patchClearIcon.style.marginLeft = '50px';
patchClearIcon.onclick = () => {
Swal.fire({
title: "Are you sure?",
text: `All settings of Patch ${patchId} will be lost!`,
icon: "warning",
color: "white",
width: "600px",
background: "#2a2a40",
showCancelButton: true,
confirmButtonText: "Yes, reset!",
cancelButtonText: "Cancel",
confirmButtonColor: "red",
cancelButtonColor: "#53bfeb" //voltar
}).then((result) => {
if (result.isConfirmed) {
notify(`Patch ${patchId} reseted!`, 'success');
sendMessage([0xF0, 0x14, letter.charCodeAt(0) - 65, j, 0xF7]);
}
});
};
const mainContent = document.getElementById('mainContent');
mainContent.appendChild(patchCopyIcon);
mainContent.appendChild(patchSwapIcon);
mainContent.appendChild(patchClearIcon);
const rect = selectedPatchText.getBoundingClientRect();
const mainRect = mainContent.getBoundingClientRect();
const scrollY = mainContent.scrollTop;
const scrollX = mainContent.scrollLeft;
patchCopyIcon.style.top = `${rect.top - mainRect.top + scrollY}px`;
patchCopyIcon.style.left = `${rect.right - mainRect.left + scrollX + 50}px`;
patchSwapIcon.style.top = patchCopyIcon.style.top;
patchSwapIcon.style.left = `${parseInt(patchCopyIcon.style.left) + 20}px`;
patchClearIcon.style.top = `${parseInt(patchCopyIcon.style.top) - 2}px`;
patchClearIcon.style.left = `${parseInt(patchSwapIcon.style.left) + 20}px`;
patchChange(letter, j);
sendMessage([0xF0, 0x06, 0x00, 0xF7]);
/*const existingTable = document.getElementById('bnkCfg');
if (existingTable) {
existingTable.remove();
}
createBnkCfg(letter);*/
sendMessage([0xF0,0x10,currentBankLetter.charCodeAt(0)-65,0xF7])
await delay(200);
//sendMessage([0xF0, 0x0B, letter.charCodeAt(0) - 65, 0xF7]);
sendMessage([0xF0, 0x0D, 0x00, 0x00, 0xF7]);
sendMessage([0xF0, 0x0D, 0x01, 0x00, 0xF7]);
sendMessage([0xF0, 0x0D, 0x02, 0x00, 0xF7]);
createLoopTable(patchId, index);
createTableRemoteSwitch(patchId, index);
createMidiTable(patchId, index, "midi-table");
createMidiTable(patchId, index, "midi-table-2");
createMidiTable(patchId, index, "midi-table-3");
document.getElementById('saveButton').style.display = 'inline-block';
document.getElementById('cancelButton').style.display = 'inline-block';
setTimeout(() => {
isProcessingPatch = false; // Libera para novos cliques
}, 300);
});
inputElement.addEventListener('input', () => {
const selectedPatchText = document.getElementById('selectedPatch');
if (inputElement.value.trim() === "") {
selectedPatchText.textContent = `Patch ${patchId}`;
} else {
selectedPatchText.textContent = `${patchId} - ${inputElement.value}`;
}
});
patchList.appendChild(patchItem);
}
bankDetails.appendChild(patchList);
return bankDetails;
}
function writeAllNames(array, bankLetter) {
// Seleciona os inputs do banco selecionado
const inputs = document.querySelectorAll(`.bank[data-letter="${bankLetter}"] + .bank-details input`);
if (inputs.length === 0) {
console.error(`Nenhum input encontrado para o banco ${bankLetter}`);
return;
}
inputs.forEach((input, index) => {
if (index < array.length && array[index].trim() !== '') {
input.value = array[index];
} else {
input.value = "";
}
});
}
async function sendMessage(message) {
lastMessage.push(message[1]);
console.log(message)
if (message[1] == 10) {
let numPatches = 8;
if (nomeControladora === 'supernova') {
numPatches = 5;
}
for (let i = 1; i < numPatches; i++) {
lastMessage.push(message[1]);
}
} else if (message[1] == 0x30){
for (let i = 1; i < 32; i++) {
lastMessage.push(message[1]);
}
} else if (message[1] == 0x4A) {
for (let i = 1; i <= 4; i++) {
lastMessage.push(message[1]);
}
} else if (message[1] == 0x14 || message[1] == 0x4D){
if (nomeControladora == "timespace" || nomeControladora == "spacewalk") {
lastMessage = [];
lastMessage.push(message[1])
}
}
console.log('Mensagens enviadas: ', [...lastMessage])
try {
const outputs = Array.from(midiAccess.outputs.values());
if (outputs.length === 0) {
alert("No MIDI device found.");
return;
}
let aux = 0;
let output = null;
//alert(dispositivoConectado)
while(aux >= 0){
if (outputs[aux].name === dispositivoConectado){
output = outputs[aux];
aux = -1;
} else aux++;
}
output.send(message);
} catch (error) {
console.log("Erro ao enviar mensagem MIDI: " + error);