Debian Codegraph @

src/gui/gui.cpp

raw
1 #define _USE_MATH_DEFINES
2 // OK, sorry for inserting the define here but I'm so tired of this extension
3 /**
4 * Furnace Tracker - multi-system chiptune tracker
5 * Copyright (C) 2021-2025 tildearrow and contributors
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 // I hate you clangd extension!
23 // how about you DON'T insert random headers before this freaking important
24 // define!!!!!!
25
26 #include "gui.h"
27 #include "util.h"
28 #include "../ta-log.h"
29 #include "../fileutils.h"
30 #include "imgui.h"
31 #include "imgui_internal.h"
32 #include "ImGuiFileDialog.h"
33 #include "IconsFontAwesome4.h"
34 #include "misc/cpp/imgui_stdlib.h"
35 #include "plot_nolerp.h"
36 #include "guiConst.h"
37 #include "intConst.h"
38 #include "scaling.h"
39 #include "introTune.h"
40 #include <stdint.h>
41 #include <zlib.h>
42 #include <fmt/printf.h>
43 #include <stdexcept>
44
45 #ifdef _WIN32
46 #include <windows.h>
47 #include <shlobj.h>
48 #include <shlwapi.h>
49 #include "../utfutils.h"
50 #define LAYOUT_INI "\\layout.ini"
51 #define BACKUPS_DIR "\\backups"
52 #else
53 #include <sys/types.h>
54 #include <dirent.h>
55 #include <unistd.h>
56 #include <pwd.h>
57 #include <sys/stat.h>
58 #define LAYOUT_INI "/layout.ini"
59 #define BACKUPS_DIR "/backups"
60 #endif
61
62 #ifdef IS_MOBILE
63 #define MOBILE_UI_DEFAULT true
64 #else
65 #define MOBILE_UI_DEFAULT false
66 #endif
67
68 #include "actionUtil.h"
69
70 #ifdef HAVE_SNDFILE
71 #include <sndfile.h>
72 #endif
73
74 bool Particle::update(float frameTime) {
75 pos.x+=speed.x*frameTime;
76 pos.y+=speed.y*frameTime;
77 speed.x*=1.0-((1.0-friction)*frameTime);
78 speed.y*=1.0-((1.0-friction)*frameTime);
79 speed.y+=gravity*frameTime;
80 life-=lifeSpeed*frameTime;
81 return (life>0);
82 }
83
84 void FurnaceGUI::centerNextWindow(const char* name, float w, float h) {
85 if (ImGui::IsPopupOpen(name)) {
86 if (settings.centerPopup) {
87 ImGui::SetNextWindowPos(ImVec2(w*0.5,h*0.5),ImGuiCond_Always,ImVec2(0.5,0.5));
88 }
89 }
90 }
91
92 void FurnaceGUI::bindEngine(DivEngine* eng) {
93 e=eng;
94 wavePreview.setEngine(e);
95 }
96
97 void FurnaceGUI::enableSafeMode() {
98 safeMode=true;
99 }
100
101 const char* FurnaceGUI::noteName(short note, short octave) {
102 if (note==100) {
103 return noteOffLabel;
104 } else if (note==101) { // note off and envelope release
105 return noteRelLabel;
106 } else if (note==102) { // envelope release only
107 return macroRelLabel;
108 } else if (octave==0 && note==0) {
109 return emptyLabel;
110 } else if (note==0 && octave!=0) {
111 return "BUG";
112 }
113 int seek=(note+(signed char)octave*12)+60;
114 if (seek<0 || seek>=180) {
115 return "???";
116 }
117 if (settings.flatNotes) {
118 if (settings.germanNotation) return noteNamesGF[seek];
119 return noteNamesF[seek];
120 }
121 if (settings.germanNotation) return noteNamesG[seek];
122 return noteNames[seek];
123 }
124
125 bool FurnaceGUI::decodeNote(const char* what, short& note, short& octave) {
126 if (strlen(what)!=3) return false;
127 if (strcmp(what,"...")==0) {
128 note=0;
129 octave=0;
130 return true;
131 }
132 if (strcmp(what,"???")==0) {
133 note=0;
134 octave=0;
135 return true;
136 }
137 if (strcmp(what,"OFF")==0) {
138 note=100;
139 octave=0;
140 return true;
141 }
142 if (strcmp(what,"===")==0) {
143 note=101;
144 octave=0;
145 return true;
146 }
147 if (strcmp(what,"REL")==0) {
148 note=102;
149 octave=0;
150 return true;
151 }
152 for (int i=0; i<180; i++) {
153 if (strcmp(what,noteNames[i])==0) {
154 if ((i%12)==0) {
155 note=12;
156 octave=(unsigned char)((i/12)-6);
157 } else {
158 note=i%12;
159 octave=(unsigned char)((i/12)-5);
160 }
161 return true;
162 }
163 }
164 return false;
165 }
166
167 String FurnaceGUI::encodeKeyMap(std::map<int,int>& map) {
168 String ret;
169 for (std::map<int,int>::value_type& i: map) {
170 ret+=fmt::sprintf("%d:%d;",i.first,i.second);
171 }
172 return ret;
173 }
174
175 void FurnaceGUI::decodeKeyMap(std::map<int,int>& map, String source) {
176 map.clear();
177 bool inValue=false;
178 bool negateKey=false;
179 bool negateValue=false;
180 int key=0;
181 int val=0;
182 for (char& i: source) {
183 switch (i) {
184 case '0': case '1': case '2': case '3': case '4':
185 case '5': case '6': case '7': case '8': case '9':
186 if (inValue) {
187 val*=10;
188 val+=i-'0';
189 } else {
190 key*=10;
191 key+=i-'0';
192 }
193 break;
194 case '-':
195 if (inValue) {
196 negateValue=true;
197 } else {
198 negateKey=true;
199 }
200 break;
201 case ':':
202 inValue=true;
203 break;
204 case ';':
205 if (inValue) {
206 map[negateKey?-key:key]=negateValue?-val:val;
207 }
208 key=0;
209 val=0;
210 inValue=false;
211 negateKey=false;
212 negateValue=false;
213 break;
214 }
215 }
216 }
217
218 void FurnaceGUI::encodeMMLStr(String& target, int* macro, int macroLen, int macroLoop, int macroRel, bool hex, bool bit30) {
219 target="";
220 char buf[32];
221 for (int i=0; i<macroLen; i++) {
222 if (i==macroLoop) target+="| ";
223 if (i==macroRel) target+="/ ";
224 if (bit30 && ((macro[i]&0xc0000000)==0x40000000 || (macro[i]&0xc0000000)==0x80000000)) target+="@";
225 int macroVal=macro[i];
226 if (macro[i]<0) {
227 if (!(macroVal&0x40000000)) macroVal|=0x40000000;
228 } else {
229 if (macroVal&0x40000000) macroVal&=~0x40000000;
230 }
231 if (hex) {
232 if (i==macroLen-1) {
233 snprintf(buf,31,"%.2X",macroVal);
234 } else {
235 snprintf(buf,31,"%.2X ",macroVal);
236 }
237 } else {
238 if (i==macroLen-1) {
239 snprintf(buf,31,"%d",macroVal);
240 } else {
241 snprintf(buf,31,"%d ",macroVal);
242 }
243 }
244 target+=buf;
245 }
246 }
247
248 void FurnaceGUI::decodeMMLStrW(String& source, int* macro, int& macroLen, int macroMin, int macroMax, bool hex) {
249 int buf=0;
250 bool negaBuf=false;
251 bool hasVal=false;
252 macroLen=0;
253 for (char& i: source) {
254 switch (i) {
255 case '0': case '1': case '2': case '3': case '4':
256 case '5': case '6': case '7': case '8': case '9':
257 hasVal=true;
258 buf*=hex?16:10;
259 buf+=i-'0';
260 break;
261 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
262 if (hex) {
263 hasVal=true;
264 buf*=16;
265 buf+=10+i-'A';
266 }
267 break;
268 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
269 if (hex) {
270 hasVal=true;
271 buf*=16;
272 buf+=10+i-'a';
273 }
274 break;
275 case '-':
276 if (!hasVal) {
277 hasVal=true;
278 negaBuf=true;
279 }
280 break;
281 case ' ':
282 if (hasVal) {
283 hasVal=false;
284 macro[macroLen]=negaBuf?-buf:buf;
285 negaBuf=false;
286 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
287 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
288 macroLen++;
289 buf=0;
290 }
291 break;
292 }
293 if (macroLen>=256) break;
294 }
295 if (hasVal && macroLen<256) {
296 hasVal=false;
297 macro[macroLen]=negaBuf?-buf:buf;
298 negaBuf=false;
299 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
300 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
301 macroLen++;
302 buf=0;
303 }
304 }
305
306 void FurnaceGUI::decodeMMLStr(String& source, int* macro, unsigned char& macroLen, unsigned char& macroLoop, int macroMin, int macroMax, unsigned char& macroRel, bool bit30) {
307 int buf=0;
308 bool negaBuf=false;
309 bool setBit30=false;
310 bool hasVal=false;
311 macroLen=0;
312 macroLoop=255;
313 macroRel=255;
314 for (char& i: source) {
315 switch (i) {
316 case '0': case '1': case '2': case '3': case '4':
317 case '5': case '6': case '7': case '8': case '9':
318 hasVal=true;
319 buf*=10;
320 buf+=i-'0';
321 break;
322 case '-':
323 if (!hasVal) {
324 hasVal=true;
325 negaBuf=true;
326 }
327 break;
328 case '@':
329 if (bit30) {
330 setBit30=true;
331 }
332 break;
333 case ' ':
334 if (hasVal) {
335 hasVal=false;
336 macro[macroLen]=negaBuf?-buf:buf;
337 negaBuf=false;
338 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
339 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
340 if (setBit30) macro[macroLen]^=0x40000000;
341 setBit30=false;
342 macroLen++;
343 buf=0;
344 }
345 break;
346 case '|':
347 if (hasVal) {
348 hasVal=false;
349 macro[macroLen]=negaBuf?-buf:buf;
350 negaBuf=false;
351 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
352 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
353 if (setBit30) macro[macroLen]^=0x40000000;
354 setBit30=false;
355 macroLen++;
356 buf=0;
357 }
358 if (macroLoop==255) {
359 macroLoop=macroLen;
360 }
361 break;
362 case '/':
363 if (hasVal) {
364 hasVal=false;
365 macro[macroLen]=negaBuf?-buf:buf;
366 negaBuf=false;
367 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
368 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
369 if (setBit30) macro[macroLen]^=0x40000000;
370 setBit30=false;
371 macroLen++;
372 buf=0;
373 }
374 if (macroRel==255) {
375 macroRel=macroLen;
376 }
377 break;
378 }
379 if (macroLen>=255) break;
380 }
381 if (hasVal && macroLen<255) {
382 hasVal=false;
383 macro[macroLen]=negaBuf?-buf:buf;
384 negaBuf=false;
385 if (macro[macroLen]<macroMin) macro[macroLen]=macroMin;
386 if (macro[macroLen]>macroMax) macro[macroLen]=macroMax;
387 if (setBit30) macro[macroLen]^=0x40000000;
388 setBit30=false;
389 macroLen++;
390 buf=0;
391 MARK_MODIFIED;
392 }
393 }
394
395 #define CW_ADDITION(T) \
396 if (p_min!=NULL && p_max!=NULL) { \
397 if (*((T*)p_min)>*((T*)p_max)) { \
398 if (wheelY<0) { \
399 if ((*((T*)p_data)-wheelY)>*((T*)p_min)) { \
400 *((T*)p_data)=*((T*)p_min); \
401 } else { \
402 *((T*)p_data)-=wheelY; \
403 } \
404 } else { \
405 if ((*((T*)p_data)-wheelY)<*((T*)p_max)) { \
406 *((T*)p_data)=*((T*)p_max); \
407 } else { \
408 *((T*)p_data)-=wheelY; \
409 } \
410 } \
411 } else { \
412 if (wheelY>0) { \
413 if ((*((T*)p_data)+wheelY)>*((T*)p_max)) { \
414 *((T*)p_data)=*((T*)p_max); \
415 } else { \
416 *((T*)p_data)+=wheelY; \
417 } \
418 } else { \
419 if ((*((T*)p_data)+wheelY)<*((T*)p_min)) { \
420 *((T*)p_data)=*((T*)p_min); \
421 } else { \
422 *((T*)p_data)+=wheelY; \
423 } \
424 } \
425 } \
426 }
427
428 bool FurnaceGUI::isCtrlWheelModifierHeld() const {
429 switch (settings.ctrlWheelModifier) {
430 case 0:
431 return ImGui::IsKeyDown(ImGuiMod_Ctrl) || ImGui::IsKeyDown(ImGuiMod_Super);
432 case 1:
433 return ImGui::IsKeyDown(ImGuiMod_Ctrl);
434 case 2:
435 return ImGui::IsKeyDown(ImGuiMod_Super);
436 case 3:
437 return ImGui::IsKeyDown(ImGuiMod_Alt);
438 default:
439 return false;
440 }
441 }
442
443 bool FurnaceGUI::CWSliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) {
444 flags^=ImGuiSliderFlags_AlwaysClamp;
445 if (ImGui::SliderScalar(label,data_type,p_data,p_min,p_max,format,flags)) {
446 return true;
447 }
448 if (ImGui::IsItemHovered() && ctrlWheeling) {
449 switch (data_type) {
450 case ImGuiDataType_U8:
451 CW_ADDITION(unsigned char);
452 break;
453 case ImGuiDataType_S8:
454 CW_ADDITION(signed char);
455 break;
456 case ImGuiDataType_U16:
457 CW_ADDITION(unsigned short);
458 break;
459 case ImGuiDataType_S16:
460 CW_ADDITION(short);
461 break;
462 case ImGuiDataType_U32:
463 CW_ADDITION(unsigned int);
464 break;
465 case ImGuiDataType_S32:
466 CW_ADDITION(int);
467 break;
468 case ImGuiDataType_Float:
469 CW_ADDITION(float);
470 break;
471 case ImGuiDataType_Double:
472 CW_ADDITION(double);
473 break;
474 }
475 return true;
476 }
477 return false;
478 }
479
480 bool FurnaceGUI::CWVSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) {
481 flags^=ImGuiSliderFlags_AlwaysClamp;
482 if (ImGui::VSliderScalar(label,size,data_type,p_data,p_min,p_max,format,flags)) {
483 return true;
484 }
485 if (ImGui::IsItemHovered() && ctrlWheeling) {
486 switch (data_type) {
487 case ImGuiDataType_U8:
488 CW_ADDITION(unsigned char);
489 break;
490 case ImGuiDataType_S8:
491 CW_ADDITION(signed char);
492 break;
493 case ImGuiDataType_U16:
494 CW_ADDITION(unsigned short);
495 break;
496 case ImGuiDataType_S16:
497 CW_ADDITION(short);
498 break;
499 case ImGuiDataType_U32:
500 CW_ADDITION(unsigned int);
501 break;
502 case ImGuiDataType_S32:
503 CW_ADDITION(int);
504 break;
505 case ImGuiDataType_Float:
506 CW_ADDITION(float);
507 break;
508 case ImGuiDataType_Double:
509 CW_ADDITION(double);
510 break;
511 }
512 return true;
513 }
514 return false;
515 }
516
517 bool FurnaceGUI::CWSliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) {
518 return CWSliderScalar(label,ImGuiDataType_S32,v,&v_min,&v_max,format,flags);
519 }
520
521 bool FurnaceGUI::CWSliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) {
522 return CWSliderScalar(label,ImGuiDataType_Float,v,&v_min,&v_max,format,flags);
523 }
524
525 bool FurnaceGUI::CWVSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) {
526 return CWVSliderScalar(label,size,ImGuiDataType_S32,v,&v_min,&v_max,format,flags);
527 }
528
529 bool FurnaceGUI::InvCheckbox(const char* label, bool* value) {
530 bool t=!(*value);
531 if (ImGui::Checkbox(label,&t)) {
532 *value=!t;
533 return true;
534 }
535 return false;
536 }
537
538 bool FurnaceGUI::LocalizedComboGetter(void* data, int idx, const char** out_text) {
539 const char* const* items=(const char* const*)data;
540 if (out_text) *out_text=_(items[idx]);
541 return true;
542 }
543
544 void FurnaceGUI::sameLineMaybe(float width) {
545 if (width<0.0f) width=ImGui::GetFrameHeight();
546
547 ImGui::SameLine();
548 if (ImGui::GetContentRegionAvail().x<width) ImGui::NewLine();
549 }
550
551 const char* FurnaceGUI::getSystemName(DivSystem which) {
552 /*
553 if (settings.chipNames) {
554 return e->getSystemChips(which);
555 }
556 */
557 return e->getSystemName(which);
558 }
559
560 void FurnaceGUI::updateScroll(int amount) {
561 float lineHeight=(PAT_FONT_SIZE+2*dpiScale);
562 nextScroll=lineHeight*amount;
563 haveHitBounds=false;
564 }
565
566 void FurnaceGUI::updateScrollRaw(float amount) {
567 nextScroll=amount;
568 haveHitBounds=false;
569 }
570
571 void FurnaceGUI::addScroll(int amount) {
572 float lineHeight=(PAT_FONT_SIZE+2*dpiScale);
573 nextAddScroll=lineHeight*amount;
574 haveHitBounds=false;
575 }
576
577 void FurnaceGUI::addScrollX(int amount) {
578 float lineHeight=(PAT_FONT_SIZE+2*dpiScale);
579 nextAddScrollX=lineHeight*amount;
580 haveHitBounds=false;
581 }
582
583 void FurnaceGUI::setFileName(String name) {
584 #ifdef _WIN32
585 wchar_t ret[4096];
586 WString ws=utf8To16(name.c_str());
587 int index=0;
588 for (wchar_t& i: ws) {
589 ret[index++]=i;
590 if (index>=4095) break;
591 }
592 ret[index]=0;
593 backupLock.lock();
594 if (GetFullPathNameW(ws.c_str(),4095,ret,NULL)==0) {
595 curFileName=name;
596 } else {
597 curFileName=utf16To8(ret);
598 }
599 backupLock.unlock();
600 #else
601 char ret[4096];
602 backupLock.lock();
603 if (realpath(name.c_str(),ret)==NULL) {
604 curFileName=name;
605 } else {
606 curFileName=ret;
607 }
608 backupLock.unlock();
609 #endif
610 updateWindowTitle();
611 pushRecentFile(curFileName);
612 if (settings.alwaysPlayIntro==2) shortIntro=true;
613 }
614
615 void FurnaceGUI::updateWindowTitle() {
616 String title;
617 switch (settings.titleBarInfo) {
618 case 0:
619 title="Furnace";
620 break;
621 case 1:
622 if (e->song.name.empty()) {
623 title="Furnace";
624 } else {
625 title=fmt::sprintf("%s - Furnace",e->song.name);
626 }
627 break;
628 case 2:
629 if (curFileName.empty()) {
630 title="Furnace";
631 } else {
632 String shortName;
633 size_t pos=curFileName.rfind(DIR_SEPARATOR);
634 if (pos==String::npos) {
635 shortName=curFileName;
636 } else {
637 shortName=curFileName.substr(pos+1);
638 }
639 title=fmt::sprintf("%s - Furnace",shortName);
640 }
641 break;
642 case 3:
643 if (curFileName.empty()) {
644 title="Furnace";
645 } else {
646 title=fmt::sprintf("%s - Furnace",curFileName);
647 }
648 break;
649 }
650
651 if (settings.titleBarSys) {
652 if (e->song.systemName!="") {
653 title+=fmt::sprintf(" (%s)",e->song.systemName);
654 }
655 }
656
657 if (sdlWin!=NULL) SDL_SetWindowTitle(sdlWin,title.c_str());
658
659 if (e->song.insLen==1) {
660 unsigned int checker=0x11111111;
661 unsigned int checker1=0;
662 DivInstrument* ins=e->getIns(0);
663 if (ins->name.size()==15 && e->curSubSong->ordersLen==8) {
664 for (int i=0; i<15; i++) {
665 checker^=ins->name[i]<<i;
666 checker1+=ins->name[i];
667 checker=(checker>>1|(((checker)^(checker>>2)^(checker>>3)^(checker>>5))&1)<<31);
668 checker1<<=1;
669 }
670 if (checker==0x5ec4497d && checker1==0x6347ee) nonLatchNibble=true;
671 }
672 }
673 }
674
675 void FurnaceGUI::autoDetectSystemIter(std::vector<FurnaceGUISysDef>& category, bool& isMatch, std::map<DivSystem,int>& defCountMap, std::map<DivSystem,DivConfig>& defConfMap, std::map<DivSystem,int>& sysCountMap, std::map<DivSystem,DivConfig>& sysConfMap) {
676 for (FurnaceGUISysDef& j: category) {
677 if (!j.orig.empty()) {
678 defCountMap.clear();
679 defConfMap.clear();
680 for (FurnaceGUISysDefChip& k: j.orig) {
681 auto it=defCountMap.find(k.sys);
682 if (it==defCountMap.cend()) {
683 defCountMap[k.sys]=1;
684 } else {
685 it->second++;
686 }
687 DivConfig dc;
688 dc.loadFromMemory(k.flags.c_str());
689 defConfMap[k.sys]=dc;
690 }
691 if (defCountMap.size()==sysCountMap.size()) {
692 isMatch=true;
693 /*logV("trying on defCountMap: %s",j.name);
694 for (std::pair<DivSystem,int> k: defCountMap) {
695 logV("- %s: %d",e->getSystemName(k.first),k.second);
696 }*/
697 for (std::pair<DivSystem,int> k: defCountMap) {
698 auto countI=sysCountMap.find(k.first);
699 if (countI==sysCountMap.cend()) {
700 isMatch=false;
701 break;
702 } else if (countI->second!=k.second) {
703 isMatch=false;
704 break;
705 }
706
707 auto confI=sysConfMap.find(k.first);
708 if (confI==sysConfMap.cend()) {
709 isMatch=false;
710 break;
711 }
712 DivConfig& sysDC=confI->second;
713 auto defConfI=defConfMap.find(k.first);
714 if (defConfI==defConfMap.cend()) {
715 isMatch=false;
716 break;
717 }
718 for (std::pair<String,String> l: defConfI->second.configMap()) {
719 if (!sysDC.has(l.first)) {
720 isMatch=false;
721 break;
722 }
723 if (sysDC.getString(l.first,"")!=l.second) {
724 isMatch=false;
725 break;
726 }
727 }
728 if (!isMatch) break;
729 }
730 if (isMatch) {
731 logV("match found!");
732 e->song.systemName=j.name;
733 break;
734 }
735 }
736 }
737 if (!j.subDefs.empty()) autoDetectSystemIter(j.subDefs,isMatch,defCountMap,defConfMap,sysCountMap,sysConfMap);
738 if (isMatch) break;
739 }
740 }
741
742 void FurnaceGUI::autoDetectSystem() {
743 std::map<DivSystem,int> sysCountMap;
744 std::map<DivSystem,DivConfig> sysConfMap;
745 for (int i=0; i<e->song.systemLen; i++) {
746 auto it=sysCountMap.find(e->song.system[i]);
747 if (it==sysCountMap.cend()) {
748 sysCountMap[e->song.system[i]]=1;
749 } else {
750 it->second++;
751 }
752 sysConfMap[e->song.system[i]]=e->song.systemFlags[i];
753 }
754
755 logV("sysCountMap:");
756 for (std::pair<DivSystem,int> k: sysCountMap) {
757 logV("%s: %d",e->getSystemName(k.first),k.second);
758 }
759
760 bool isMatch=false;
761 std::map<DivSystem,int> defCountMap;
762 std::map<DivSystem,DivConfig> defConfMap;
763 for (FurnaceGUISysCategory& i: sysCategories) {
764 autoDetectSystemIter(i.systems,isMatch,defCountMap,defConfMap,sysCountMap,sysConfMap);
765 if (isMatch) break;
766 }
767
768 if (!isMatch) {
769 bool isFirst=true;
770 e->song.systemName="";
771 for (std::pair<DivSystem,int> k: sysCountMap) {
772 if (!isFirst) e->song.systemName+=" + ";
773 if (k.second>1) {
774 e->song.systemName+=fmt::sprintf("%d×",k.second);
775 }
776 e->song.systemName+=e->getSystemName(k.first);
777 isFirst=false;
778 }
779 }
780 }
781
782 void FurnaceGUI::updateROMExportAvail() {
783 memset(romExportAvail,0,sizeof(bool)*DIV_ROM_MAX);
784 romExportExists=false;
785
786 for (int i=0; i<DIV_ROM_MAX; i++) {
787 if (e->isROMExportViable((DivROMExportOptions)i)) {
788 romExportAvail[i]=true;
789 romExportExists=true;
790 }
791 }
792
793 if (!romExportAvail[romTarget]) {
794 // find a new one
795 romTarget=DIV_ROM_ABSTRACT;
796 for (int i=0; i<DIV_ROM_MAX; i++) {
797 const DivROMExportDef* newDef=e->getROMExportDef((DivROMExportOptions)i);
798 if (newDef!=NULL) {
799 if (romExportAvail[i]) {
800 romTarget=(DivROMExportOptions)i;
801 romMultiFile=newDef->multiOutput;
802 romConfig=DivConfig();
803 if (newDef->fileExt==NULL) {
804 romFilterName="";
805 romFilterExt="";
806 } else {
807 romFilterName=newDef->fileType;
808 romFilterExt=newDef->fileExt;
809 }
810 break;
811 }
812 }
813 }
814 }
815 }
816
817 ImVec4 FurnaceGUI::channelColor(int ch) {
818 switch (settings.channelColors) {
819 case 0:
820 return uiColors[GUI_COLOR_CHANNEL_BG];
821 break;
822 case 1:
823 return uiColors[GUI_COLOR_CHANNEL_FM+e->getChannelType(ch)];
824 break;
825 case 2:
826 return uiColors[GUI_COLOR_INSTR_STD+e->getPreferInsType(ch)];
827 break;
828 }
829 // invalid
830 return uiColors[GUI_COLOR_TEXT];
831 }
832
833 ImVec4 FurnaceGUI::channelTextColor(int ch) {
834 switch (settings.channelTextColors) {
835 case 0:
836 return uiColors[GUI_COLOR_CHANNEL_FG];
837 break;
838 case 1:
839 return uiColors[GUI_COLOR_CHANNEL_FM+e->getChannelType(ch)];
840 break;
841 case 2:
842 return uiColors[GUI_COLOR_INSTR_STD+e->getPreferInsType(ch)];
843 break;
844 }
845 // invalid
846 return uiColors[GUI_COLOR_TEXT];
847 }
848
849 const char* defaultLayout="[Window][DockSpaceViewport_11111111]\n\
850 Pos=0,24\n\
851 Size=1280,776\n\
852 Collapsed=0\n\
853 \n\
854 [Window][Debug##Default]\n\
855 Pos=54,43\n\
856 Size=400,400\n\
857 Collapsed=0\n\
858 \n\
859 [Window][Play/Edit Controls]\n\
860 Pos=181,208\n\
861 Size=45,409\n\
862 Collapsed=0\n\
863 \n\
864 [Window][Song Information]\n\
865 Pos=978,24\n\
866 Size=302,179\n\
867 Collapsed=0\n\
868 DockId=0x0000000F,0\n\
869 \n\
870 [Window][Orders]\n\
871 Pos=0,24\n\
872 Size=345,217\n\
873 Collapsed=0\n\
874 DockId=0x00000007,0\n\
875 \n\
876 [Window][Instruments]\n\
877 Pos=653,24\n\
878 Size=323,217\n\
879 Collapsed=0\n\
880 DockId=0x00000006,0\n\
881 \n\
882 [Window][Wavetables]\n\
883 Pos=653,24\n\
884 Size=323,217\n\
885 Collapsed=0\n\
886 DockId=0x00000006,1\n\
887 \n\
888 [Window][Samples]\n\
889 Pos=653,24\n\
890 Size=323,217\n\
891 Collapsed=0\n\
892 DockId=0x00000006,2\n\
893 \n\
894 [Window][Pattern]\n\
895 Pos=0,243\n\
896 Size=939,557\n\
897 Collapsed=0\n\
898 DockId=0x00000017,0\n\
899 \n\
900 [Window][Instrument Editor]\n\
901 Pos=229,126\n\
902 Size=856,652\n\
903 Collapsed=0\n\
904 \n\
905 [Window][Warning]\n\
906 Pos=481,338\n\
907 Size=264,86\n\
908 Collapsed=0\n\
909 \n\
910 [Window][Sample Editor]\n\
911 Pos=47,216\n\
912 Size=1075,525\n\
913 Collapsed=0\n\
914 \n\
915 [Window][About Furnace]\n\
916 Size=1280,755\n\
917 Collapsed=0\n\
918 \n\
919 [Window][Save File##FileDialog]\n\
920 Pos=340,177\n\
921 Size=600,400\n\
922 Collapsed=0\n\
923 \n\
924 [Window][Wavetable Editor]\n\
925 Pos=253,295\n\
926 Size=748,378\n\
927 Collapsed=0\n\
928 \n\
929 [Window][Settings]\n\
930 Pos=655,224\n\
931 Size=1280,941\n\
932 Collapsed=0\n\
933 \n\
934 [Window][Error]\n\
935 Pos=491,342\n\
936 Size=514,71\n\
937 Collapsed=0\n\
938 \n\
939 [Window][Mixer]\n\
940 Pos=429,198\n\
941 Size=453,355\n\
942 Collapsed=0\n\
943 \n\
944 [Window][Oscilloscope]\n\
945 Pos=347,94\n\
946 Size=304,105\n\
947 Collapsed=0\n\
948 DockId=0x0000000E,0\n\
949 \n\
950 [Window][Volume Meter]\n\
951 Pos=1248,243\n\
952 Size=32,557\n\
953 Collapsed=0\n\
954 DockId=0x0000000C,0\n\
955 \n\
956 [Window][Debug]\n\
957 Pos=113,148\n\
958 Size=945,473\n\
959 Collapsed=0\n\
960 \n\
961 [Window][Load Sample##FileDialog]\n\
962 Pos=40,0\n\
963 Size=1200,755\n\
964 Collapsed=0\n\
965 \n\
966 [Window][Open File##FileDialog]\n\
967 Pos=250,143\n\
968 Size=779,469\n\
969 Collapsed=0\n\
970 \n\
971 [Window][Export Audio##FileDialog]\n\
972 Pos=339,177\n\
973 Size=601,400\n\
974 Collapsed=0\n\
975 \n\
976 [Window][Export VGM##FileDialog]\n\
977 Pos=340,177\n\
978 Size=600,400\n\
979 Collapsed=0\n\
980 \n\
981 [Window][Warning##Save FileFileDialogOverWriteDialog]\n\
982 Pos=390,351\n\
983 Size=500,71\n\
984 Collapsed=0\n\
985 \n\
986 [Window][Statistics]\n\
987 Pos=0,581\n\
988 Size=1246,219\n\
989 Collapsed=0\n\
990 DockId=0x00000016,0\n\
991 \n\
992 [Window][Warning##Export VGMFileDialogOverWriteDialog]\n\
993 Pos=390,351\n\
994 Size=500,71\n\
995 Collapsed=0\n\
996 \n\
997 [Window][Compatibility Flags]\n\
998 Pos=388,132\n\
999 Size=580,641\n\
1000 Collapsed=0\n\
1001 \n\
1002 [Window][Song Comments]\n\
1003 Pos=60,60\n\
1004 Size=395,171\n\
1005 Collapsed=0\n\
1006 \n\
1007 [Window][Warning##Export AudioFileDialogOverWriteDialog]\n\
1008 Pos=381,351\n\
1009 Size=500,71\n\
1010 Collapsed=0\n\
1011 \n\
1012 [Window][Select Font##FileDialog]\n\
1013 Pos=340,177\n\
1014 Size=600,400\n\
1015 Collapsed=0\n\
1016 \n\
1017 [Window][Channels]\n\
1018 Pos=60,60\n\
1019 Size=368,449\n\
1020 Collapsed=0\n\
1021 \n\
1022 [Window][Register View]\n\
1023 Pos=829,243\n\
1024 Size=417,557\n\
1025 Collapsed=0\n\
1026 DockId=0x00000014,0\n\
1027 \n\
1028 [Window][New Song]\n\
1029 Pos=267,110\n\
1030 Size=746,534\n\
1031 Collapsed=0\n\
1032 \n\
1033 [Window][Edit Controls]\n\
1034 Pos=347,24\n\
1035 Size=304,68\n\
1036 Collapsed=0\n\
1037 DockId=0x0000000D,0\n\
1038 \n\
1039 [Window][Play Controls]\n\
1040 Pos=347,201\n\
1041 Size=304,40\n\
1042 Collapsed=0\n\
1043 DockId=0x0000000A,0\n\
1044 \n\
1045 [Window][Subsongs]\n\
1046 Pos=978,24\n\
1047 Size=302,217\n\
1048 Collapsed=0\n\
1049 DockId=0x00000010,1\n\
1050 \n\
1051 [Window][Oscilloscope (per-channel)]\n\
1052 Pos=1095,243\n\
1053 Size=151,557\n\
1054 Collapsed=0\n\
1055 DockId=0x00000012,0\n\
1056 \n\
1057 [Window][Piano]\n\
1058 Pos=177,669\n\
1059 Size=922,118\n\
1060 Collapsed=0\n\
1061 \n\
1062 [Window][Log Viewer]\n\
1063 Pos=60,60\n\
1064 Size=541,637\n\
1065 Collapsed=0\n\
1066 \n\
1067 [Window][Pattern Manager]\n\
1068 Pos=60,60\n\
1069 Size=1099,366\n\
1070 Collapsed=0\n\
1071 \n\
1072 [Window][Chip Manager]\n\
1073 Pos=60,60\n\
1074 Size=490,407\n\
1075 Collapsed=0\n\
1076 \n\
1077 [Window][Speed]\n\
1078 Pos=978,24\n\
1079 Size=302,217\n\
1080 Collapsed=0\n\
1081 DockId=0x00000010,2\n\
1082 \n\
1083 [Window][Song Info##Song Information]\n\
1084 Pos=978,24\n\
1085 Size=302,217\n\
1086 Collapsed=0\n\
1087 DockId=0x00000010,0\n\
1088 \n\
1089 [Window][Effect List]\n\
1090 Pos=941,243\n\
1091 Size=305,557\n\
1092 Collapsed=0\n\
1093 DockId=0x00000018,0\n\
1094 \n\
1095 [Window][Intro]\n\
1096 Pos=0,0\n\
1097 Size=2560,1600\n\
1098 Collapsed=0\n\
1099 \n\
1100 [Window][Welcome]\n\
1101 Pos=944,666\n\
1102 Size=672,268\n\
1103 Collapsed=0\n\
1104 \n\
1105 [Window][Grooves]\n\
1106 Pos=416,314\n\
1107 Size=463,250\n\
1108 Collapsed=0\n\
1109 \n\
1110 [Window][Clock]\n\
1111 Pos=60,60\n\
1112 Size=145,184\n\
1113 Collapsed=0\n\
1114 \n\
1115 [Window][Oscilloscope (X-Y)]\n\
1116 Pos=60,60\n\
1117 Size=300,300\n\
1118 Collapsed=0\n\
1119 \n\
1120 [Docking][Data]\n\
1121 DockSpace ID=0x8B93E3BD Window=0xA787BDB4 Pos=0,24 Size=1280,776 Split=Y Selected=0x6C01C512\n\
1122 DockNode ID=0x00000001 Parent=0x8B93E3BD SizeRef=1280,217 Split=X Selected=0xF3094A52\n\
1123 DockNode ID=0x00000003 Parent=0x00000001 SizeRef=976,231 Split=X Selected=0x65CC51DC\n\
1124 DockNode ID=0x00000007 Parent=0x00000003 SizeRef=345,231 HiddenTabBar=1 Selected=0x8F5BFC9A\n\
1125 DockNode ID=0x00000008 Parent=0x00000003 SizeRef=629,231 Split=X Selected=0xD2AD486B\n\
1126 DockNode ID=0x00000005 Parent=0x00000008 SizeRef=304,406 Split=Y Selected=0x6D682373\n\
1127 DockNode ID=0x00000009 Parent=0x00000005 SizeRef=292,175 Split=Y Selected=0x6D682373\n\
1128 DockNode ID=0x0000000D Parent=0x00000009 SizeRef=292,68 HiddenTabBar=1 Selected=0xE57B1A9D\n\
1129 DockNode ID=0x0000000E Parent=0x00000009 SizeRef=292,105 HiddenTabBar=1 Selected=0x6D682373\n\
1130 DockNode ID=0x0000000A Parent=0x00000005 SizeRef=292,40 HiddenTabBar=1 Selected=0x0DE44CFF\n\
1131 DockNode ID=0x00000006 Parent=0x00000008 SizeRef=323,406 Selected=0xB75D68C7\n\
1132 DockNode ID=0x00000004 Parent=0x00000001 SizeRef=302,231 Split=Y Selected=0x60B9D088\n\
1133 DockNode ID=0x0000000F Parent=0x00000004 SizeRef=302,179 Selected=0x60B9D088\n\
1134 DockNode ID=0x00000010 Parent=0x00000004 SizeRef=302,36 Selected=0x82BEE2E5\n\
1135 DockNode ID=0x00000002 Parent=0x8B93E3BD SizeRef=1280,512 Split=X Selected=0x6C01C512\n\
1136 DockNode ID=0x0000000B Parent=0x00000002 SizeRef=1246,503 Split=X Selected=0xB9ADD0D5\n\
1137 DockNode ID=0x00000011 Parent=0x0000000B SizeRef=1093,557 Split=X Selected=0xB9ADD0D5\n\
1138 DockNode ID=0x00000013 Parent=0x00000011 SizeRef=827,557 Split=Y Selected=0xB9ADD0D5\n\
1139 DockNode ID=0x00000015 Parent=0x00000013 SizeRef=1246,336 Split=X Selected=0xB9ADD0D5\n\
1140 DockNode ID=0x00000017 Parent=0x00000015 SizeRef=939,557 CentralNode=1 HiddenTabBar=1 Selected=0xB9ADD0D5\n\
1141 DockNode ID=0x00000018 Parent=0x00000015 SizeRef=305,557 Selected=0xB94874DD\n\
1142 DockNode ID=0x00000016 Parent=0x00000013 SizeRef=1246,219 Selected=0xAD8E88F2\n\
1143 DockNode ID=0x00000014 Parent=0x00000011 SizeRef=417,557 Selected=0x425428FB\n\
1144 DockNode ID=0x00000012 Parent=0x0000000B SizeRef=151,557 HiddenTabBar=1 Selected=0x4C07BC58\n\
1145 DockNode ID=0x0000000C Parent=0x00000002 SizeRef=32,503 HiddenTabBar=1 Selected=0x644DA2C1\n";
1146
1147
1148 void FurnaceGUI::prepareLayout() {
1149 FILE* check;
1150 check=ps_fopen(finalLayoutPath,"r");
1151 if (check!=NULL) {
1152 fclose(check);
1153 return;
1154 }
1155
1156 // copy initial layout
1157 logI("loading default layout.");
1158 check=ps_fopen(finalLayoutPath,"w");
1159 if (check==NULL) {
1160 logW("could not write default layout!");
1161 return;
1162 }
1163
1164 fwrite(defaultLayout,1,strlen(defaultLayout),check);
1165 fclose(check);
1166 }
1167
1168 float FurnaceGUI::calcBPM(const DivGroovePattern& speeds, float hz, int vN, int vD) {
1169 float hl=e->curSubSong->hilightA;
1170 if (hl<=0.0f) hl=4.0f;
1171 float timeBase=e->curSubSong->timeBase+1;
1172 float speedSum=0;
1173 for (int i=0; i<MIN(16,speeds.len); i++) {
1174 speedSum+=speeds.val[i];
1175 }
1176 speedSum/=MAX(1,speeds.len);
1177 if (timeBase<1.0f) timeBase=1.0f;
1178 if (speedSum<1.0f) speedSum=1.0f;
1179 if (vD<1) vD=1;
1180 return (60.0f*hz/(timeBase*hl*speedSum))*(float)vN/(float)vD;
1181 }
1182
1183 void FurnaceGUI::play(int row) {
1184 if (e->getStreamPlayer()) {
1185 e->killStream();
1186 }
1187 memset(chanOscVol,0,DIV_MAX_CHANS*sizeof(float));
1188 for (int i=0; i<DIV_MAX_CHANS; i++) {
1189 chanOscChan[i].pitch=0.0f;
1190 }
1191 memset(chanOscBright,0,DIV_MAX_CHANS*sizeof(float));
1192 e->walkSong(loopOrder,loopRow,loopEnd);
1193 memset(lastIns,-1,sizeof(int)*DIV_MAX_CHANS);
1194 if (wasFollowing) {
1195 followPattern=true;
1196 wasFollowing=false;
1197 }
1198 if (followPattern) makeCursorUndo();
1199 if (!followPattern) e->setOrder(curOrder);
1200 if (row>=0) {
1201 if (!e->playToRow(row)) {
1202 showError(_("the song is over!"));
1203 }
1204 } else {
1205 if (!e->play()) {
1206 showError(_("the song is over!"));
1207 }
1208 }
1209 curNibble=false;
1210 orderNibble=false;
1211 activeNotes.clear();
1212 }
1213
1214 void FurnaceGUI::setOrder(unsigned char order, bool forced) {
1215 curOrder=order;
1216 if (followPattern || forced) {
1217 e->setOrder(order);
1218 }
1219 }
1220
1221 void FurnaceGUI::stop() {
1222 bool wasPlaying=e->isPlaying();
1223 e->walkSong(loopOrder,loopRow,loopEnd);
1224 e->stop();
1225 curNibble=false;
1226 orderNibble=false;
1227 if (followPattern && wasPlaying) {
1228 nextScroll=-1.0f;
1229 nextAddScroll=0.0f;
1230 e->getPlayPos(curOrder, cursor.y);
1231 if (selStart.xCoarse==selEnd.xCoarse && selStart.xFine==selEnd.xFine && selStart.y==selEnd.y && selStart.order==selEnd.order && !selecting) {
1232 selStart=cursor;
1233 selEnd=cursor;
1234 }
1235 updateScroll(cursor.y);
1236 }
1237 if (wasFollowing) {
1238 followPattern = true;
1239 wasFollowing = false;
1240 }
1241 }
1242
1243 void FurnaceGUI::previewNote(int refChan, int note, bool autoNote) {
1244 e->setMidiBaseChan(refChan);
1245 e->synchronized([this,note]() {
1246 if (!e->autoNoteOn(-1,curIns,note)) failedNoteOn=true;
1247 });
1248 }
1249
1250 void FurnaceGUI::stopPreviewNote(SDL_Scancode scancode, bool autoNote) {
1251 auto it=noteKeys.find(scancode);
1252 if (it!=noteKeys.cend()) {
1253 int key=it->second;
1254 int num=12*curOctave+key;
1255 if (num<-60) num=-60; // C-(-5)
1256 if (num>119) num=119; // B-9
1257
1258 if (key==100) return;
1259 if (key==101) return;
1260 if (key==102) return;
1261
1262 e->synchronized([this,num]() {
1263 e->autoNoteOff(-1,num);
1264 failedNoteOn=false;
1265 });
1266 }
1267 }
1268
1269 void FurnaceGUI::noteInput(int num, int key, int vol) {
1270 int ch=cursor.xCoarse;
1271 int ord=curOrder;
1272 int y=cursor.y;
1273 int tick=0;
1274 int speed=0;
1275
1276 if (e->isPlaying() && !e->isStepping() && followPattern) {
1277 e->getPlayPosTick(ord,y,tick,speed);
1278 if (tick<=(speed/2)) { // round
1279 // TODO: detect 0Dxx/0Bxx?
1280 if (++y>=e->curSubSong->patLen) {
1281 y=0;
1282 if (++ord>=e->curSubSong->ordersLen) {
1283 ord=0;
1284 }
1285 }
1286 }
1287 }
1288
1289 logV("chan %d, %d:%d %d/%d",ch,ord,y,tick,speed);
1290
1291 DivPattern* pat=e->curPat[ch].getPattern(e->curOrders->ord[ch][ord],true);
1292 bool removeIns=false;
1293
1294 prepareUndo(GUI_UNDO_PATTERN_EDIT);
1295
1296 if (key==GUI_NOTE_OFF) { // note off
1297 pat->data[y][0]=100;
1298 pat->data[y][1]=0;
1299 removeIns=true;
1300 } else if (key==GUI_NOTE_OFF_RELEASE) { // note off + env release
1301 pat->data[y][0]=101;
1302 pat->data[y][1]=0;
1303 removeIns=true;
1304 } else if (key==GUI_NOTE_RELEASE) { // env release only
1305 pat->data[y][0]=102;
1306 pat->data[y][1]=0;
1307 removeIns=true;
1308 } else {
1309 pat->data[y][0]=num%12;
1310 pat->data[y][1]=num/12;
1311 if (pat->data[y][0]==0) {
1312 pat->data[y][0]=12;
1313 pat->data[y][1]--;
1314 }
1315 pat->data[y][1]=(unsigned char)pat->data[y][1];
1316 if (latchIns==-2) {
1317 if (curIns>=(int)e->song.ins.size()) curIns=-1;
1318 if (curIns>=0) {
1319 pat->data[y][2]=curIns;
1320 }
1321 } else if (latchIns!=-1 && !e->song.ins.empty()) {
1322 pat->data[y][2]=MIN(((int)e->song.ins.size())-1,latchIns);
1323 }
1324 int maxVol=e->getMaxVolumeChan(ch);
1325 if (latchVol!=-1) {
1326 pat->data[y][3]=MIN(maxVol,latchVol);
1327 } else if (vol!=-1) {
1328 pat->data[y][3]=e->mapVelocity(ch,pow((float)vol/127.0f,midiMap.volExp));
1329 }
1330 if (latchEffect!=-1) pat->data[y][4]=latchEffect;
1331 if (latchEffectVal!=-1) pat->data[y][5]=latchEffectVal;
1332 }
1333 if (removeIns) {
1334 if (settings.removeInsOff) {
1335 pat->data[y][2]=-1;
1336 }
1337 if (settings.removeVolOff) {
1338 pat->data[y][3]=-1;
1339 }
1340 }
1341 editAdvance();
1342 makeUndo(GUI_UNDO_PATTERN_EDIT);
1343 curNibble=false;
1344 }
1345
1346 void FurnaceGUI::valueInput(int num, bool direct, int target) {
1347 int ch=cursor.xCoarse;
1348 int ord=curOrder;
1349 int y=cursor.y;
1350
1351 if (e->isPlaying() && !e->isStepping() && followPattern) {
1352 e->getPlayPos(ord,y);
1353 }
1354
1355 DivPattern* pat=e->curPat[ch].getPattern(e->curOrders->ord[ch][ord],true);
1356 prepareUndo(GUI_UNDO_PATTERN_EDIT);
1357 if (target==-1) target=cursor.xFine+1;
1358 if (direct) {
1359 pat->data[y][target]=num&0xff;
1360 } else {
1361 if (pat->data[y][target]==-1) pat->data[y][target]=0;
1362 if (!settings.pushNibble && !curNibble) {
1363 pat->data[y][target]=num;
1364 } else {
1365 pat->data[y][target]=((pat->data[y][target]<<4)|num)&0xff;
1366 }
1367 }
1368 if (cursor.xFine==1) { // instrument
1369 if (pat->data[y][target]>=(int)e->song.ins.size()) {
1370 pat->data[y][target]&=0x0f;
1371 if (pat->data[y][target]>=(int)e->song.ins.size()) {
1372 pat->data[y][target]=(int)e->song.ins.size()-1;
1373 }
1374 }
1375 if (settings.absorbInsInput) {
1376 curIns=pat->data[y][target];
1377 wavePreviewInit=true;
1378 updateFMPreview=true;
1379 }
1380 if (direct) {
1381 curNibble=false;
1382 } else {
1383 if (e->song.ins.size()<16) {
1384 curNibble=false;
1385 editAdvance();
1386 } else {
1387 curNibble=!curNibble;
1388 if (!curNibble) editAdvance();
1389 }
1390 }
1391 makeUndo(GUI_UNDO_PATTERN_EDIT);
1392 } else if (cursor.xFine==2) {
1393 if (curNibble) {
1394 if (pat->data[y][target]>e->getMaxVolumeChan(ch)) pat->data[y][target]=e->getMaxVolumeChan(ch);
1395 } else {
1396 pat->data[y][target]&=15;
1397 }
1398 if (direct) {
1399 curNibble=false;
1400 } else {
1401 if (e->getMaxVolumeChan(ch)<16) {
1402 curNibble=false;
1403 if (pat->data[y][target]>e->getMaxVolumeChan(ch)) pat->data[y][target]=e->getMaxVolumeChan(ch);
1404 editAdvance();
1405 } else {
1406 curNibble=!curNibble;
1407 if (!curNibble) editAdvance();
1408 }
1409 }
1410 makeUndo(GUI_UNDO_PATTERN_EDIT);
1411 } else {
1412 if (direct) {
1413 curNibble=false;
1414 } else {
1415 curNibble=!curNibble;
1416 if (!curNibble) {
1417 if (!settings.effectCursorDir) {
1418 editAdvance();
1419 } else {
1420 if (settings.effectCursorDir==2) {
1421 if (++cursor.xFine>=(3+(e->curPat[ch].effectCols*2))) {
1422 cursor.xFine=3;
1423 }
1424 } else {
1425 if (cursor.xFine&1) {
1426 cursor.xFine++;
1427 } else {
1428 editAdvance();
1429 cursor.xFine--;
1430 }
1431 }
1432 }
1433 }
1434 }
1435 makeUndo(GUI_UNDO_PATTERN_EDIT);
1436 }
1437 }
1438
1439 void FurnaceGUI::orderInput(int num) {
1440 if (orderCursor>=0 && orderCursor<e->getTotalChannelCount()) {
1441 prepareUndo(GUI_UNDO_CHANGE_ORDER);
1442 e->lockSave([this,num]() {
1443 if (!curNibble && !settings.pushNibble) e->curOrders->ord[orderCursor][curOrder]=0;
1444 e->curOrders->ord[orderCursor][curOrder]=((e->curOrders->ord[orderCursor][curOrder]<<4)|num);
1445 });
1446 MARK_MODIFIED;
1447 curNibble=!curNibble;
1448 if (orderEditMode==2 || orderEditMode==3) {
1449 if (!curNibble) {
1450 if (orderEditMode==2) {
1451 orderCursor++;
1452 if (orderCursor>=e->getTotalChannelCount()) orderCursor=0;
1453 } else if (orderEditMode==3) {
1454 if (curOrder<e->curSubSong->ordersLen-1) {
1455 setOrder(curOrder+1);
1456 }
1457 }
1458 }
1459 }
1460 e->walkSong(loopOrder,loopRow,loopEnd);
1461 makeUndo(GUI_UNDO_CHANGE_ORDER);
1462 }
1463 }
1464
1465 #define changeLatch(x) \
1466 if (x<0) x=0; \
1467 if (!latchNibble && !settings.pushNibble) x=0; \
1468 x=(x<<4)|num; \
1469 latchNibble=!latchNibble; \
1470 if (!latchNibble) { \
1471 if (++latchTarget>4) latchTarget=0; \
1472 }
1473
1474 void FurnaceGUI::keyDown(SDL_Event& ev) {
1475 if (introPos<11.0 && !shortIntro) return;
1476 if (aboutOpen) return;
1477 if (cvOpen) return;
1478
1479 int mapped=ev.key.keysym.sym;
1480 if (ev.key.keysym.mod&KMOD_CTRL) {
1481 mapped|=FURKMOD_CTRL;
1482 }
1483 if (ev.key.keysym.mod&KMOD_ALT) {
1484 mapped|=FURKMOD_ALT;
1485 }
1486 if (ev.key.keysym.mod&KMOD_GUI) {
1487 mapped|=FURKMOD_META;
1488 }
1489 if (ev.key.keysym.mod&KMOD_SHIFT) {
1490 mapped|=FURKMOD_SHIFT;
1491 }
1492
1493 if (!ImGuiFileDialog::Instance()->IsOpened()) {
1494 if (bindSetActive) {
1495 if (!ev.key.repeat) {
1496 switch (ev.key.keysym.sym) {
1497 case SDLK_LCTRL: case SDLK_RCTRL:
1498 case SDLK_LALT: case SDLK_RALT:
1499 case SDLK_LGUI: case SDLK_RGUI:
1500 case SDLK_LSHIFT: case SDLK_RSHIFT:
1501 bindSetPending=false;
1502 actionKeys[bindSetTarget][bindSetTargetIdx]=(mapped&(~FURK_MASK))|0xffffff;
1503 break;
1504 default:
1505 actionKeys[bindSetTarget][bindSetTargetIdx]=mapped;
1506
1507 // de-dupe with an n^2 algorithm that will never ever be a problem (...but for real though)
1508 for (size_t i=0; i<actionKeys[bindSetTarget].size(); i++) {
1509 for (size_t j=i+1; j<actionKeys[bindSetTarget].size(); j++) {
1510 if (actionKeys[bindSetTarget][i]==actionKeys[bindSetTarget][j]) {
1511 actionKeys[bindSetTarget].erase(actionKeys[bindSetTarget].begin()+j);
1512 }
1513 }
1514 }
1515
1516 bindSetActive=false;
1517 bindSetPending=false;
1518 bindSetTarget=0;
1519 bindSetTargetIdx=0;
1520 bindSetPrevValue=0;
1521 parseKeybinds();
1522 break;
1523 }
1524 }
1525 return;
1526 }
1527
1528 if (latchTarget) {
1529 if (mapped==SDLK_DELETE || mapped==SDLK_BACKSPACE) {
1530 switch (latchTarget) {
1531 case 1:
1532 latchIns=-1;
1533 break;
1534 case 2:
1535 latchVol=-1;
1536 break;
1537 case 3:
1538 latchEffect=-1;
1539 break;
1540 case 4:
1541 latchEffectVal=-1;
1542 break;
1543 }
1544 } else {
1545 auto it=valueKeys.find(ev.key.keysym.sym);
1546 if (it!=valueKeys.cend()) {
1547 int num=it->second;
1548 switch (latchTarget) {
1549 case 1: // instrument
1550 changeLatch(latchIns);
1551 break;
1552 case 2: // volume
1553 changeLatch(latchVol);
1554 break;
1555 case 3: // effect
1556 changeLatch(latchEffect);
1557 break;
1558 case 4: // effect value
1559 changeLatch(latchEffectVal);
1560 break;
1561 }
1562 }
1563 }
1564 return;
1565 }
1566
1567 if (sampleMapWaitingInput) {
1568 switch (sampleMapColumn) {
1569 case 0: {
1570 if (ev.key.keysym.scancode==SDL_SCANCODE_DELETE) {
1571 alterSampleMap(0,-1);
1572 return;
1573 }
1574 auto it=valueKeys.find(ev.key.keysym.sym);
1575 if (it!=valueKeys.cend()) {
1576 int num=it->second;
1577 if (num<10) {
1578 alterSampleMap(0,num);
1579 return;
1580 }
1581 }
1582 break;
1583 }
1584 case 1: {
1585 if (ev.key.keysym.scancode==SDL_SCANCODE_DELETE) {
1586 alterSampleMap(1,-1);
1587 return;
1588 }
1589 auto it=noteKeys.find(ev.key.keysym.scancode);
1590 if (it!=noteKeys.cend()) {
1591 int key=it->second;
1592 int num=12*curOctave+key;
1593
1594 if (num<-60) num=-60; // C-(-5)
1595 if (num>119) num=119; // B-9
1596
1597 alterSampleMap(1,num);
1598 return;
1599 }
1600 break;
1601 }
1602 case 2: {
1603 if (ev.key.keysym.scancode==SDL_SCANCODE_DELETE) {
1604 alterSampleMap(2,-1);
1605 return;
1606 }
1607 auto it=valueKeys.find(ev.key.keysym.sym);
1608 if (it!=valueKeys.cend()) {
1609 int num=it->second;
1610 if (num<10) {
1611 alterSampleMap(2,num);
1612 return;
1613 }
1614 }
1615 break;
1616 }
1617 case 3: {
1618 if (ev.key.keysym.scancode==SDL_SCANCODE_DELETE) {
1619 alterSampleMap(3,-1);
1620 return;
1621 }
1622 auto it=valueKeys.find(ev.key.keysym.sym);
1623 if (it!=valueKeys.cend()) {
1624 int num=it->second;
1625 if (num<16) {
1626 alterSampleMap(3,num);
1627 return;
1628 }
1629 }
1630 break;
1631 }
1632 }
1633 }
1634
1635 // PER-WINDOW KEYS
1636 switch (curWindow) {
1637 case GUI_WINDOW_PATTERN: {
1638 auto actionI=actionMapPat.find(mapped);
1639 if (actionI!=actionMapPat.cend()) {
1640 int action=actionI->second;
1641 if (action>0) {
1642 doAction(action);
1643 return;
1644 }
1645 }
1646 // pattern input otherwise
1647 if (mapped&(FURKMOD_ALT|FURKMOD_CTRL|FURKMOD_META|FURKMOD_SHIFT)) break;
1648 if (!ev.key.repeat || settings.inputRepeat) {
1649 if (cursor.xFine==0) { // note
1650 auto it=noteKeys.find(ev.key.keysym.scancode);
1651 if (it!=noteKeys.cend()) {
1652 int key=it->second;
1653 int num=12*curOctave+key;
1654
1655 if (num<-60) num=-60; // C-(-5)
1656 if (num>119) num=119; // B-9
1657
1658 if (edit) {
1659 noteInput(num,key);
1660 }
1661 }
1662 } else if (edit) { // value
1663 auto it=valueKeys.find(ev.key.keysym.sym);
1664 if (it!=valueKeys.cend()) {
1665 int num=it->second;
1666 valueInput(num);
1667 }
1668 }
1669 }
1670 break;
1671 }
1672 case GUI_WINDOW_ORDERS: {
1673 auto actionI=actionMapOrders.find(mapped);
1674 if (actionI!=actionMapOrders.cend()) {
1675 int action=actionI->second;
1676 if (action>0) {
1677 doAction(action);
1678 return;
1679 }
1680 }
1681 // order input otherwise
1682 if (mapped&(FURKMOD_ALT|FURKMOD_CTRL|FURKMOD_META|FURKMOD_SHIFT)) break;
1683 if (orderEditMode!=0) {
1684 auto it=valueKeys.find(ev.key.keysym.sym);
1685 if (it!=valueKeys.cend()) {
1686 int num=it->second;
1687 orderInput(num);
1688 }
1689 }
1690 break;
1691 }
1692 case GUI_WINDOW_SAMPLE_EDIT: {
1693 auto actionI=actionMapSample.find(mapped);
1694 if (actionI!=actionMapSample.cend()) {
1695 int action=actionI->second;
1696 if (action>0) {
1697 doAction(action);
1698 return;
1699 }
1700 }
1701 break;
1702 }
1703 case GUI_WINDOW_INS_LIST: {
1704 auto actionI=actionMapInsList.find(mapped);
1705 if (actionI!=actionMapInsList.cend()) {
1706 int action=actionI->second;
1707 if (action>0) {
1708 doAction(action);
1709 return;
1710 }
1711 }
1712 break;
1713 }
1714 case GUI_WINDOW_WAVE_LIST: {
1715 auto actionI=actionMapWaveList.find(mapped);
1716 if (actionI!=actionMapWaveList.cend()) {
1717 int action=actionI->second;
1718 if (action>0) {
1719 doAction(action);
1720 return;
1721 }
1722 }
1723 break;
1724 }
1725 case GUI_WINDOW_SAMPLE_LIST: {
1726 auto actionI=actionMapSampleList.find(mapped);
1727 if (actionI!=actionMapSampleList.cend()) {
1728 int action=actionI->second;
1729 if (action>0) {
1730 doAction(action);
1731 return;
1732 }
1733 }
1734 break;
1735 }
1736 default:
1737 break;
1738 }
1739 }
1740
1741 // GLOBAL KEYS
1742 auto actionI=actionMapGlobal.find(mapped);
1743 if (actionI!=actionMapGlobal.cend()) {
1744 int action=actionI->second;
1745 if (action>0) {
1746 if (ImGuiFileDialog::Instance()->IsOpened()) {
1747 if (action!=GUI_ACTION_OCTAVE_UP && action!=GUI_ACTION_OCTAVE_DOWN) return;
1748 }
1749 doAction(action);
1750 return;
1751 }
1752 }
1753 }
1754
1755 void FurnaceGUI::keyUp(SDL_Event& ev) {
1756 // nothing for now
1757 }
1758
1759 bool dirExists(String s) {
1760 return dirExists(s.c_str());
1761 }
1762
1763 void FurnaceGUI::openFileDialog(FurnaceGUIFileDialogs type) {
1764 bool hasOpened=false;
1765
1766 String shortName;
1767 size_t shortNamePos=curFileName.rfind(DIR_SEPARATOR);
1768 if (shortNamePos!=String::npos && (shortNamePos+1)<curFileName.size()) {
1769 shortName=curFileName.substr(shortNamePos+1);
1770 // remove extension
1771 shortNamePos=shortName.rfind('.');
1772 if (shortNamePos!=String::npos) {
1773 shortName=shortName.substr(0,shortNamePos);
1774 }
1775 }
1776
1777 switch (type) {
1778 case GUI_FILE_OPEN:
1779 if (!dirExists(workingDirSong)) workingDirSong=getHomeDir();
1780 hasOpened=fileDialog->openLoad(
1781 _("Open File"),
1782 {_("compatible files"), "*.fur *.dmf *.mod *.s3m *.xm *.it *.fc13 *.fc14 *.smod *.fc *.ftm *.0cc *.dnm *.eft *.fub *.tfe",
1783 _("all files"), "*"},
1784 workingDirSong,
1785 dpiScale
1786 );
1787 break;
1788 case GUI_FILE_OPEN_BACKUP:
1789 if (!dirExists(backupPath)) {
1790 showError(_("no backups made yet!"));
1791 break;
1792 }
1793 hasOpened=fileDialog->openLoad(
1794 _("Restore Backup"),
1795 {_("Furnace song"), "*.fur"},
1796 backupPath+String(DIR_SEPARATOR_STR),
1797 dpiScale
1798 );
1799 break;
1800 case GUI_FILE_SAVE:
1801 if (!dirExists(workingDirSong)) workingDirSong=getHomeDir();
1802 hasOpened=fileDialog->openSave(
1803 _("Save File"),
1804 {_("Furnace song"), "*.fur"},
1805 workingDirSong,
1806 dpiScale
1807 );
1808 break;
1809 case GUI_FILE_SAVE_DMF:
1810 if (!dirExists(workingDirSong)) workingDirSong=getHomeDir();
1811 hasOpened=fileDialog->openSave(
1812 _("Export DMF"),
1813 {_("DefleMask 1.1.3 module"), "*.dmf"},
1814 workingDirSong,
1815 dpiScale,
1816 (settings.autoFillSave)?shortName:""
1817 );
1818 break;
1819 case GUI_FILE_SAVE_DMF_LEGACY:
1820 if (!dirExists(workingDirSong)) workingDirSong=getHomeDir();
1821 hasOpened=fileDialog->openSave(
1822 _("Export DMF"),
1823 {_("DefleMask 1.0/legacy module"), "*.dmf"},
1824 workingDirSong,
1825 dpiScale,
1826 (settings.autoFillSave)?shortName:""
1827 );
1828 break;
1829 case GUI_FILE_INS_OPEN:
1830 case GUI_FILE_INS_OPEN_REPLACE:
1831 prevIns=-3;
1832 if (prevInsData!=NULL) {
1833 delete prevInsData;
1834 prevInsData=NULL;
1835 }
1836 prevInsData=new DivInstrument;
1837 *prevInsData=*e->getIns(curIns);
1838 if (!dirExists(workingDirIns)) workingDirIns=getHomeDir();
1839 hasOpened=fileDialog->openLoad(
1840 _("Load Instrument"),
1841 {_("all compatible files"), "*.fui *.dmp *.tfi *.vgi *.s3i *.sbi *.opli *.opni *.y12 *.bnk *.ff *.gyb *.opm *.wopl *.wopn",
1842 _("Furnace instrument"), "*.fui",
1843 _("DefleMask preset"), "*.dmp",
1844 _("TFM Music Maker instrument"), "*.tfi",
1845 _("VGM Music Maker instrument"), "*.vgi",
1846 _("Scream Tracker 3 instrument"), "*.s3i",
1847 _("SoundBlaster instrument"), "*.sbi",
1848 _("Wohlstand OPL instrument"), "*.opli",
1849 _("Wohlstand OPN instrument"), "*.opni",
1850 _("Gens KMod patch dump"), "*.y12",
1851 _("BNK file (AdLib)"), "*.bnk",
1852 _("FF preset bank"), "*.ff",
1853 _("2612edit GYB preset bank"), "*.gyb",
1854 _("VOPM preset bank"), "*.opm",
1855 _("Wohlstand WOPL bank"), "*.wopl",
1856 _("Wohlstand WOPN bank"), "*.wopn",
1857 _("all files"), "*"},
1858 workingDirIns,
1859 dpiScale,
1860 [this](const char* path) {
1861 int sampleCountBefore=e->song.sampleLen;
1862 std::vector<DivInstrument*> instruments=e->instrumentFromFile(path,false);
1863 if (!instruments.empty()) {
1864 if (e->song.sampleLen!=sampleCountBefore) {
1865 e->renderSamplesP();
1866 }
1867 if (curFileDialog==GUI_FILE_INS_OPEN_REPLACE) {
1868 if (prevIns==-3) {
1869 prevIns=curIns;
1870 }
1871 if (prevIns>=0 && prevIns<=(int)e->song.ins.size()) {
1872 *e->song.ins[prevIns]=*instruments[0];
1873 }
1874 } else {
1875 e->loadTempIns(instruments[0]);
1876 if (curIns!=-2) {
1877 prevIns=curIns;
1878 }
1879 curIns=-2;
1880 }
1881 }
1882 for (DivInstrument* i: instruments) delete i;
1883 },
1884 (type==GUI_FILE_INS_OPEN)
1885 );
1886 break;
1887 case GUI_FILE_INS_SAVE:
1888 if (!dirExists(workingDirIns)) workingDirIns=getHomeDir();
1889 hasOpened=fileDialog->openSave(
1890 _("Save Instrument"),
1891 {_("Furnace instrument"), "*.fui"},
1892 workingDirIns,
1893 dpiScale,
1894 (settings.autoFillSave)?e->getIns(curIns)->name:""
1895 );
1896 break;
1897 case GUI_FILE_INS_SAVE_DMP:
1898 if (!dirExists(workingDirIns)) workingDirIns=getHomeDir();
1899 hasOpened=fileDialog->openSave(
1900 _("Save Instrument"),
1901 {_("DefleMask preset"), "*.dmp"},
1902 workingDirIns,
1903 dpiScale,
1904 (settings.autoFillSave)?e->getIns(curIns)->name:""
1905 );
1906 break;
1907 case GUI_FILE_INS_SAVE_ALL:
1908 if (!dirExists(workingDirIns)) workingDirIns=getHomeDir();
1909 hasOpened=fileDialog->openSelectDir(
1910 _("Save All Instruments"),
1911 workingDirIns,
1912 dpiScale
1913 );
1914 break;
1915 case GUI_FILE_WAVE_OPEN:
1916 case GUI_FILE_WAVE_OPEN_REPLACE:
1917 if (!dirExists(workingDirWave)) workingDirWave=getHomeDir();
1918 hasOpened=fileDialog->openLoad(
1919 _("Load Wavetable"),
1920 {_("compatible files"), "*.fuw *.dmw",
1921 _("all files"), "*"},
1922 workingDirWave,
1923 dpiScale,
1924 NULL, // TODO
1925 (type==GUI_FILE_WAVE_OPEN)
1926 );
1927 break;
1928 case GUI_FILE_WAVE_SAVE:
1929 if (!dirExists(workingDirWave)) workingDirWave=getHomeDir();
1930 hasOpened=fileDialog->openSave(
1931 _("Save Wavetable"),
1932 {_("Furnace wavetable"), ".fuw"},
1933 workingDirWave,
1934 dpiScale
1935 );
1936 break;
1937 case GUI_FILE_WAVE_SAVE_DMW:
1938 if (!dirExists(workingDirWave)) workingDirWave=getHomeDir();
1939 hasOpened=fileDialog->openSave(
1940 _("Save Wavetable"),
1941 {_("DefleMask wavetable"), ".dmw"},
1942 workingDirWave,
1943 dpiScale
1944 );
1945 break;
1946 case GUI_FILE_WAVE_SAVE_RAW:
1947 if (!dirExists(workingDirWave)) workingDirWave=getHomeDir();
1948 hasOpened=fileDialog->openSave(
1949 _("Save Wavetable"),
1950 {_("raw data"), ".raw"},
1951 workingDirWave,
1952 dpiScale
1953 );
1954 break;
1955 case GUI_FILE_WAVE_SAVE_ALL:
1956 if (!dirExists(workingDirWave)) workingDirWave=getHomeDir();
1957 hasOpened=fileDialog->openSelectDir(
1958 _("Save All Wavetables"),
1959 workingDirWave,
1960 dpiScale
1961 );
1962 break;
1963 case GUI_FILE_SAMPLE_OPEN:
1964 case GUI_FILE_SAMPLE_OPEN_REPLACE:
1965 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
1966 hasOpened=fileDialog->openLoad(
1967 _("Load Sample"),
1968 audioLoadFormats,
1969 workingDirSample,
1970 dpiScale,
1971 NULL, // TODO
1972 (type==GUI_FILE_SAMPLE_OPEN)
1973 );
1974 break;
1975 case GUI_FILE_SAMPLE_OPEN_RAW:
1976 case GUI_FILE_SAMPLE_OPEN_REPLACE_RAW:
1977 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
1978 hasOpened=fileDialog->openLoad(
1979 _("Load Raw Sample"),
1980 {_("all files"), "*"},
1981 workingDirSample,
1982 dpiScale
1983 );
1984 break;
1985 case GUI_FILE_SAMPLE_SAVE:
1986 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
1987 hasOpened=fileDialog->openSave(
1988 _("Save Sample"),
1989 {_("Wave file"), "*.wav"},
1990 workingDirSample,
1991 dpiScale,
1992 (settings.autoFillSave)?e->getSample(curSample)->name:""
1993 );
1994 break;
1995 case GUI_FILE_SAMPLE_SAVE_RAW:
1996 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
1997 hasOpened=fileDialog->openSave(
1998 _("Save Raw Sample"),
1999 {_("all files"), "*"},
2000 workingDirSample,
2001 dpiScale,
2002 (settings.autoFillSave)?e->getSample(curSample)->name:""
2003 );
2004 break;
2005 case GUI_FILE_SAMPLE_SAVE_ALL:
2006 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
2007 hasOpened=fileDialog->openSelectDir(
2008 _("Save All Samples"),
2009 workingDirSample,
2010 dpiScale
2011 );
2012 break;
2013 case GUI_FILE_EXPORT_AUDIO_ONE:
2014 if (!dirExists(workingDirAudioExport)) workingDirAudioExport=getHomeDir();
2015 hasOpened=fileDialog->openSave(
2016 _("Export Audio"),
2017 {_("Wave file"), "*.wav"},
2018 workingDirAudioExport,
2019 dpiScale,
2020 (settings.autoFillSave)?shortName:""
2021 );
2022 break;
2023 case GUI_FILE_EXPORT_AUDIO_PER_SYS:
2024 if (!dirExists(workingDirAudioExport)) workingDirAudioExport=getHomeDir();
2025 hasOpened=fileDialog->openSave(
2026 _("Export Audio"),
2027 {_("Wave file"), "*.wav"},
2028 workingDirAudioExport,
2029 dpiScale,
2030 (settings.autoFillSave)?shortName:""
2031 );
2032 break;
2033 case GUI_FILE_EXPORT_AUDIO_PER_CHANNEL:
2034 if (!dirExists(workingDirAudioExport)) workingDirAudioExport=getHomeDir();
2035 hasOpened=fileDialog->openSave(
2036 _("Export Audio"),
2037 {_("Wave file"), "*.wav"},
2038 workingDirAudioExport,
2039 dpiScale,
2040 (settings.autoFillSave)?shortName:""
2041 );
2042 break;
2043 case GUI_FILE_EXPORT_VGM:
2044 if (!dirExists(workingDirVGMExport)) workingDirVGMExport=getHomeDir();
2045 hasOpened=fileDialog->openSave(
2046 _("Export VGM"),
2047 {_("VGM file"), "*.vgm"},
2048 workingDirVGMExport,
2049 dpiScale,
2050 (settings.autoFillSave)?shortName:""
2051 );
2052 break;
2053 case GUI_FILE_EXPORT_TEXT:
2054 if (!dirExists(workingDirROMExport)) workingDirROMExport=getHomeDir();
2055 hasOpened=fileDialog->openSave(
2056 _("Export Command Stream"),
2057 {_("text file"), "*.txt"},
2058 workingDirROMExport,
2059 dpiScale,
2060 (settings.autoFillSave)?shortName:""
2061 );
2062 break;
2063 case GUI_FILE_EXPORT_CMDSTREAM:
2064 if (!dirExists(workingDirROMExport)) workingDirROMExport=getHomeDir();
2065 hasOpened=fileDialog->openSave(
2066 _("Export Command Stream"),
2067 {_("binary file"), "*.bin"},
2068 workingDirROMExport,
2069 dpiScale,
2070 (settings.autoFillSave)?shortName:""
2071 );
2072 break;
2073 case GUI_FILE_EXPORT_ROM:
2074 if (!dirExists(workingDirROMExport)) workingDirROMExport=getHomeDir();
2075 if (romMultiFile) {
2076 hasOpened=fileDialog->openSelectDir(
2077 _("Export ROM"),
2078 workingDirROMExport,
2079 dpiScale
2080 );
2081 } else {
2082 hasOpened=fileDialog->openSave(
2083 _("Export ROM"),
2084 {romFilterName, "*"+romFilterExt},
2085 workingDirROMExport,
2086 dpiScale,
2087 (settings.autoFillSave)?shortName:""
2088 );
2089 }
2090 break;
2091 case GUI_FILE_LOAD_MAIN_FONT:
2092 if (!dirExists(workingDirFont)) workingDirFont=getHomeDir();
2093 hasOpened=fileDialog->openLoad(
2094 _("Select Font"),
2095 {_("compatible files"), "*.ttf *.otf *.ttc *.dfont *.pcf *.psf"},
2096 workingDirFont,
2097 dpiScale
2098 );
2099 break;
2100 case GUI_FILE_LOAD_HEAD_FONT:
2101 if (!dirExists(workingDirFont)) workingDirFont=getHomeDir();
2102 hasOpened=fileDialog->openLoad(
2103 _("Select Font"),
2104 {_("compatible files"), "*.ttf *.otf *.ttc *.dfont *.pcf *.psf"},
2105 workingDirFont,
2106 dpiScale
2107 );
2108 break;
2109 case GUI_FILE_LOAD_PAT_FONT:
2110 if (!dirExists(workingDirFont)) workingDirFont=getHomeDir();
2111 hasOpened=fileDialog->openLoad(
2112 _("Select Font"),
2113 {_("compatible files"), "*.ttf *.otf *.ttc *.dfont *.pcf *.psf"},
2114 workingDirFont,
2115 dpiScale
2116 );
2117 break;
2118 case GUI_FILE_IMPORT_COLORS:
2119 if (!dirExists(workingDirColors)) workingDirColors=getHomeDir();
2120 hasOpened=fileDialog->openLoad(
2121 _("Select Color File"),
2122 {_("configuration files"), "*.cfgc"},
2123 workingDirColors,
2124 dpiScale
2125 );
2126 break;
2127 case GUI_FILE_IMPORT_KEYBINDS:
2128 if (!dirExists(workingDirKeybinds)) workingDirKeybinds=getHomeDir();
2129 hasOpened=fileDialog->openLoad(
2130 _("Select Keybind File"),
2131 {_("configuration files"), "*.cfgk"},
2132 workingDirKeybinds,
2133 dpiScale
2134 );
2135 break;
2136 case GUI_FILE_IMPORT_LAYOUT:
2137 if (!dirExists(workingDirLayout)) workingDirLayout=getHomeDir();
2138 hasOpened=fileDialog->openLoad(
2139 _("Select Layout File"),
2140 {_(".ini files"), "*.ini"},
2141 workingDirLayout,
2142 dpiScale
2143 );
2144 break;
2145 case GUI_FILE_IMPORT_USER_PRESETS:
2146 case GUI_FILE_IMPORT_USER_PRESETS_REPLACE:
2147 if (!dirExists(workingDirConfig)) workingDirConfig=getHomeDir();
2148 hasOpened=fileDialog->openLoad(
2149 _("Select User Presets File"),
2150 {_("configuration files"), "*.cfgu"},
2151 workingDirConfig,
2152 dpiScale
2153 );
2154 break;
2155 case GUI_FILE_IMPORT_CONFIG:
2156 if (!dirExists(workingDirConfig)) workingDirConfig=getHomeDir();
2157 hasOpened=fileDialog->openLoad(
2158 _("Select Settings File"),
2159 {_("configuration files"), "*.cfg"},
2160 workingDirConfig,
2161 dpiScale
2162 );
2163 break;
2164 case GUI_FILE_EXPORT_COLORS:
2165 if (!dirExists(workingDirColors)) workingDirColors=getHomeDir();
2166 hasOpened=fileDialog->openSave(
2167 _("Export Colors"),
2168 {_("configuration files"), "*.cfgc"},
2169 workingDirColors,
2170 dpiScale
2171 );
2172 break;
2173 case GUI_FILE_EXPORT_KEYBINDS:
2174 if (!dirExists(workingDirKeybinds)) workingDirKeybinds=getHomeDir();
2175 hasOpened=fileDialog->openSave(
2176 _("Export Keybinds"),
2177 {_("configuration files"), "*.cfgk"},
2178 workingDirKeybinds,
2179 dpiScale
2180 );
2181 break;
2182 case GUI_FILE_EXPORT_LAYOUT:
2183 if (!dirExists(workingDirLayout)) workingDirLayout=getHomeDir();
2184 hasOpened=fileDialog->openSave(
2185 _("Export Layout"),
2186 {_(".ini files"), "*.ini"},
2187 workingDirLayout,
2188 dpiScale
2189 );
2190 break;
2191 case GUI_FILE_EXPORT_USER_PRESETS:
2192 if (!dirExists(workingDirConfig)) workingDirConfig=getHomeDir();
2193 hasOpened=fileDialog->openSave(
2194 _("Export User Presets"),
2195 {_("configuration files"), "*.cfgu"},
2196 workingDirConfig,
2197 dpiScale
2198 );
2199 break;
2200 case GUI_FILE_EXPORT_CONFIG:
2201 if (!dirExists(workingDirConfig)) workingDirConfig=getHomeDir();
2202 hasOpened=fileDialog->openSave(
2203 _("Export Settings"),
2204 {_("configuration files"), "*.cfg"},
2205 workingDirConfig,
2206 dpiScale
2207 );
2208 break;
2209 case GUI_FILE_YRW801_ROM_OPEN:
2210 case GUI_FILE_TG100_ROM_OPEN:
2211 case GUI_FILE_MU5_ROM_OPEN:
2212 if (!dirExists(workingDirSample)) workingDirSample=getHomeDir();
2213 hasOpened=fileDialog->openLoad(
2214 _("Load ROM"),
2215 {_("compatible files"), "*.rom *.bin",
2216 _("all files"), "*"},
2217 workingDirROM,
2218 dpiScale
2219 );
2220 break;
2221 case GUI_FILE_CMDSTREAM_OPEN:
2222 if (!dirExists(workingDirROM)) workingDirROM=getHomeDir();
2223 hasOpened=fileDialog->openLoad(
2224 _("Play Command Stream"),
2225 {_("command stream"), "*.bin",
2226 _("all files"), "*"},
2227 workingDirROM,
2228 dpiScale
2229 );
2230 break;
2231 case GUI_FILE_TEST_OPEN:
2232 if (!dirExists(workingDirTest)) workingDirTest=getHomeDir();
2233 hasOpened=fileDialog->openLoad(
2234 _("Open Test"),
2235 {_("compatible files"), "*.fur *.dmf *.mod",
2236 _("another option"), "*.wav *.ttf",
2237 _("all files"), "*"},
2238 workingDirTest,
2239 dpiScale,
2240 [](const char* path) {
2241 if (path!=NULL) {
2242 logI("Callback Result: %s",path);
2243 } else {
2244 logI("Callback Result: NULL");
2245 }
2246 }
2247 );
2248 break;
2249 case GUI_FILE_TEST_OPEN_MULTI:
2250 if (!dirExists(workingDirTest)) workingDirTest=getHomeDir();
2251 hasOpened=fileDialog->openLoad(
2252 _("Open Test (Multi)"),
2253 {_("compatible files"), "*.fur *.dmf *.mod",
2254 _("another option"), "*.wav *.ttf",
2255 _("all files"), "*"},
2256 workingDirTest,
2257 dpiScale,
2258 [](const char* path) {
2259 if (path!=NULL) {
2260 logI("Callback Result: %s",path);
2261 } else {
2262 logI("Callback Result: NULL");
2263 }
2264 },
2265 true
2266 );
2267 break;
2268 case GUI_FILE_TEST_SAVE:
2269 if (!dirExists(workingDirTest)) workingDirTest=getHomeDir();
2270 hasOpened=fileDialog->openSave(
2271 _("Save Test"),
2272 {_("Furnace song"), "*.fur",
2273 _("DefleMask module"), "*.dmf"},
2274 workingDirTest,
2275 dpiScale
2276 );
2277 break;
2278 }
2279 if (hasOpened) curFileDialog=type;
2280 //ImGui::GetIO().ConfigFlags|=ImGuiConfigFlags_NavEnableKeyboard;
2281 }
2282
2283 int FurnaceGUI::save(String path, int dmfVersion) {
2284 SafeWriter* w;
2285 logD("saving file...");
2286 if (dmfVersion) {
2287 if (dmfVersion<24) dmfVersion=24;
2288 w=e->saveDMF(dmfVersion);
2289 } else {
2290 w=e->saveFur(false,settings.newPatternFormat);
2291 }
2292 if (w==NULL) {
2293 lastError=e->getLastError();
2294 logE("couldn't save! %s",lastError);
2295 return 3;
2296 }
2297 logV("opening file for writing...");
2298 FILE* outFile=ps_fopen(path.c_str(),"wb");
2299 if (outFile==NULL) {
2300 lastError=strerror(errno);
2301 logE("couldn't save! %s",lastError);
2302 w->finish();
2303 return 1;
2304 }
2305 if (settings.compress) {
2306 unsigned char zbuf[131072];
2307 int ret;
2308 z_stream zl;
2309 memset(&zl,0,sizeof(z_stream));
2310 ret=deflateInit(&zl,Z_DEFAULT_COMPRESSION);
2311 if (ret!=Z_OK) {
2312 logE("zlib error!");
2313 lastError=_("compression error");
2314 fclose(outFile);
2315 w->finish();
2316 return 2;
2317 }
2318 zl.avail_in=w->size();
2319 zl.next_in=w->getFinalBuf();
2320 while (zl.avail_in>0) {
2321 zl.avail_out=131072;
2322 zl.next_out=zbuf;
2323 if ((ret=deflate(&zl,Z_NO_FLUSH))==Z_STREAM_ERROR) {
2324 logE("zlib stream error!");
2325 lastError=_("zlib stream error");
2326 deflateEnd(&zl);
2327 fclose(outFile);
2328 w->finish();
2329 return 2;
2330 }
2331 size_t amount=131072-zl.avail_out;
2332 if (amount>0) {
2333 if (fwrite(zbuf,1,amount,outFile)!=amount) {
2334 logE("did not write entirely: %s!",strerror(errno));
2335 lastError=strerror(errno);
2336 deflateEnd(&zl);
2337 fclose(outFile);
2338 w->finish();
2339 return 1;
2340 }
2341 }
2342 }
2343 zl.avail_out=131072;
2344 zl.next_out=zbuf;
2345 if ((ret=deflate(&zl,Z_FINISH))==Z_STREAM_ERROR) {
2346 logE("zlib finish stream error!");
2347 lastError=_("zlib finish stream error");
2348 deflateEnd(&zl);
2349 fclose(outFile);
2350 w->finish();
2351 return 2;
2352 }
2353 if (131072-zl.avail_out>0) {
2354 if (fwrite(zbuf,1,131072-zl.avail_out,outFile)!=(131072-zl.avail_out)) {
2355 logE("did not write entirely: %s!",strerror(errno));
2356 lastError=strerror(errno);
2357 deflateEnd(&zl);
2358 fclose(outFile);
2359 w->finish();
2360 return 1;
2361 }
2362 }
2363 deflateEnd(&zl);
2364 } else {
2365 if (fwrite(w->getFinalBuf(),1,w->size(),outFile)!=w->size()) {
2366 logE("did not write entirely: %s!",strerror(errno));
2367 lastError=strerror(errno);
2368 fclose(outFile);
2369 w->finish();
2370 return 1;
2371 }
2372 }
2373 fclose(outFile);
2374 w->finish();
2375 backupLock.lock();
2376 curFileName=path;
2377 backupLock.unlock();
2378 modified=false;
2379 updateWindowTitle();
2380 if (!e->getWarnings().empty()) {
2381 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
2382 }
2383 pushRecentFile(path);
2384 pushRecentSys(path.c_str());
2385 logD("save complete.");
2386 return 0;
2387 }
2388
2389 int FurnaceGUI::load(String path) {
2390 bool wasPlaying=e->isPlaying();
2391 if (!path.empty()) {
2392 logI("loading module...");
2393 FILE* f=ps_fopen(path.c_str(),"rb");
2394 if (f==NULL) {
2395 perror("error");
2396 lastError=strerror(errno);
2397 return 1;
2398 }
2399 if (fseek(f,0,SEEK_END)<0) {
2400 perror("size error");
2401 lastError=fmt::sprintf(_("on seek: %s"),strerror(errno));
2402 fclose(f);
2403 return 1;
2404 }
2405 ssize_t len=ftell(f);
2406 if (len==(SIZE_MAX>>1)) {
2407 perror("could not get file length");
2408 lastError=fmt::sprintf(_("on pre tell: %s"),strerror(errno));
2409 fclose(f);
2410 return 1;
2411 }
2412 if (len<1) {
2413 if (len==0) {
2414 logE("that file is empty!");
2415 lastError=_("file is empty");
2416 } else {
2417 perror("tell error");
2418 lastError=fmt::sprintf(_("on tell: %s"),strerror(errno));
2419 }
2420 fclose(f);
2421 return 1;
2422 }
2423 if (fseek(f,0,SEEK_SET)<0) {
2424 perror("size error");
2425 lastError=fmt::sprintf(_("on get size: %s"),strerror(errno));
2426 fclose(f);
2427 return 1;
2428 }
2429 unsigned char* file=new unsigned char[len];
2430 if (fread(file,1,(size_t)len,f)!=(size_t)len) {
2431 perror("read error");
2432 lastError=fmt::sprintf(_("on read: %s"),strerror(errno));
2433 fclose(f);
2434 delete[] file;
2435 return 1;
2436 }
2437 fclose(f);
2438 if (!e->load(file,(size_t)len,path.c_str())) {
2439 lastError=e->getLastError();
2440 logE("could not open file!");
2441 return 1;
2442 }
2443 }
2444 backupLock.lock();
2445 curFileName=path;
2446 backupLock.unlock();
2447 modified=false;
2448 curNibble=false;
2449 orderNibble=false;
2450 orderCursor=-1;
2451 curOrder=0;
2452 oldRow=0;
2453 samplePos=0;
2454 updateSampleTex=true;
2455 selStart=SelectionPoint();
2456 selEnd=SelectionPoint();
2457 cursor=SelectionPoint();
2458 lastError=_("everything OK");
2459 undoHist.clear();
2460 redoHist.clear();
2461 updateWindowTitle();
2462 updateROMExportAvail();
2463 updateScroll(0);
2464 if (!e->getWarnings().empty()) {
2465 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
2466 }
2467 pushRecentFile(path);
2468 // walk song
2469 e->walkSong(loopOrder,loopRow,loopEnd);
2470 // do not auto-play a backup
2471 if (path.find(backupPath)!=0) {
2472 if (settings.playOnLoad==2 || (settings.playOnLoad==1 && wasPlaying)) {
2473 play();
2474 }
2475 } else {
2476 // warn the user
2477 showWarning(_("you have loaded a backup!\nif you need to, please save it somewhere.\n\nDO NOT RELY ON THE BACKUP SYSTEM FOR AUTO-SAVE!\nFurnace will not save backups of backups."),GUI_WARN_GENERIC);
2478 }
2479
2480 // if this is a PC module import, warn the user on the first import.
2481 if (!tutorial.importedMOD && e->song.version==DIV_VERSION_MOD) {
2482 showWarning(_("you have imported a ProTracker/SoundTracker/PC module!\nkeep the following in mind:\n\n- Furnace is not a replacement for your MOD player\n- import is not perfect. your song may sound different:\n - E6x pattern loop is not supported\n\nhave fun!"),GUI_WARN_IMPORT);
2483 }
2484 if (!tutorial.importedS3M && e->song.version==DIV_VERSION_S3M) {
2485 showWarning(_("you have imported a Scream Tracker 3 module!\nkeep the following in mind:\n\n- Furnace is not a replacement for your S3M player\n- import is not perfect. your song may sound different:\n - OPL instruments may be detuned\n\nhave fun!"),GUI_WARN_IMPORT);
2486 }
2487 if (!tutorial.importedXM && e->song.version==DIV_VERSION_XM) {
2488 showWarning(_("you have imported a FastTracker II module!\nkeep the following in mind:\n\n- Furnace is not a replacement for your XM player\n- import is not perfect. your song may sound different:\n - envelopes have been converted to macros\n - global volume changes are not supported\n\nhave fun!"),GUI_WARN_IMPORT);
2489 }
2490 if (!tutorial.importedIT && e->song.version==DIV_VERSION_IT) {
2491 showWarning(_("you have imported an Impulse Tracker module!\nkeep the following in mind:\n\n- Furnace is not a replacement for your IT player\n- import is not perfect. your song may sound different:\n - envelopes have been converted to macros\n - global volume changes are not supported\n - channel volume changes are not supported\n - New Note Actions (NNA) are not supported\n\nhave fun!"),GUI_WARN_IMPORT);
2492 }
2493 return 0;
2494 }
2495
2496 void FurnaceGUI::openRecentFile(String path) {
2497 if (modified) {
2498 nextFile=path;
2499 showWarning(_("Unsaved changes! Save changes before opening file?"),GUI_WARN_OPEN_DROP);
2500 } else {
2501 if (load(path)>0) {
2502 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
2503 }
2504 }
2505 }
2506
2507 void FurnaceGUI::pushRecentFile(String path) {
2508 if (path.empty()) return;
2509 if (path.find(backupPath)==0) return;
2510 for (int i=0; i<(int)recentFile.size(); i++) {
2511 if (recentFile[i]==path) {
2512 recentFile.erase(i);
2513 i--;
2514 }
2515 }
2516 recentFile.push_front(path);
2517
2518 while (!recentFile.empty() && (int)recentFile.size()>settings.maxRecentFile) {
2519 recentFile.pop_back();
2520 }
2521 }
2522
2523 void FurnaceGUI::pushRecentSys(const char* path) {
2524 #ifdef _WIN32
2525 WString widePath=utf8To16(path);
2526 SHAddToRecentDocs(SHARD_PATHW,widePath.c_str());
2527 #endif
2528 }
2529
2530 void FurnaceGUI::delFirstBackup(String name) {
2531 std::vector<String> listOfFiles;
2532 #ifdef _WIN32
2533 String findPath=backupPath+String(DIR_SEPARATOR_STR)+name+String("*.fur");
2534 WIN32_FIND_DATAW next;
2535 HANDLE backDir=FindFirstFileW(utf8To16(findPath.c_str()).c_str(),&next);
2536 if (backDir!=INVALID_HANDLE_VALUE) {
2537 do {
2538 listOfFiles.push_back(utf16To8(next.cFileName));
2539 } while (FindNextFileW(backDir,&next)!=0);
2540 FindClose(backDir);
2541 }
2542 #else
2543 DIR* backDir=opendir(backupPath.c_str());
2544 if (backDir==NULL) {
2545 logW("could not open backups dir!");
2546 return;
2547 }
2548 while (true) {
2549 struct dirent* next=readdir(backDir);
2550 if (next==NULL) break;
2551 if (strstr(next->d_name,name.c_str())!=next->d_name) continue;
2552 listOfFiles.push_back(String(next->d_name));
2553 }
2554 closedir(backDir);
2555 #endif
2556
2557 std::sort(listOfFiles.begin(),listOfFiles.end(),[](const String& a, const String& b) -> bool {
2558 return strcmp(a.c_str(),b.c_str())<0;
2559 });
2560
2561 int totalDelete=((int)listOfFiles.size())-settings.backupMaxCopies;
2562 for (int i=0; i<totalDelete; i++) {
2563 String toDelete=backupPath+String(DIR_SEPARATOR_STR)+listOfFiles[i];
2564 deleteFile(toDelete.c_str());
2565 }
2566 }
2567
2568 int FurnaceGUI::loadStream(String path) {
2569 if (!path.empty()) {
2570 logI("loading stream...");
2571 FILE* f=ps_fopen(path.c_str(),"rb");
2572 if (f==NULL) {
2573 perror("error");
2574 lastError=strerror(errno);
2575 return 1;
2576 }
2577 if (fseek(f,0,SEEK_END)<0) {
2578 perror("size error");
2579 lastError=fmt::sprintf(_("on seek: %s"),strerror(errno));
2580 fclose(f);
2581 return 1;
2582 }
2583 ssize_t len=ftell(f);
2584 if (len==(SIZE_MAX>>1)) {
2585 perror("could not get file length");
2586 lastError=fmt::sprintf(_("on pre tell: %s"),strerror(errno));
2587 fclose(f);
2588 return 1;
2589 }
2590 if (len<1) {
2591 if (len==0) {
2592 logE("that file is empty!");
2593 lastError=_("file is empty");
2594 } else {
2595 perror("tell error");
2596 lastError=fmt::sprintf(_("on tell: %s"),strerror(errno));
2597 }
2598 fclose(f);
2599 return 1;
2600 }
2601 if (fseek(f,0,SEEK_SET)<0) {
2602 perror("size error");
2603 lastError=fmt::sprintf(_("on get size: %s"),strerror(errno));
2604 fclose(f);
2605 return 1;
2606 }
2607 unsigned char* file=new unsigned char[len];
2608 if (fread(file,1,(size_t)len,f)!=(size_t)len) {
2609 perror("read error");
2610 lastError=fmt::sprintf(_("on read: %s"),strerror(errno));
2611 fclose(f);
2612 delete[] file;
2613 return 1;
2614 }
2615 fclose(f);
2616 if (!e->playStream(file,(size_t)len)) {
2617 lastError=e->getLastError();
2618 logE("could not open file!");
2619 return 1;
2620 }
2621 }
2622 return 0;
2623 }
2624
2625
2626 void FurnaceGUI::exportAudio(String path, DivAudioExportModes mode) {
2627 songOrdersLengths.clear();
2628
2629 int loopOrder=0;
2630 int loopRow=0;
2631 int loopEnd=0;
2632 e->walkSong(loopOrder,loopRow,loopEnd);
2633
2634 e->findSongLength(loopOrder,loopRow,audioExportOptions.fadeOut,songFadeoutSectionLength,songHasSongEndCommand,songOrdersLengths,songLength); // for progress estimation
2635
2636 songLoopedSectionLength=songLength;
2637 for (int i=0; i<loopOrder && i<(int)songOrdersLengths.size(); i++) {
2638 songLoopedSectionLength-=songOrdersLengths[i];
2639 }
2640 songLoopedSectionLength-=loopRow;
2641
2642 e->saveAudio(path.c_str(),audioExportOptions);
2643
2644 totalFiles=0;
2645 e->getTotalAudioFiles(totalFiles);
2646 int totalLoops=0;
2647
2648 lengthOfOneFile=songLength;
2649
2650 if (!songHasSongEndCommand) {
2651 e->getTotalLoops(totalLoops);
2652
2653 lengthOfOneFile+=songLoopedSectionLength*totalLoops;
2654 lengthOfOneFile+=songFadeoutSectionLength; // account for fadeout
2655 }
2656
2657 totalLength=lengthOfOneFile*totalFiles;
2658
2659 curProgress=0.0f;
2660
2661 displayExporting=true;
2662 }
2663
2664 void FurnaceGUI::exportCmdStream(bool target, String path) {
2665 csExportPath=path;
2666 csExportTarget=target;
2667 csExportDone=false;
2668 csExportThread=new std::thread([this]() {
2669 SafeWriter* w=e->saveCommand(&csProgress,csExportOptions);
2670 csExportResult=w;
2671 csExportDone=true;
2672 });
2673 displayExportingCS=true;
2674 }
2675
2676 void FurnaceGUI::editStr(String* which) {
2677 editString=which;
2678 displayEditString=true;
2679 }
2680
2681 void FurnaceGUI::showWarning(String what, FurnaceGUIWarnings type) {
2682 warnString=what;
2683 warnAction=type;
2684 warnQuit=true;
2685 }
2686
2687 void FurnaceGUI::showError(String what) {
2688 errorString=what;
2689 displayError=true;
2690 }
2691
2692 String FurnaceGUI::getLastError() {
2693 return lastError;
2694 }
2695
2696 // what monster did I just create here?
2697 #define B30(tt) (macroDragBit30?((((tt)&0xc0000000)==0x40000000 || ((tt)&0xc0000000)==0x80000000)?0x40000000:0):0)
2698
2699 #define MACRO_DRAG(t) \
2700 if (macroDragSettingBit30) { \
2701 if (macroDragLastX!=x || macroDragLastY!=y) { \
2702 macroDragLastX=x; \
2703 macroDragLastY=y; \
2704 if (macroDragInitialValueSet) { \
2705 if (!macroDragInitialValue) { \
2706 if (t[x]&0x80000000) { \
2707 t[x]&=~0x40000000; \
2708 } else { \
2709 t[x]|=0x40000000; \
2710 } \
2711 } else { \
2712 if (t[x]&0x80000000) { \
2713 t[x]|=0x40000000; \
2714 } else { \
2715 t[x]&=~0x40000000; \
2716 } \
2717 } \
2718 } else { \
2719 macroDragInitialValue=(((t[x])&0xc0000000)==0x40000000 || ((t[x])&0xc0000000)==0x80000000); \
2720 macroDragInitialValueSet=true; \
2721 t[x]^=0x40000000; \
2722 } \
2723 } \
2724 } else if (macroDragBitMode) { \
2725 if (macroDragLastX!=x || macroDragLastY!=y) { \
2726 macroDragLastX=x; \
2727 macroDragLastY=y; \
2728 if (macroDragInitialValueSet) { \
2729 if (macroDragInitialValue) { \
2730 t[x]=(((t[x])&((1<<macroDragMax)-1))&(~(1<<y))); \
2731 } else { \
2732 t[x]=(((t[x])&((1<<macroDragMax)-1))|(1<<y)); \
2733 } \
2734 } else { \
2735 macroDragInitialValue=(((t[x])&((1<<macroDragMax)-1))&(1<<y)); \
2736 macroDragInitialValueSet=true; \
2737 t[x]=(((t[x])&((1<<macroDragMax)-1))^(1<<y)); \
2738 } \
2739 t[x]&=(1<<macroDragMax)-1; \
2740 } \
2741 } else { \
2742 if (macroDragLineMode) { \
2743 if (!macroDragInitialValueSet) { \
2744 macroDragLineInitial=ImVec2(x,y); \
2745 macroDragLineInitialV=ImVec2(dragX,dragY); \
2746 macroDragInitialValueSet=true; \
2747 macroDragMouseMoved=false; \
2748 } else if (!macroDragMouseMoved) { \
2749 if ((pow(dragX-macroDragLineInitialV.x,2.0)+pow(dragY-macroDragLineInitialV.y,2.0))>=16.0f) { \
2750 macroDragMouseMoved=true; \
2751 } \
2752 } \
2753 if (macroDragMouseMoved) { \
2754 if ((int)round(x-macroDragLineInitial.x)==0) { \
2755 t[x]=B30(t[x])^(int)(macroDragLineInitial.y); \
2756 } else { \
2757 if ((int)round(x-macroDragLineInitial.x)<0) { \
2758 for (int i=0; i<=(int)round(macroDragLineInitial.x-x); i++) { \
2759 int index=(int)round(x+i); \
2760 if (index<0) continue; \
2761 t[index]=B30(t[index])^(int)(y+(macroDragLineInitial.y-y)*((float)i/(float)(macroDragLineInitial.x-x))); \
2762 } \
2763 } else { \
2764 for (int i=0; i<=(int)round(x-macroDragLineInitial.x); i++) { \
2765 int index=(int)round(i+macroDragLineInitial.x); \
2766 if (index<0) continue; \
2767 t[index]=B30(t[index])^(int)(macroDragLineInitial.y+(y-macroDragLineInitial.y)*((float)i/(x-macroDragLineInitial.x))); \
2768 } \
2769 } \
2770 } \
2771 } \
2772 } else { \
2773 t[x]=B30(t[x])^(y); \
2774 } \
2775 }
2776
2777 void FurnaceGUI::processDrags(int dragX, int dragY) {
2778 if (macroDragActive) {
2779 if (macroDragLen>0) {
2780 int x=((dragX-macroDragStart.x)*macroDragLen/MAX(1,macroDragAreaSize.x));
2781 if (x<0) x=0;
2782 if (x>=macroDragLen) x=macroDragLen-1;
2783 x+=macroDragScroll;
2784 int y;
2785 if (macroDragBitMode) {
2786 y=(int)(macroDragMax-((dragY-macroDragStart.y)*(double(macroDragMax-macroDragMin)/(double)MAX(1,macroDragAreaSize.y))));
2787 } else {
2788 y=round(macroDragMax-((dragY-macroDragStart.y)*(double(macroDragMax-macroDragMin)/(double)MAX(1,macroDragAreaSize.y))));
2789 }
2790 if (y>macroDragMax) y=macroDragMax;
2791 if (y<macroDragMin) y=macroDragMin;
2792 if (macroDragChar) {
2793 MACRO_DRAG(macroDragCTarget);
2794 } else {
2795 MACRO_DRAG(macroDragTarget);
2796 }
2797 }
2798 }
2799 if (macroLoopDragActive) {
2800 if (macroLoopDragLen>0) {
2801 int x=(dragX-macroLoopDragStart.x)*macroLoopDragLen/MAX(1,macroLoopDragAreaSize.x);
2802 if (x<0) x=0;
2803 if (x>=macroLoopDragLen) {
2804 x=-1;
2805 } else {
2806 x+=macroDragScroll;
2807 }
2808 *macroLoopDragTarget=x;
2809 }
2810 }
2811 if (waveDragActive) {
2812 if (waveDragLen>0) {
2813 int x=(dragX-waveDragStart.x)*waveDragLen/MAX(1,waveDragAreaSize.x);
2814 if (x<0) x=0;
2815 if (x>=waveDragLen) x=waveDragLen-1;
2816 int y=(waveDragMax+1)-((dragY-waveDragStart.y)*(double((waveDragMax+1)-waveDragMin)/(double)MAX(1,waveDragAreaSize.y)));
2817 if (y>waveDragMax) y=waveDragMax;
2818 if (y<waveDragMin) y=waveDragMin;
2819 waveDragTarget[x]=y;
2820 notifyWaveChange=true;
2821 MARK_MODIFIED;
2822 }
2823 }
2824 if (sampleDragActive) {
2825 int x=samplePos+floor(double(dragX-sampleDragStart.x)*sampleZoom);
2826 int x1=samplePos+floor(double(dragX-sampleDragStart.x+1)*sampleZoom);
2827 if (x<0) x=0;
2828 if (sampleDragMode) {
2829 if (x>=(int)sampleDragLen) x=sampleDragLen-1;
2830 } else {
2831 if (x>(int)sampleDragLen) x=sampleDragLen;
2832 }
2833 if (x1<0) x1=0;
2834 if (x1>=(int)sampleDragLen) x1=sampleDragLen-1;
2835 double y=0.5-double(dragY-sampleDragStart.y)/sampleDragAreaSize.y;
2836 if (sampleDragMode) { // draw
2837 if (sampleDragTarget) {
2838 if (sampleDrag16) {
2839 int val=y*65536;
2840 if (val<-32768) val=-32768;
2841 if (val>32767) val=32767;
2842 for (int i=x; i<=x1; i++) ((short*)sampleDragTarget)[i]=val;
2843 } else {
2844 int val=y*256;
2845 if (val<-128) val=-128;
2846 if (val>127) val=127;
2847 for (int i=x; i<=x1; i++) ((signed char*)sampleDragTarget)[i]=val;
2848 }
2849 updateSampleTex=true;
2850 }
2851 } else { // select
2852 if (sampleSelStart<0) {
2853 sampleSelStart=x;
2854 }
2855 sampleSelEnd=x;
2856 }
2857 }
2858 if (orderScrollLocked) {
2859 if (fabs(orderScrollRealOrigin.x-dragX)>2.0f*dpiScale || fabs(orderScrollRealOrigin.y-dragY)>2.0f*dpiScale) orderScrollTolerance=false;
2860 orderScroll=(orderScrollSlideOrigin-dragX)/(40.0*dpiScale);
2861 if (orderScroll<0.0f) orderScroll=0.0f;
2862 if (orderScroll>(float)e->curSubSong->ordersLen-1) orderScroll=e->curSubSong->ordersLen-1;
2863 }
2864 }
2865
2866 #define checkExtension(x) \
2867 String lowerCase=fileName; \
2868 for (char& i: lowerCase) { \
2869 if (i>='A' && i<='Z') i+='a'-'A'; \
2870 } \
2871 if (lowerCase.size()<strlen(x) || lowerCase.rfind(x)!=lowerCase.size()-strlen(x)) { \
2872 fileName+=x; \
2873 }
2874
2875 #define drawOpMask(m) \
2876 ImGui::PushFont(patFont); \
2877 ImGui::PushID("om_" #m); \
2878 if (ImGui::BeginTable("opMaskTable",5,ImGuiTableFlags_Borders|ImGuiTableFlags_SizingFixedFit|ImGuiTableFlags_NoHostExtendX)) { \
2879 ImGui::TableNextRow(); \
2880 ImGui::TableNextColumn(); \
2881 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_ACTIVE]); \
2882 if (ImGui::Selectable(m.note?"C-4##opMaskNote":"---##opMaskNote",m.note,ImGuiSelectableFlags_DontClosePopups)) { \
2883 m.note=!m.note; \
2884 } \
2885 ImGui::PopStyleColor(); \
2886 ImGui::TableNextColumn(); \
2887 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS]); \
2888 if (ImGui::Selectable(m.ins?"01##opMaskIns":"--##opMaskIns",m.ins,ImGuiSelectableFlags_DontClosePopups)) { \
2889 m.ins=!m.ins; \
2890 } \
2891 ImGui::PopStyleColor(); \
2892 ImGui::TableNextColumn(); \
2893 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_VOLUME_MAX]); \
2894 if (ImGui::Selectable(m.vol?"7F##opMaskVol":"--##opMaskVol",m.vol,ImGuiSelectableFlags_DontClosePopups)) { \
2895 m.vol=!m.vol; \
2896 } \
2897 ImGui::PopStyleColor(); \
2898 ImGui::TableNextColumn(); \
2899 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_PITCH]); \
2900 if (ImGui::Selectable(m.effect?"04##opMaskEffect":"--##opMaskEffect",m.effect,ImGuiSelectableFlags_DontClosePopups)) { \
2901 m.effect=!m.effect; \
2902 } \
2903 ImGui::TableNextColumn(); \
2904 if (ImGui::Selectable(m.effectVal?"72##opMaskEffectVal":"--##opMaskEffectVal",m.effectVal,ImGuiSelectableFlags_DontClosePopups)) { \
2905 m.effectVal=!m.effectVal; \
2906 } \
2907 ImGui::PopStyleColor(); \
2908 ImGui::EndTable(); \
2909 } \
2910 ImGui::PopID(); \
2911 ImGui::PopFont();
2912
2913 void FurnaceGUI::editOptions(bool topMenu) {
2914 char id[4096];
2915 editOptsVisible=true;
2916
2917 if (ImGui::MenuItem(_("cut"),BIND_FOR(GUI_ACTION_PAT_CUT))) doCopy(true,true,selStart,selEnd);
2918 if (ImGui::MenuItem(_("copy"),BIND_FOR(GUI_ACTION_PAT_COPY))) doCopy(false,true,selStart,selEnd);
2919 if (ImGui::MenuItem(_("paste"),BIND_FOR(GUI_ACTION_PAT_PASTE))) doPaste();
2920 if (ImGui::BeginMenu(_("paste special..."))) {
2921 if (ImGui::MenuItem(_("paste mix"),BIND_FOR(GUI_ACTION_PAT_PASTE_MIX))) doPaste(GUI_PASTE_MODE_MIX_FG);
2922 if (ImGui::MenuItem(_("paste mix (background)"),BIND_FOR(GUI_ACTION_PAT_PASTE_MIX_BG))) doPaste(GUI_PASTE_MODE_MIX_BG);
2923 if (ImGui::BeginMenu(_("paste with ins (foreground)"))) {
2924 if (e->song.ins.empty()) {
2925 ImGui::Text(_("no instruments available"));
2926 }
2927 for (size_t i=0; i<e->song.ins.size(); i++) {
2928 snprintf(id,4095,"%.2X: %s",(int)i,e->song.ins[i]->name.c_str());
2929 if (ImGui::MenuItem(id)) {
2930 doPaste(GUI_PASTE_MODE_INS_FG,i);
2931 }
2932 }
2933 ImGui::EndMenu();
2934 }
2935 if (ImGui::BeginMenu(_("paste with ins (background)"))) {
2936 if (e->song.ins.empty()) {
2937 ImGui::Text(_("no instruments available"));
2938 }
2939 for (size_t i=0; i<e->song.ins.size(); i++) {
2940 snprintf(id,4095,"%.2X: %s",(int)i,e->song.ins[i]->name.c_str());
2941 if (ImGui::MenuItem(id)) {
2942 doPaste(GUI_PASTE_MODE_INS_BG,i);
2943 }
2944 }
2945 ImGui::EndMenu();
2946 }
2947 if (ImGui::MenuItem(_("paste flood"),BIND_FOR(GUI_ACTION_PAT_PASTE_FLOOD))) doPaste(GUI_PASTE_MODE_FLOOD);
2948 if (ImGui::MenuItem(_("paste overflow"),BIND_FOR(GUI_ACTION_PAT_PASTE_OVERFLOW))) doPaste(GUI_PASTE_MODE_OVERFLOW);
2949 ImGui::EndMenu();
2950 }
2951 if (ImGui::MenuItem(_("delete"),BIND_FOR(GUI_ACTION_PAT_DELETE))) doDelete();
2952 if (topMenu) {
2953 if (ImGui::MenuItem(_("select all"),BIND_FOR(GUI_ACTION_PAT_SELECT_ALL))) doSelectAll();
2954 }
2955 ImGui::Separator();
2956
2957 if (ImGui::BeginMenu(_("operation mask..."))) {
2958 drawOpMask(opMaskDelete);
2959 ImGui::SameLine();
2960 ImGui::Text(_("delete"));
2961
2962 drawOpMask(opMaskPullDelete);
2963 ImGui::SameLine();
2964 ImGui::Text(_("pull delete"));
2965
2966 drawOpMask(opMaskInsert);
2967 ImGui::SameLine();
2968 ImGui::Text(_("insert"));
2969
2970 drawOpMask(opMaskPaste);
2971 ImGui::SameLine();
2972 ImGui::Text(_("paste"));
2973
2974 drawOpMask(opMaskTransposeNote);
2975 ImGui::SameLine();
2976 ImGui::Text(_("transpose (note)"));
2977
2978 drawOpMask(opMaskTransposeValue);
2979 ImGui::SameLine();
2980 ImGui::Text(_("transpose (value)"));
2981
2982 drawOpMask(opMaskInterpolate);
2983 ImGui::SameLine();
2984 ImGui::Text(_("interpolate"));
2985
2986 drawOpMask(opMaskFade);
2987 ImGui::SameLine();
2988 ImGui::Text(_("fade"));
2989
2990 drawOpMask(opMaskInvertVal);
2991 ImGui::SameLine();
2992 ImGui::Text(_("invert values"));
2993
2994 drawOpMask(opMaskScale);
2995 ImGui::SameLine();
2996 ImGui::Text(_("scale"));
2997
2998 drawOpMask(opMaskRandomize);
2999 ImGui::SameLine();
3000 ImGui::Text(_("randomize"));
3001
3002 drawOpMask(opMaskFlip);
3003 ImGui::SameLine();
3004 ImGui::Text(_("flip"));
3005
3006 drawOpMask(opMaskCollapseExpand);
3007 ImGui::SameLine();
3008 ImGui::Text(_("collapse/expand"));
3009
3010 ImGui::EndMenu();
3011 }
3012
3013 ImGui::Text(_("input latch"));
3014 ImGui::PushFont(patFont);
3015 if (ImGui::BeginTable("inputLatchTable",5,ImGuiTableFlags_Borders|ImGuiTableFlags_SizingFixedFit|ImGuiTableFlags_NoHostExtendX)) {
3016 static char id[64];
3017 ImGui::TableNextRow();
3018 ImGui::TableNextColumn();
3019 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_ACTIVE]);
3020 ImGui::Text("C-4");
3021 ImGui::PopStyleColor();
3022 ImGui::TableNextColumn();
3023 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS]);
3024 if (latchIns==-2) {
3025 strcpy(id,"&&##LatchIns");
3026 } else if (latchIns==-1) {
3027 strcpy(id,"..##LatchIns");
3028 } else {
3029 snprintf(id,63,"%.2X##LatchIns",latchIns&0xff);
3030 }
3031 if (ImGui::Selectable(id,latchTarget==1,ImGuiSelectableFlags_DontClosePopups)) {
3032 latchTarget=1;
3033 latchNibble=false;
3034 }
3035 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
3036 latchIns=-2;
3037 }
3038 if (ImGui::IsItemHovered()) {
3039 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_TEXT]);
3040 ImGui::SetTooltip(_("&&: selected instrument\n..: no instrument"));
3041 ImGui::PopStyleColor();
3042 }
3043 ImGui::PopStyleColor();
3044 ImGui::TableNextColumn();
3045 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_VOLUME_MAX]);
3046 if (latchVol==-1) {
3047 strcpy(id,"..##LatchVol");
3048 } else {
3049 snprintf(id,63,"%.2X##LatchVol",latchVol&0xff);
3050 }
3051 if (ImGui::Selectable(id,latchTarget==2,ImGuiSelectableFlags_DontClosePopups)) {
3052 latchTarget=2;
3053 latchNibble=false;
3054 }
3055 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
3056 latchVol=-1;
3057 }
3058 ImGui::PopStyleColor();
3059 ImGui::TableNextColumn();
3060 if (latchEffect==-1) {
3061 strcpy(id,"..##LatchFX");
3062 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INACTIVE]);
3063 } else {
3064 const unsigned char data=latchEffect;
3065 snprintf(id,63,"%.2X##LatchFX",data);
3066 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[fxColors[data]]);
3067 }
3068
3069 if (ImGui::Selectable(id,latchTarget==3,ImGuiSelectableFlags_DontClosePopups)) {
3070 latchTarget=3;
3071 latchNibble=false;
3072 }
3073 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
3074 latchEffect=-1;
3075 }
3076 ImGui::TableNextColumn();
3077 if (latchEffectVal==-1) {
3078 strcpy(id,"..##LatchFXV");
3079 } else {
3080 snprintf(id,63,"%.2X##LatchFXV",latchEffectVal&0xff);
3081 }
3082 if (ImGui::Selectable(id,latchTarget==4,ImGuiSelectableFlags_DontClosePopups)) {
3083 latchTarget=4;
3084 latchNibble=false;
3085 }
3086 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
3087 latchEffectVal=-1;
3088 }
3089 ImGui::PopStyleColor();
3090 ImGui::EndTable();
3091 }
3092 ImGui::PopFont();
3093 ImGui::SameLine();
3094 if (ImGui::Button(_("Set"))) {
3095 DivPattern* pat=e->curPat[cursor.xCoarse].getPattern(e->curOrders->ord[cursor.xCoarse][curOrder],true);
3096 latchIns=pat->data[cursor.y][2];
3097 latchVol=pat->data[cursor.y][3];
3098 latchEffect=pat->data[cursor.y][4];
3099 latchEffectVal=pat->data[cursor.y][5];
3100 latchTarget=0;
3101 latchNibble=false;
3102 }
3103 ImGui::SameLine();
3104 if (ImGui::Button(_("Reset"))) {
3105 latchIns=-2;
3106 latchVol=-1;
3107 latchEffect=-1;
3108 latchEffectVal=-1;
3109 latchTarget=0;
3110 latchNibble=false;
3111 }
3112 ImGui::Separator();
3113
3114 if (ImGui::MenuItem(_("note up"),BIND_FOR(GUI_ACTION_PAT_NOTE_UP))) doTranspose(1,opMaskTransposeNote);
3115 if (ImGui::MenuItem(_("note down"),BIND_FOR(GUI_ACTION_PAT_NOTE_DOWN))) doTranspose(-1,opMaskTransposeNote);
3116 if (ImGui::MenuItem(_("octave up"),BIND_FOR(GUI_ACTION_PAT_OCTAVE_UP))) doTranspose(12,opMaskTransposeNote);
3117 if (ImGui::MenuItem(_("octave down"),BIND_FOR(GUI_ACTION_PAT_OCTAVE_DOWN))) doTranspose(-12,opMaskTransposeNote);
3118 ImGui::Separator();
3119 if (ImGui::MenuItem(_("values up"),BIND_FOR(GUI_ACTION_PAT_VALUE_UP))) doTranspose(1,opMaskTransposeValue);
3120 if (ImGui::MenuItem(_("values down"),BIND_FOR(GUI_ACTION_PAT_VALUE_DOWN))) doTranspose(-1,opMaskTransposeValue);
3121 if (ImGui::MenuItem(_("values up (+16)"),BIND_FOR(GUI_ACTION_PAT_VALUE_UP_COARSE))) doTranspose(16,opMaskTransposeValue);
3122 if (ImGui::MenuItem(_("values down (-16)"),BIND_FOR(GUI_ACTION_PAT_VALUE_DOWN_COARSE))) doTranspose(-16,opMaskTransposeValue);
3123 ImGui::Separator();
3124 ImGui::AlignTextToFramePadding();
3125 ImGui::Text(_("transpose"));
3126 ImGui::SameLine();
3127 ImGui::SetNextItemWidth(120.0f*dpiScale);
3128 if (ImGui::InputInt("##TransposeAmount",&transposeAmount,1,12)) {
3129 if (transposeAmount<-96) transposeAmount=-96;
3130 if (transposeAmount>96) transposeAmount=96;
3131 }
3132 ImGui::SameLine();
3133 if (ImGui::Button(_("Notes"))) {
3134 doTranspose(transposeAmount,opMaskTransposeNote);
3135 ImGui::CloseCurrentPopup();
3136 }
3137 ImGui::SameLine();
3138 if (ImGui::Button(_("Values"))) {
3139 doTranspose(transposeAmount,opMaskTransposeValue);
3140 ImGui::CloseCurrentPopup();
3141 }
3142
3143 ImGui::Separator();
3144 if (ImGui::MenuItem(_("interpolate"),BIND_FOR(GUI_ACTION_PAT_INTERPOLATE))) doInterpolate();
3145 if (ImGui::BeginMenu(_("change instrument..."))) {
3146 if (e->song.ins.empty()) {
3147 ImGui::Text(_("no instruments available"));
3148 }
3149 for (size_t i=0; i<e->song.ins.size(); i++) {
3150 snprintf(id,4095,"%.2X: %s",(int)i,e->song.ins[i]->name.c_str());
3151 if (ImGui::MenuItem(id)) {
3152 doChangeIns(i);
3153 }
3154 }
3155 ImGui::EndMenu();
3156 }
3157
3158 if (ImGui::BeginMenu(_("gradient/fade..."))) {
3159 if (ImGui::InputInt(_("Start"),&fadeMin,1,16)) {
3160 if (fadeMin<0) fadeMin=0;
3161 if (fadeMode) {
3162 if (fadeMin>15) fadeMin=15;
3163 } else {
3164 if (fadeMin>255) fadeMin=255;
3165 }
3166 }
3167 if (ImGui::InputInt(_("End"),&fadeMax,1,16)) {
3168 if (fadeMax<0) fadeMax=0;
3169 if (fadeMode) {
3170 if (fadeMax>15) fadeMax=15;
3171 } else {
3172 if (fadeMax>255) fadeMax=255;
3173 }
3174 }
3175 if (ImGui::Checkbox(_("Nibble mode"),&fadeMode)) {
3176 if (fadeMode) {
3177 if (fadeMin>15) fadeMin=15;
3178 if (fadeMax>15) fadeMax=15;
3179 } else {
3180 if (fadeMin>255) fadeMin=255;
3181 if (fadeMax>255) fadeMax=255;
3182 }
3183 }
3184 if (ImGui::Button(_("Go ahead"))) {
3185 doFade(fadeMin,fadeMax,fadeMode);
3186 ImGui::CloseCurrentPopup();
3187 }
3188 ImGui::EndMenu();
3189 }
3190 if (ImGui::BeginMenu(_("scale..."))) {
3191 if (ImGui::InputFloat("##ScaleMax",&scaleMax,1,10,"%.1f%%")) {
3192 if (scaleMax<0.0f) scaleMax=0.0f;
3193 if (scaleMax>25600.0f) scaleMax=25600.0f;
3194 }
3195 if (ImGui::Button(_("Scale"))) {
3196 doScale(scaleMax);
3197 ImGui::CloseCurrentPopup();
3198 }
3199 ImGui::EndMenu();
3200 }
3201 if (ImGui::BeginMenu(_("randomize..."))) {
3202 if (ImGui::InputInt(_("Minimum"),&randomizeMin,1,16)) {
3203 if (randomizeMin<0) randomizeMin=0;
3204 if (randomMode) {
3205 if (randomizeMin>15) randomizeMin=15;
3206 } else {
3207 if (randomizeMin>255) randomizeMin=255;
3208 }
3209 if (randomizeMin>randomizeMax) randomizeMin=randomizeMax;
3210 }
3211 if (ImGui::InputInt(_("Maximum"),&randomizeMax,1,16)) {
3212 if (randomizeMax<0) randomizeMax=0;
3213 if (randomizeMax<randomizeMin) randomizeMax=randomizeMin;
3214 if (randomMode) {
3215 if (randomizeMax>15) randomizeMax=15;
3216 } else {
3217 if (randomizeMax>255) randomizeMax=255;
3218 }
3219 }
3220 if (ImGui::Checkbox(_("Nibble mode"),&randomMode)) {
3221 if (randomMode) {
3222 if (randomizeMin>15) randomizeMin=15;
3223 if (randomizeMax>15) randomizeMax=15;
3224 } else {
3225 if (randomizeMin>255) randomizeMin=255;
3226 if (randomizeMax>255) randomizeMax=255;
3227 }
3228 }
3229 if (selStart.xFine>2 || selEnd.xFine>2 || selStart.xCoarse!=selEnd.xCoarse) {
3230 ImGui::Checkbox(_("Set effect"),&randomizeEffect);
3231 if (randomizeEffect) {
3232 if (ImGui::InputScalar(_("Effect"),ImGuiDataType_S32,&randomizeEffectVal,&_ONE,&_SIXTEEN,"%.2X",ImGuiInputTextFlags_CharsHexadecimal)) {
3233 if (randomizeEffectVal<0) randomizeEffectVal=0;
3234 if (randomizeEffectVal>255) randomizeEffectVal=255;
3235 }
3236 }
3237 }
3238 if (ImGui::Button(_("Randomize"))) {
3239 doRandomize(randomizeMin,randomizeMax,randomMode,randomizeEffect,randomizeEffectVal);
3240 ImGui::CloseCurrentPopup();
3241 }
3242 ImGui::EndMenu();
3243 }
3244 if (ImGui::MenuItem(_("invert values"),BIND_FOR(GUI_ACTION_PAT_INVERT_VALUES))) doInvertValues();
3245
3246 ImGui::Separator();
3247
3248 if (ImGui::MenuItem(_("flip selection"),BIND_FOR(GUI_ACTION_PAT_FLIP_SELECTION))) doFlip();
3249
3250 ImGui::SetNextItemWidth(120.0f*dpiScale);
3251 if (ImGui::InputInt(_("collapse/expand amount##CollapseAmount"),&collapseAmount,1,4)) {
3252 if (collapseAmount<2) collapseAmount=2;
3253 if (collapseAmount>256) collapseAmount=256;
3254 }
3255 if (ImGui::MenuItem(_("collapse"),BIND_FOR(GUI_ACTION_PAT_COLLAPSE_ROWS))) doCollapse(collapseAmount,selStart,selEnd);
3256 if (ImGui::MenuItem(_("expand"),BIND_FOR(GUI_ACTION_PAT_EXPAND_ROWS))) doExpand(collapseAmount,selStart,selEnd);
3257
3258 if (topMenu) {
3259 ImGui::Separator();
3260 if (ImGui::MenuItem(_("collapse pattern"),BIND_FOR(GUI_ACTION_PAT_COLLAPSE_PAT))) doAction(GUI_ACTION_PAT_COLLAPSE_PAT);
3261 if (ImGui::MenuItem(_("expand pattern"),BIND_FOR(GUI_ACTION_PAT_EXPAND_PAT))) doAction(GUI_ACTION_PAT_EXPAND_PAT);
3262 }
3263
3264 if (topMenu) {
3265 ImGui::Separator();
3266 if (ImGui::MenuItem(_("collapse song"),BIND_FOR(GUI_ACTION_PAT_COLLAPSE_SONG))) doAction(GUI_ACTION_PAT_COLLAPSE_SONG);
3267 if (ImGui::MenuItem(_("expand song"),BIND_FOR(GUI_ACTION_PAT_EXPAND_SONG))) doAction(GUI_ACTION_PAT_EXPAND_SONG);
3268 }
3269
3270 if (topMenu) {
3271 ImGui::Separator();
3272 if (ImGui::MenuItem(_("find/replace"),BIND_FOR(GUI_ACTION_WINDOW_FIND),findOpen)) {
3273 if (findOpen) {
3274 findOpen=false;
3275 } else {
3276 nextWindow=GUI_WINDOW_FIND;
3277 }
3278 }
3279 }
3280 }
3281
3282 void FurnaceGUI::toggleMobileUI(bool enable, bool force) {
3283 if (mobileUI!=enable || force) {
3284 if (!mobileUI && enable) {
3285 if (!ImGui::SaveIniSettingsToDisk(finalLayoutPath,true)) {
3286 reportError(fmt::sprintf(_("could NOT save layout! %s"),strerror(errno)));
3287 }
3288 }
3289 mobileUI=enable;
3290 if (mobileUI) {
3291 ImGui::GetIO().IniFilename=NULL;
3292 ImGui::GetIO().ConfigFlags|=ImGuiConfigFlags_InertialScrollEnable;
3293 ImGui::GetIO().ConfigFlags|=ImGuiConfigFlags_NoHoverColors;
3294 ImGui::GetIO().AlwaysScrollText=true;
3295 fileDialog->mobileUI=true;
3296 } else {
3297 ImGui::GetIO().IniFilename=NULL;
3298 if (!ImGui::LoadIniSettingsFromDisk(finalLayoutPath,true)) {
3299 reportError(fmt::sprintf(_("could NOT load layout! %s"),strerror(errno)));
3300 ImGui::LoadIniSettingsFromMemory(defaultLayout);
3301 }
3302 ImGui::GetIO().ConfigFlags&=~ImGuiConfigFlags_InertialScrollEnable;
3303 ImGui::GetIO().ConfigFlags&=~ImGuiConfigFlags_NoHoverColors;
3304 ImGui::GetIO().AlwaysScrollText=false;
3305 fileDialog->mobileUI=false;
3306 }
3307 }
3308 }
3309
3310 void FurnaceGUI::pushToggleColors(bool status) {
3311 ImVec4 toggleColor=status?uiColors[GUI_COLOR_TOGGLE_ON]:uiColors[GUI_COLOR_TOGGLE_OFF];
3312 ImGui::PushStyleColor(ImGuiCol_Button,toggleColor);
3313 if (!mobileUI) {
3314 if (settings.guiColorsBase) {
3315 toggleColor.x*=0.8f;
3316 toggleColor.y*=0.8f;
3317 toggleColor.z*=0.8f;
3318 } else {
3319 toggleColor.x=CLAMP(toggleColor.x*1.3f,0.0f,1.0f);
3320 toggleColor.y=CLAMP(toggleColor.y*1.3f,0.0f,1.0f);
3321 toggleColor.z=CLAMP(toggleColor.z*1.3f,0.0f,1.0f);
3322 }
3323 }
3324 ImGui::PushStyleColor(ImGuiCol_ButtonHovered,toggleColor);
3325 if (settings.guiColorsBase) {
3326 toggleColor.x*=0.8f;
3327 toggleColor.y*=0.8f;
3328 toggleColor.z*=0.8f;
3329 } else {
3330 toggleColor.x=CLAMP(toggleColor.x*1.5f,0.0f,1.0f);
3331 toggleColor.y=CLAMP(toggleColor.y*1.5f,0.0f,1.0f);
3332 toggleColor.z=CLAMP(toggleColor.z*1.5f,0.0f,1.0f);
3333 }
3334 ImGui::PushStyleColor(ImGuiCol_ButtonActive,toggleColor);
3335 }
3336
3337 void FurnaceGUI::popToggleColors() {
3338 ImGui::PopStyleColor(3);
3339 }
3340
3341 int _processEvent(void* instance, SDL_Event* event) {
3342 return ((FurnaceGUI*)instance)->processEvent(event);
3343 }
3344
3345 #if SDL_VERSION_ATLEAST(2,0,17)
3346 #define VALID_MODS KMOD_NUM|KMOD_CAPS|KMOD_SCROLL
3347 #else
3348 #define VALID_MODS KMOD_NUM|KMOD_CAPS
3349 #endif
3350
3351 int FurnaceGUI::processEvent(SDL_Event* ev) {
3352 if (introPos<11.0 && !shortIntro) return 1;
3353 #ifdef IS_MOBILE
3354 if (ev->type==SDL_APP_TERMINATING) {
3355 // TODO: save last song state here
3356 } else if (ev->type==SDL_APP_WILLENTERBACKGROUND) {
3357 commitState(e->getConfObject());
3358 e->saveConf();
3359 }
3360 #endif
3361 if (cvOpen) return 1;
3362 if (ev->type==SDL_KEYDOWN) {
3363 if (!ev->key.repeat && latchTarget==0 && !wantCaptureKeyboard && !sampleMapWaitingInput && (ev->key.keysym.mod&(~(VALID_MODS)))==0) {
3364 if (settings.notePreviewBehavior==0) return 1;
3365 switch (curWindow) {
3366 case GUI_WINDOW_SAMPLE_EDIT:
3367 case GUI_WINDOW_SAMPLE_LIST: {
3368 auto it=noteKeys.find(ev->key.keysym.scancode);
3369 if (it!=noteKeys.cend()) {
3370 int key=it->second;
3371 int num=12*curOctave+key;
3372 if (key!=100 && key!=101 && key!=102) {
3373 int pStart=-1;
3374 int pEnd=-1;
3375 if (curWindow==GUI_WINDOW_SAMPLE_EDIT) {
3376 if (sampleSelStart!=sampleSelEnd) {
3377 pStart=sampleSelStart;
3378 pEnd=sampleSelEnd;
3379 if (pStart>pEnd) {
3380 pStart^=pEnd;
3381 pEnd^=pStart;
3382 pStart^=pEnd;
3383 }
3384 }
3385 }
3386 e->previewSample(curSample,num,pStart,pEnd);
3387 samplePreviewOn=true;
3388 samplePreviewKey=ev->key.keysym.scancode;
3389 samplePreviewNote=num;
3390 }
3391 }
3392 break;
3393 }
3394 case GUI_WINDOW_WAVE_LIST:
3395 case GUI_WINDOW_WAVE_EDIT: {
3396 auto it=noteKeys.find(ev->key.keysym.scancode);
3397 if (it!=noteKeys.cend()) {
3398 int key=it->second;
3399 int num=12*curOctave+key;
3400 if (key!=100 && key!=101 && key!=102) {
3401 e->previewWave(curWave,num);
3402 wavePreviewOn=true;
3403 wavePreviewKey=ev->key.keysym.scancode;
3404 wavePreviewNote=num;
3405 }
3406 }
3407 break;
3408 }
3409 case GUI_WINDOW_ORDERS: // ignore here
3410 break;
3411 case GUI_WINDOW_PATTERN:
3412 if (settings.notePreviewBehavior==1) {
3413 if (cursor.xFine!=0) break;
3414 } else if (settings.notePreviewBehavior==2) {
3415 if (edit && cursor.xFine!=0) break;
3416 }
3417 // fall-through
3418 default: {
3419 auto it=noteKeys.find(ev->key.keysym.scancode);
3420 if (it!=noteKeys.cend()) {
3421 int key=it->second;
3422 int num=12*curOctave+key;
3423
3424 if (num<-60) num=-60; // C-(-5)
3425 if (num>119) num=119; // B-9
3426
3427 if (key!=100 && key!=101 && key!=102) {
3428 previewNote(cursor.xCoarse,num);
3429 }
3430 }
3431 break;
3432 }
3433 }
3434 }
3435 } else if (ev->type==SDL_KEYUP) {
3436 stopPreviewNote(ev->key.keysym.scancode,true);
3437 if (wavePreviewOn) {
3438 if (ev->key.keysym.scancode==wavePreviewKey) {
3439 wavePreviewOn=false;
3440 e->stopWavePreview();
3441 }
3442 }
3443 if (samplePreviewOn) {
3444 if (ev->key.keysym.scancode==samplePreviewKey) {
3445 samplePreviewOn=false;
3446 e->stopSamplePreview();
3447 }
3448 }
3449 }
3450 return 1;
3451 }
3452
3453 #define FIND_POINT(p,pid) \
3454 for (TouchPoint& i: activePoints) { \
3455 if (i.id==pid) { \
3456 p=&i; \
3457 } \
3458 }
3459
3460 void FurnaceGUI::processPoint(SDL_Event& ev) {
3461 switch (ev.type) {
3462 case SDL_MOUSEMOTION: {
3463 TouchPoint* point=NULL;
3464 FIND_POINT(point,-1);
3465 if (point!=NULL) {
3466 point->x=(double)ev.motion.x*((double)canvasW/(double)scrW);
3467 point->y=(double)ev.motion.y*((double)canvasH/(double)scrH);
3468 }
3469 break;
3470 }
3471 case SDL_MOUSEBUTTONDOWN: {
3472 if (ev.button.button!=SDL_BUTTON_LEFT) break;
3473 for (size_t i=0; i<activePoints.size(); i++) {
3474 TouchPoint& point=activePoints[i];
3475 if (point.id==-1) {
3476 releasedPoints.push_back(point);
3477 activePoints.erase(activePoints.begin()+i);
3478 break;
3479 }
3480 }
3481 TouchPoint newPoint(ev.button.x,ev.button.y);
3482 #ifdef __APPLE__
3483 newPoint.x*=dpiScale;
3484 newPoint.y*=dpiScale;
3485 #endif
3486 activePoints.push_back(newPoint);
3487 pressedPoints.push_back(newPoint);
3488 break;
3489 }
3490 case SDL_MOUSEBUTTONUP: {
3491 if (ev.button.button!=SDL_BUTTON_LEFT) break;
3492 for (size_t i=0; i<activePoints.size(); i++) {
3493 TouchPoint& point=activePoints[i];
3494 if (point.id==-1) {
3495 releasedPoints.push_back(point);
3496 activePoints.erase(activePoints.begin()+i);
3497 break;
3498 }
3499 }
3500 break;
3501 }
3502 case SDL_FINGERMOTION: {
3503 TouchPoint* point=NULL;
3504 FIND_POINT(point,ev.tfinger.fingerId);
3505 if (point!=NULL) {
3506 float prevX=point->x;
3507 float prevY=point->y;
3508 point->x=ev.tfinger.x*canvasW;
3509 point->y=ev.tfinger.y*canvasH;
3510 point->z=ev.tfinger.pressure;
3511
3512 if (point->id==0) {
3513 ImGui::GetIO().AddMousePosEvent(point->x,point->y);
3514 pointMotion(point->x,point->y,point->x-prevX,point->y-prevY);
3515 }
3516 }
3517 break;
3518 }
3519 case SDL_FINGERDOWN: {
3520 for (size_t i=0; i<activePoints.size(); i++) {
3521 TouchPoint& point=activePoints[i];
3522 if (point.id==ev.tfinger.fingerId) {
3523 releasedPoints.push_back(point);
3524 activePoints.erase(activePoints.begin()+i);
3525 break;
3526 }
3527 }
3528 TouchPoint newPoint(ev.tfinger.fingerId,ev.tfinger.x*canvasW,ev.tfinger.y*canvasH,ev.tfinger.pressure);
3529 activePoints.push_back(newPoint);
3530 pressedPoints.push_back(newPoint);
3531
3532 if (newPoint.id==0) {
3533 ImGui::GetIO().AddMousePosEvent(newPoint.x,newPoint.y);
3534 ImGui::GetIO().AddMouseButtonEvent(ImGuiMouseButton_Left,true);
3535 pointDown(newPoint.x,newPoint.y,0);
3536 }
3537 break;
3538 }
3539 case SDL_FINGERUP: {
3540 for (size_t i=0; i<activePoints.size(); i++) {
3541 TouchPoint& point=activePoints[i];
3542 if (point.id==ev.tfinger.fingerId) {
3543 if (point.id==0) {
3544 ImGui::GetIO().AddMouseButtonEvent(ImGuiMouseButton_Left,false);
3545 //ImGui::GetIO().AddMousePosEvent(-FLT_MAX,-FLT_MAX);
3546 pointUp(point.x,point.y,0);
3547 }
3548
3549 releasedPoints.push_back(point);
3550 activePoints.erase(activePoints.begin()+i);
3551
3552 break;
3553 }
3554 }
3555 break;
3556 }
3557 }
3558 }
3559
3560 void FurnaceGUI::pointDown(int x, int y, int button) {
3561 aboutOpen=false;
3562 if (bindSetActive) {
3563 bindSetActive=false;
3564 bindSetPending=false;
3565 actionKeys[bindSetTarget][bindSetTargetIdx]=bindSetPrevValue;
3566 if (bindSetTargetIdx==(int)actionKeys[bindSetTarget].size()-1 && bindSetPrevValue<=0) {
3567 actionKeys[bindSetTarget].pop_back();
3568 }
3569 bindSetTarget=0;
3570 bindSetTargetIdx=0;
3571 bindSetPrevValue=0;
3572 }
3573 if (introPos<11.0 && !shortIntro) {
3574 introSkipDo=true;
3575 }
3576 }
3577
3578 void FurnaceGUI::pointUp(int x, int y, int button) {
3579 if (macroDragActive || macroLoopDragActive || waveDragActive || (sampleDragActive && sampleDragMode && sampleDragTarget)) {
3580 MARK_MODIFIED;
3581 }
3582 if (macroDragActive && macroDragLineMode && !macroDragMouseMoved) {
3583 displayMacroMenu=true;
3584 }
3585 macroDragActive=false;
3586 macroDragBitMode=false;
3587 macroDragInitialValue=false;
3588 macroDragInitialValueSet=false;
3589 macroDragLastX=-1;
3590 macroDragLastY=-1;
3591 macroLoopDragActive=false;
3592 waveDragActive=false;
3593 if (introPos<11.0 && introSkip<0.5 && !shortIntro) {
3594 introSkipDo=false;
3595 }
3596 if (sampleDragActive) {
3597 logD("stopping sample drag");
3598 if (sampleDragMode) {
3599 e->renderSamplesP(curSample);
3600 } else {
3601 if (sampleSelStart>sampleSelEnd) {
3602 sampleSelStart^=sampleSelEnd;
3603 sampleSelEnd^=sampleSelStart;
3604 sampleSelStart^=sampleSelEnd;
3605 }
3606 }
3607 }
3608 sampleDragActive=false;
3609 if (orderScrollLocked) {
3610 int targetOrder=round(orderScroll);
3611 if (orderScrollTolerance) {
3612 targetOrder=round(orderScroll+(orderScrollRealOrigin.x-((float)canvasW/2.0f))/(40.0f*dpiScale));
3613 }
3614 if (targetOrder<0) targetOrder=0;
3615 if (targetOrder>e->curSubSong->ordersLen-1) targetOrder=e->curSubSong->ordersLen-1;
3616 if (curOrder!=targetOrder) setOrder(targetOrder);
3617 }
3618 orderScrollLocked=false;
3619 orderScrollTolerance=false;
3620 if (dragMobileMenu) {
3621 dragMobileMenu=false;
3622 if (mobileMenuOpen) {
3623 mobileMenuOpen=(mobileMenuPos>=0.85f);
3624 } else {
3625 mobileMenuOpen=(mobileMenuPos>=0.15f);
3626 }
3627 }
3628 if (dragMobileEditButton) {
3629 dragMobileEditButton=false;
3630 }
3631 }
3632
3633 void FurnaceGUI::pointMotion(int x, int y, int xrel, int yrel) {
3634 if (selecting && (!mobileUI || mobilePatSel)) {
3635 // detect whether we have to scroll
3636 if (y<patWindowPos.y+2.0f*dpiScale) {
3637 addScroll(-1);
3638 }
3639 if (y>patWindowPos.y+patWindowSize.y-2.0f*dpiScale) {
3640 addScroll(1);
3641 }
3642 if (x<patWindowPos.x+(mobileUI?40.0f:4.0f)*dpiScale) {
3643 addScrollX(-1);
3644 }
3645 if (x>patWindowPos.x+patWindowSize.x-(mobileUI?40.0f:4.0f)*dpiScale) {
3646 addScrollX(1);
3647 }
3648 }
3649 if (macroDragActive || macroLoopDragActive || waveDragActive || sampleDragActive || orderScrollLocked) {
3650 int distance=fabs((double)xrel);
3651 if (distance<1) distance=1;
3652 float start=x-xrel;
3653 float end=x;
3654 float startY=y-yrel;
3655 float endY=y;
3656 for (int i=0; i<=distance; i++) {
3657 float fraction=(float)i/(float)distance;
3658 float x=start+(end-start)*fraction;
3659 float y=startY+(endY-startY)*fraction;
3660 processDrags(x,y);
3661 }
3662 }
3663 }
3664
3665 // how many pixels should be visible at least at x/y dir
3666 #define OOB_PIXELS_SAFETY 25
3667
3668 bool FurnaceGUI::detectOutOfBoundsWindow(SDL_Rect& failing) {
3669 int count=SDL_GetNumVideoDisplays();
3670 if (count<1) {
3671 logW("bounds check: error: %s",SDL_GetError());
3672 return false;
3673 }
3674
3675 SDL_Rect rect;
3676 for (int i=0; i<count; i++) {
3677 if (SDL_GetDisplayUsableBounds(i,&rect)!=0) {
3678 logW("bounds check: error in display %d: %s",i,SDL_GetError());
3679 continue;
3680 }
3681
3682 bool xbound=((rect.x+OOB_PIXELS_SAFETY)<=(scrX+scrW)) && ((rect.x+rect.w-OOB_PIXELS_SAFETY)>=scrX);
3683 bool ybound=((rect.y+OOB_PIXELS_SAFETY)<=(scrY+scrH)) && ((rect.y+rect.h-OOB_PIXELS_SAFETY)>=scrY);
3684 logD("bounds check: display %d is at %dx%dx%dx%d: %s%s",i,rect.x+OOB_PIXELS_SAFETY,rect.y+OOB_PIXELS_SAFETY,rect.x+rect.w-OOB_PIXELS_SAFETY,rect.y+rect.h-OOB_PIXELS_SAFETY,xbound?"x":"",ybound?"y":"");
3685
3686 if (xbound && ybound) {
3687 return true;
3688 }
3689 }
3690
3691 failing=rect;
3692 return false;
3693 }
3694
3695 #define DECLARE_METRIC(_n) \
3696 uint64_t __perfM##_n;
3697
3698 #define MEASURE_BEGIN(_n) \
3699 __perfM##_n=SDL_GetPerformanceCounter();
3700
3701 #define MEASURE_END(_n) \
3702 if (perfMetricsLen<64) { \
3703 perfMetrics[perfMetricsLen++]=FurnaceGUIPerfMetric(#_n,SDL_GetPerformanceCounter()-__perfM##_n); \
3704 }
3705
3706 #define MEASURE(_n,_x) \
3707 MEASURE_BEGIN(_n) \
3708 _x; \
3709 MEASURE_END(_n)
3710
3711 #define IMPORT_CLOSE(x) \
3712 if (x) pendingLayoutImportReopen.push(&x); \
3713 x=false;
3714
3715 bool FurnaceGUI::loop() {
3716 DECLARE_METRIC(calcChanOsc)
3717 DECLARE_METRIC(mobileControls)
3718 DECLARE_METRIC(mobileOrderSel)
3719 DECLARE_METRIC(subSongs)
3720 DECLARE_METRIC(findReplace)
3721 DECLARE_METRIC(spoiler)
3722 DECLARE_METRIC(pattern)
3723 DECLARE_METRIC(editControls)
3724 DECLARE_METRIC(speed)
3725 DECLARE_METRIC(grooves)
3726 DECLARE_METRIC(songInfo)
3727 DECLARE_METRIC(orders)
3728 #ifndef NO_INTRO
3729 DECLARE_METRIC(intro)
3730 #endif
3731 DECLARE_METRIC(sampleList)
3732 DECLARE_METRIC(sampleEdit)
3733 DECLARE_METRIC(waveList)
3734 DECLARE_METRIC(waveEdit)
3735 DECLARE_METRIC(insList)
3736 DECLARE_METRIC(insEdit)
3737 DECLARE_METRIC(mixer)
3738 DECLARE_METRIC(readOsc)
3739 DECLARE_METRIC(osc)
3740 DECLARE_METRIC(chanOsc)
3741 DECLARE_METRIC(xyOsc)
3742 DECLARE_METRIC(volMeter)
3743 DECLARE_METRIC(settings)
3744 DECLARE_METRIC(debug)
3745 DECLARE_METRIC(csPlayer)
3746 DECLARE_METRIC(stats)
3747 DECLARE_METRIC(memory)
3748 DECLARE_METRIC(compatFlags)
3749 DECLARE_METRIC(piano)
3750 DECLARE_METRIC(notes)
3751 DECLARE_METRIC(channels)
3752 DECLARE_METRIC(patManager)
3753 DECLARE_METRIC(sysManager)
3754 DECLARE_METRIC(clock)
3755 DECLARE_METRIC(regView)
3756 DECLARE_METRIC(log)
3757 DECLARE_METRIC(effectList)
3758 DECLARE_METRIC(userPresets)
3759 DECLARE_METRIC(popup)
3760
3761 #ifdef IS_MOBILE
3762 bool doThreadedInput=true;
3763 #else
3764 bool doThreadedInput=!settings.noThreadedInput;
3765 #endif
3766 if (doThreadedInput) {
3767 logD("key input: event filter");
3768 SDL_SetEventFilter(_processEvent,this);
3769 } else {
3770 logD("key input: main thread");
3771 }
3772
3773 if (safeMode) {
3774 showError(_("Furnace has been started in Safe Mode.\nthis means that:\n\n- software rendering is being used\n- audio output may not work\n- font loading is disabled\n\ncheck any settings which may have made Furnace start up in this mode.\nfont loading is one of these."));
3775 settingsOpen=true;
3776 }
3777
3778 while (!quit) {
3779 SDL_Event ev;
3780 if (e->isPlaying()) {
3781 WAKE_UP;
3782 }
3783 if (--drawHalt<=0) {
3784 drawHalt=0;
3785 if (settings.powerSave) SDL_WaitEventTimeout(NULL,500);
3786 }
3787
3788 memcpy(perfMetricsLast,perfMetrics,64*sizeof(FurnaceGUIPerfMetric));
3789 perfMetricsLastLen=perfMetricsLen;
3790 perfMetricsLen=0;
3791
3792 eventTimeBegin=SDL_GetPerformanceCounter();
3793 bool updateWindow=false;
3794 if (injectBackUp) {
3795 ImGui::GetIO().AddKeyEvent(ImGuiKey_Backspace,false);
3796 injectBackUp=false;
3797 }
3798
3799 while (SDL_PollEvent(&ev)) {
3800 WAKE_UP;
3801 ImGui_ImplSDL2_ProcessEvent(&ev);
3802 processPoint(ev);
3803 if (!doThreadedInput) processEvent(&ev);
3804 switch (ev.type) {
3805 case SDL_MOUSEMOTION: {
3806 int motionX=(double)ev.motion.x*((double)canvasW/(double)scrW);
3807 int motionY=(double)ev.motion.y*((double)canvasH/(double)scrH);
3808 int motionXrel=(double)ev.motion.xrel*((double)canvasW/(double)scrW);
3809 int motionYrel=(double)ev.motion.yrel*((double)canvasH/(double)scrH);
3810 pointMotion(motionX,motionY,motionXrel,motionYrel);
3811 break;
3812 }
3813 case SDL_MOUSEBUTTONUP:
3814 pointUp(ev.button.x,ev.button.y,ev.button.button);
3815 insEditMayBeDirty=true;
3816 break;
3817 case SDL_MOUSEBUTTONDOWN:
3818 pointDown(ev.button.x,ev.button.y,ev.button.button);
3819 insEditMayBeDirty=true;
3820 break;
3821 case SDL_MOUSEWHEEL:
3822 wheelX+=ev.wheel.x;
3823 wheelY+=ev.wheel.y;
3824 insEditMayBeDirty=true;
3825 break;
3826 case SDL_WINDOWEVENT:
3827 switch (ev.window.event) {
3828 case SDL_WINDOWEVENT_RESIZED:
3829 scrW=ev.window.data1;
3830 scrH=ev.window.data2;
3831 portrait=(scrW<scrH);
3832 logV("portrait: %d (%dx%d)",portrait,scrW,scrH);
3833 logD("window resized to %dx%d",scrW,scrH);
3834 updateWindow=true;
3835 rend->resized(ev);
3836 break;
3837 case SDL_WINDOWEVENT_MOVED:
3838 scrX=ev.window.data1;
3839 scrY=ev.window.data2;
3840 updateWindow=true;
3841 shallDetectScale=2;
3842 logV("window moved to %dx%d",scrX,scrY);
3843 break;
3844 case SDL_WINDOWEVENT_SIZE_CHANGED:
3845 logV("window size changed to %dx%d",ev.window.data1,ev.window.data2);
3846 break;
3847 case SDL_WINDOWEVENT_MINIMIZED:
3848 logV("window minimized");
3849 break;
3850 case SDL_WINDOWEVENT_MAXIMIZED:
3851 scrMax=true;
3852 updateWindow=true;
3853 logV("window maximized");
3854 break;
3855 case SDL_WINDOWEVENT_RESTORED:
3856 scrMax=false;
3857 updateWindow=true;
3858 logV("window restored");
3859 break;
3860 case SDL_WINDOWEVENT_SHOWN:
3861 logV("window shown");
3862 break;
3863 case SDL_WINDOWEVENT_HIDDEN:
3864 logV("window hidden");
3865 break;
3866 case SDL_WINDOWEVENT_EXPOSED:
3867 logV("window exposed");
3868 break;
3869 }
3870 break;
3871 #if SDL_VERSION_ATLEAST(2,0,4)
3872 case SDL_RENDER_DEVICE_RESET:
3873 killGraphics=true;
3874 break;
3875 #endif
3876 #if SDL_VERSION_ATLEAST(2,0,17)
3877 case SDL_DISPLAYEVENT: {
3878 switch (ev.display.event) {
3879 case SDL_DISPLAYEVENT_CONNECTED:
3880 logD("display %d connected!",ev.display.display);
3881 updateWindow=true;
3882 shallDetectScale=16;
3883 break;
3884 case SDL_DISPLAYEVENT_DISCONNECTED:
3885 logD("display %d disconnected!",ev.display.display);
3886 updateWindow=true;
3887 shallDetectScale=16;
3888 break;
3889 case SDL_DISPLAYEVENT_ORIENTATION:
3890 logD("display oriented to %d",ev.display.data1);
3891 updateWindow=true;
3892 break;
3893 }
3894 break;
3895 }
3896 #endif
3897 case SDL_KEYDOWN:
3898 if (!ImGui::GetIO().WantCaptureKeyboard || (ImGuiFileDialog::Instance()->IsOpened() && !ImGui::GetIO().WantTextInput)) {
3899 keyDown(ev);
3900 }
3901 if (introPos<11.0 && !shortIntro) {
3902 if (ev.key.keysym.scancode==SDL_SCANCODE_SPACE || ev.key.keysym.scancode==SDL_SCANCODE_ESCAPE || ev.key.keysym.scancode==SDL_SCANCODE_RETURN) {
3903 introSkip=0.5;
3904 }
3905 introSkipDo=true;
3906 }
3907 insEditMayBeDirty=true;
3908 #ifdef IS_MOBILE
3909 injectBackUp=true;
3910 #endif
3911 break;
3912 case SDL_KEYUP:
3913 // for now
3914 insEditMayBeDirty=true;
3915 if (introPos<11.0 && introSkip<0.5 && !shortIntro) {
3916 introSkipDo=false;
3917 }
3918 break;
3919 case SDL_DROPFILE:
3920 if (ev.drop.file!=NULL) {
3921 if (introPos<11.0) {
3922 SDL_free(ev.drop.file);
3923 break;
3924 }
3925 int sampleCountBefore=e->song.sampleLen;
3926 std::vector<DivInstrument*> instruments=e->instrumentFromFile(ev.drop.file,true,settings.readInsNames);
3927 std::vector<DivSample*> samples = e->sampleFromFile(ev.drop.file);
3928 DivWavetable* droppedWave=NULL;
3929 //DivSample* droppedSample=NULL;
3930 if (!instruments.empty()) {
3931 if (e->song.sampleLen!=sampleCountBefore) {
3932 e->renderSamplesP();
3933 }
3934 if (!e->getWarnings().empty()) {
3935 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
3936 }
3937 int instrumentCount=-1;
3938 for (DivInstrument* i: instruments) {
3939 instrumentCount=e->addInstrumentPtr(i);
3940 }
3941 if (instrumentCount>=0 && settings.selectAssetOnLoad) {
3942 curIns=instrumentCount-1;
3943 }
3944 nextWindow=GUI_WINDOW_INS_LIST;
3945 MARK_MODIFIED;
3946 } else if ((droppedWave=e->waveFromFile(ev.drop.file,false))!=NULL) {
3947 int waveCount=-1;
3948 waveCount=e->addWavePtr(droppedWave);
3949 if (waveCount>=0 && settings.selectAssetOnLoad) {
3950 curWave=waveCount-1;
3951 }
3952 nextWindow=GUI_WINDOW_WAVE_LIST;
3953 MARK_MODIFIED;
3954 }
3955 else if (!samples.empty())
3956 {
3957 if (e->song.sampleLen!=sampleCountBefore) {
3958 //e->renderSamplesP();
3959 }
3960 if (!e->getWarnings().empty())
3961 {
3962 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
3963 }
3964 int sampleCount=-1;
3965 for (DivSample* s: samples)
3966 {
3967 sampleCount=e->addSamplePtr(s);
3968 }
3969 //sampleCount=e->addSamplePtr(droppedSample);
3970 if (sampleCount>=0 && settings.selectAssetOnLoad)
3971 {
3972 curSample=sampleCount;
3973 updateSampleTex=true;
3974 }
3975 nextWindow=GUI_WINDOW_SAMPLE_LIST;
3976 MARK_MODIFIED;
3977 } else if (modified) {
3978 nextFile=ev.drop.file;
3979 showWarning(_("Unsaved changes! Save changes before opening file?"),GUI_WARN_OPEN_DROP);
3980 } else {
3981 if (load(ev.drop.file)>0) {
3982 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
3983 }
3984 }
3985 SDL_free(ev.drop.file);
3986 }
3987 break;
3988 case SDL_USEREVENT:
3989 // used for MIDI wake up
3990 break;
3991 case SDL_QUIT:
3992 if (requestQuit()) {
3993 return true;
3994 }
3995 break;
3996 }
3997 }
3998
3999 // update config x/y/w/h values based on scrMax state
4000 if (updateWindow) {
4001 logV("updateWindow is true");
4002 if (!scrMax && !fullScreen) {
4003 logV("updating scrConf");
4004 scrConfX=scrX;
4005 scrConfY=scrY;
4006 scrConfW=scrW;
4007 scrConfH=scrH;
4008 }
4009 if (rend!=NULL) {
4010 logV("restoring swap interval...");
4011 rend->setSwapInterval(settings.vsync);
4012 }
4013 }
4014 // update canvas size as well
4015 if (!rend->getOutputSize(canvasW,canvasH)) {
4016 logW("loop: error while getting output size!");
4017 } else {
4018 //logV("updateWindow: canvas size %dx%d",canvasW,canvasH);
4019 // and therefore window size
4020 int prevScrW=scrW;
4021 int prevScrH=scrH;
4022 SDL_GetWindowSize(sdlWin,&scrW,&scrH);
4023 if (prevScrW!=scrW || prevScrH!=scrH) {
4024 logV("size change 2: %dx%d (from %dx%d)",scrW,scrH,prevScrW,prevScrH);
4025 }
4026
4027 ImGui::GetIO().InputScale=(float)canvasW/(float)scrW;
4028 }
4029
4030 wantCaptureKeyboard=ImGui::GetIO().WantTextInput;
4031
4032 if (wantCaptureKeyboard!=oldWantCaptureKeyboard) {
4033 oldWantCaptureKeyboard=wantCaptureKeyboard;
4034 if (wantCaptureKeyboard) {
4035 SDL_StartTextInput();
4036 } else {
4037 SDL_StopTextInput();
4038 }
4039 }
4040
4041 if (wantCaptureKeyboard) {
4042 WAKE_UP;
4043 }
4044
4045 if (ImGui::GetIO().IsSomethingHappening) {
4046 WAKE_UP;
4047 }
4048
4049 if (ImGui::GetIO().MouseDown[0] || ImGui::GetIO().MouseDown[1] || ImGui::GetIO().MouseDown[2] || ImGui::GetIO().MouseDown[3] || ImGui::GetIO().MouseDown[4]) {
4050 WAKE_UP;
4051 }
4052
4053 while (true) {
4054 midiLock.lock();
4055 midiWakeUp=true;
4056 if (midiQueue.empty()) {
4057 midiLock.unlock();
4058 break;
4059 }
4060 TAMidiMessage msg=midiQueue.front();
4061 midiLock.unlock();
4062
4063 if (msg.type==TA_MIDI_SYSEX) {
4064 unsigned char* data=msg.sysExData.get();
4065 for (size_t i=0; i<msg.sysExLen; i++) {
4066 if ((i&15)==0) printf("\n");
4067 printf("%.2x ",data[i]);
4068 }
4069 printf("\n");
4070
4071 if (!parseSysEx(data,msg.sysExLen)) {
4072 logW("error while parsing SysEx data!");
4073 }
4074 }
4075
4076 // parse message here
4077 if (learning!=-1) {
4078 if (learning>=0 && learning<(int)midiMap.binds.size()) {
4079 midiMap.binds[learning].type=msg.type>>4;
4080 midiMap.binds[learning].channel=msg.type&15;
4081 midiMap.binds[learning].data1=msg.data[0];
4082 switch (msg.type&0xf0) {
4083 case TA_MIDI_NOTE_OFF:
4084 case TA_MIDI_NOTE_ON:
4085 case TA_MIDI_AFTERTOUCH:
4086 case TA_MIDI_PITCH_BEND:
4087 case TA_MIDI_CONTROL:
4088 midiMap.binds[learning].data2=msg.data[1];
4089 break;
4090 default:
4091 midiMap.binds[learning].data2=128;
4092 break;
4093 }
4094 }
4095 learning=-1;
4096 } else {
4097 int action=midiMap.at(msg);
4098 if (action!=0) {
4099 doAction(action);
4100 } else switch (msg.type&0xf0) {
4101 case TA_MIDI_NOTE_ON:
4102 if (midiMap.valueInputStyle==0 || midiMap.valueInputStyle>3 || cursor.xFine==0) {
4103 if (midiMap.noteInput && edit && msg.data[1]!=0) {
4104 noteInput(
4105 msg.data[0]-12,
4106 0,
4107 midiMap.volInput?msg.data[1]:-1
4108 );
4109 }
4110 } else {
4111 if (edit && msg.data[1]!=0) {
4112 switch (midiMap.valueInputStyle) {
4113 case 1: {
4114 int val=msg.data[0]%24;
4115 if (val<16) {
4116 valueInput(val);
4117 }
4118 break;
4119 }
4120 case 2:
4121 valueInput(msg.data[0]&15);
4122 break;
4123 case 3:
4124 int val=altValues[msg.data[0]%24];
4125 if (val>=0) {
4126 valueInput(val);
4127 }
4128 break;
4129 }
4130 }
4131 }
4132 break;
4133 case TA_MIDI_PROGRAM:
4134 if (midiMap.programChange && !(midiMap.directChannel && midiMap.directProgram)) {
4135 curIns=msg.data[0];
4136 if (curIns>=(int)e->song.ins.size()) curIns=e->song.ins.size()-1;
4137 wavePreviewInit=true;
4138 updateFMPreview=true;
4139 }
4140 break;
4141 case TA_MIDI_CONTROL:
4142 bool gchanged=false;
4143 if (msg.data[0]==midiMap.valueInputControlMSB) {
4144 midiMap.valueInputCurMSB=msg.data[1];
4145 gchanged=true;
4146 }
4147 if (msg.data[0]==midiMap.valueInputControlLSB) {
4148 midiMap.valueInputCurLSB=msg.data[1];
4149 gchanged=true;
4150 }
4151 if (msg.data[0]==midiMap.valueInputControlSingle) {
4152 midiMap.valueInputCurSingle=msg.data[1];
4153 gchanged=true;
4154 }
4155 if (gchanged && cursor.xFine>0) {
4156 switch (midiMap.valueInputStyle) {
4157 case 4: // dual CC
4158 valueInput(((midiMap.valueInputCurMSB>>3)<<4)|(midiMap.valueInputCurLSB>>3),true);
4159 break;
4160 case 5: // 14-bit
4161 valueInput((midiMap.valueInputCurMSB<<1)|(midiMap.valueInputCurLSB>>6),true);
4162 break;
4163 case 6: // single CC
4164 valueInput((midiMap.valueInputCurSingle*255)/127,true);
4165 break;
4166 }
4167 }
4168
4169 for (int i=0; i<18; i++) {
4170 bool changed=false;
4171 if (midiMap.valueInputSpecificStyle[i]!=0) {
4172 if (msg.data[0]==midiMap.valueInputSpecificMSB[i]) {
4173 changed=true;
4174 midiMap.valueInputCurMSBS[i]=msg.data[1];
4175 }
4176 if (msg.data[0]==midiMap.valueInputSpecificLSB[i]) {
4177 changed=true;
4178 midiMap.valueInputCurLSBS[i]=msg.data[1];
4179 }
4180 if (msg.data[0]==midiMap.valueInputSpecificSingle[i]) {
4181 changed=true;
4182 midiMap.valueInputCurSingleS[i]=msg.data[1];
4183 }
4184
4185 if (changed) switch (midiMap.valueInputStyle) {
4186 case 1: // dual CC
4187 valueInput(((midiMap.valueInputCurMSBS[i]>>3)<<4)|(midiMap.valueInputCurLSBS[i]>>3),true,i+2);
4188 break;
4189 case 2: // 14-bit
4190 valueInput((midiMap.valueInputCurMSBS[i]<<1)|(midiMap.valueInputCurLSBS[i]>>6),true,i+2);
4191 break;
4192 case 3: // single CC
4193 valueInput((midiMap.valueInputCurSingleS[i]*255)/127,true,i+2);
4194 break;
4195 }
4196 }
4197 }
4198 break;
4199 }
4200 }
4201
4202 midiLock.lock();
4203 midiQueue.pop();
4204 midiLock.unlock();
4205 }
4206
4207 if (notifyWaveChange) {
4208 notifyWaveChange=false;
4209 e->notifyWaveChange(curWave);
4210 }
4211
4212 eventTimeEnd=SDL_GetPerformanceCounter();
4213
4214 if (SDL_GetWindowFlags(sdlWin)&SDL_WINDOW_MINIMIZED) {
4215 SDL_Delay(30);
4216 drawHalt=0;
4217 continue;
4218 }
4219
4220 #ifndef NO_INTRO
4221 if (firstFrame && !safeMode && renderBackend!=GUI_BACKEND_SOFTWARE) {
4222 if (!tutorial.introPlayed || settings.alwaysPlayIntro==3 || (settings.alwaysPlayIntro==2 && curFileName.empty())) {
4223 unsigned char* introTemp=new unsigned char[intro_fur_len];
4224 memcpy(introTemp,intro_fur,intro_fur_len);
4225 e->load(introTemp,intro_fur_len);
4226 }
4227 }
4228 #endif
4229
4230 if (!e->isRunning()) {
4231 activeNotes.clear();
4232 memset(chanOscVol,0,DIV_MAX_CHANS*sizeof(float));
4233 for (int i=0; i<DIV_MAX_CHANS; i++) {
4234 chanOscChan[i].pitch=0.0f;
4235 }
4236 memset(chanOscBright,0,DIV_MAX_CHANS*sizeof(float));
4237
4238 e->synchronized([this]() {
4239 for (int i=0; i<e->getTotalChannelCount(); i++) {
4240 DivDispatchOscBuffer* buf=e->getOscBuffer(i);
4241 if (buf!=NULL) {
4242 //buf->needle=0;
4243 //buf->readNeedle=0;
4244 // TODO: should we reset here?
4245 }
4246 }
4247 });
4248 }
4249
4250 // recover from dead graphics
4251 if (rend->isDead() || killGraphics) {
4252 killGraphics=false;
4253
4254 logW("graphics are dead! restarting...");
4255
4256 if (sampleTex!=NULL) {
4257 rend->destroyTexture(sampleTex);
4258 sampleTex=NULL;
4259 }
4260
4261 if (chanOscGradTex!=NULL) {
4262 rend->destroyTexture(chanOscGradTex);
4263 chanOscGradTex=NULL;
4264 }
4265
4266 for (auto& i: images) {
4267 if (i.second->tex!=NULL) {
4268 rend->destroyTexture(i.second->tex);
4269 i.second->tex=NULL;
4270 }
4271 }
4272
4273 commitState(e->getConfObject());
4274 rend->quitGUI();
4275 rend->quit();
4276 ImGui_ImplSDL2_Shutdown();
4277
4278 int initAttempts=0;
4279
4280 SDL_Delay(500);
4281
4282 logD("starting render backend...");
4283 while (++initAttempts<=5) {
4284 if (rend->init(sdlWin,settings.vsync)) {
4285 break;
4286 }
4287 SDL_Delay(1000);
4288 logV("trying again...");
4289 }
4290
4291 if (initAttempts>5) {
4292 reportError(_("can't keep going without graphics! Furnace will quit now."));
4293 quit=true;
4294 break;
4295 }
4296
4297 rend->clear(ImVec4(0.0,0.0,0.0,1.0));
4298 rend->present();
4299
4300 logD("preparing user interface...");
4301 rend->initGUI(sdlWin);
4302
4303 logD("building font...");
4304 if (rend->areTexturesSquare()) {
4305 ImGui::GetIO().Fonts->Flags|=ImFontAtlasFlags_Square;
4306 }
4307
4308 firstFrame=true;
4309 mustClear=2;
4310 initialScreenWipe=1.0f;
4311
4312 continue;
4313 }
4314
4315 bool fontsFailed=false;
4316
4317 layoutTimeBegin=SDL_GetPerformanceCounter();
4318
4319 if (pendingLayoutImport!=NULL) {
4320 if (pendingLayoutImportStep==0) {
4321 IMPORT_CLOSE(editControlsOpen);
4322 IMPORT_CLOSE(ordersOpen);
4323 IMPORT_CLOSE(insListOpen);
4324 IMPORT_CLOSE(songInfoOpen);
4325 IMPORT_CLOSE(patternOpen);
4326 IMPORT_CLOSE(insEditOpen);
4327 IMPORT_CLOSE(waveListOpen);
4328 IMPORT_CLOSE(waveEditOpen);
4329 IMPORT_CLOSE(sampleListOpen);
4330 IMPORT_CLOSE(sampleEditOpen);
4331 IMPORT_CLOSE(aboutOpen);
4332 IMPORT_CLOSE(settingsOpen);
4333 IMPORT_CLOSE(mixerOpen);
4334 IMPORT_CLOSE(debugOpen);
4335 IMPORT_CLOSE(inspectorOpen);
4336 IMPORT_CLOSE(oscOpen);
4337 IMPORT_CLOSE(volMeterOpen);
4338 IMPORT_CLOSE(statsOpen);
4339 IMPORT_CLOSE(compatFlagsOpen);
4340 IMPORT_CLOSE(pianoOpen);
4341 IMPORT_CLOSE(notesOpen);
4342 IMPORT_CLOSE(channelsOpen);
4343 IMPORT_CLOSE(regViewOpen);
4344 IMPORT_CLOSE(logOpen);
4345 IMPORT_CLOSE(effectListOpen);
4346 IMPORT_CLOSE(chanOscOpen);
4347 IMPORT_CLOSE(subSongsOpen);
4348 IMPORT_CLOSE(findOpen);
4349 IMPORT_CLOSE(spoilerOpen);
4350 IMPORT_CLOSE(patManagerOpen);
4351 IMPORT_CLOSE(sysManagerOpen);
4352 IMPORT_CLOSE(clockOpen);
4353 IMPORT_CLOSE(speedOpen);
4354 IMPORT_CLOSE(groovesOpen);
4355 IMPORT_CLOSE(xyOscOpen);
4356 IMPORT_CLOSE(memoryOpen);
4357 IMPORT_CLOSE(csPlayerOpen);
4358 IMPORT_CLOSE(userPresetsOpen);
4359 } else if (pendingLayoutImportStep==1) {
4360 // let the UI settle
4361 } else if (pendingLayoutImportStep==2) {
4362 ImGui::LoadIniSettingsFromMemory((const char*)pendingLayoutImport,pendingLayoutImportLen);
4363 } else if (pendingLayoutImportStep==3) {
4364 // restore open windows
4365 while (!pendingLayoutImportReopen.empty()) {
4366 bool* next=pendingLayoutImportReopen.front();
4367 *next=true;
4368 pendingLayoutImportReopen.pop();
4369 }
4370 } else if (pendingLayoutImportStep==4) {
4371 delete[] pendingLayoutImport;
4372 pendingLayoutImport=NULL;
4373 }
4374 pendingLayoutImportStep++;
4375 if (pendingLayoutImport==NULL) pendingLayoutImportStep=0;
4376 }
4377
4378 rend->newFrame();
4379 ImGui_ImplSDL2_NewFrame();
4380 ImGui::NewFrame();
4381
4382 // one second counter
4383 secondTimer+=ImGui::GetIO().DeltaTime;
4384 if (secondTimer>=1.0f) secondTimer=fmod(secondTimer,1.0f);
4385
4386 curWindowLast=curWindow;
4387 curWindow=GUI_WINDOW_NOTHING;
4388 editOptsVisible=false;
4389
4390 int nextPlayOrder=0;
4391 int nextOldRow=0;
4392 e->getPlayPos(nextPlayOrder,nextOldRow);
4393 oldRowChanged=false;
4394 playOrder=nextPlayOrder;
4395 if (followPattern && (!e->isStepping() || pendingStepUpdate)) {
4396 curOrder=playOrder;
4397 }
4398 if (e->isPlaying()) {
4399 if (oldRow!=nextOldRow) oldRowChanged=true;
4400 oldRow=nextOldRow;
4401 }
4402
4403 // check whether pattern of channel(s) at cursor/selection is/are unique
4404 isPatUnique=true;
4405 if (curOrder>=0 && curOrder<e->curSubSong->ordersLen && selStart.xCoarse>=0 && selStart.xCoarse<e->getTotalChannelCount() && selEnd.xCoarse>=0 && selEnd.xCoarse<e->getTotalChannelCount()) {
4406 for (int i=0; i<e->curSubSong->ordersLen; i++) {
4407 if (i==curOrder) continue;
4408 for (int j=selStart.xCoarse; j<=selEnd.xCoarse; j++) {
4409 if (e->curSubSong->orders.ord[j][i]==e->curSubSong->orders.ord[j][curOrder]) isPatUnique=false;
4410 break;
4411 }
4412 if (!isPatUnique) break;
4413 }
4414 }
4415
4416 if (!mobileUI) {
4417 ImGui::BeginMainMenuBar();
4418 if (ImGui::BeginMenu(settings.capitalMenuBar?_("File"):_("file"))) {
4419 if (ImGui::MenuItem(_("new..."),BIND_FOR(GUI_ACTION_NEW))) {
4420 if (modified) {
4421 showWarning(_("Unsaved changes! Save changes before creating a new song?"),GUI_WARN_NEW);
4422 } else {
4423 displayNew=true;
4424 }
4425 }
4426 if (ImGui::MenuItem(_("open..."),BIND_FOR(GUI_ACTION_OPEN))) {
4427 if (modified) {
4428 showWarning(_("Unsaved changes! Save changes before opening another file?"),GUI_WARN_OPEN);
4429 } else {
4430 openFileDialog(GUI_FILE_OPEN);
4431 }
4432 }
4433 if (ImGui::BeginMenu(_("open recent"))) {
4434 exitDisabledTimer=1;
4435 for (int i=0; i<(int)recentFile.size(); i++) {
4436 String item=recentFile[i];
4437 if (ImGui::MenuItem(item.c_str())) {
4438 if (modified) {
4439 nextFile=item;
4440 showWarning(_("Unsaved changes! Save changes before opening file?"),GUI_WARN_OPEN_DROP);
4441 } else {
4442 recentFile.erase(i);
4443 i--;
4444 }
4445 openRecentFile(item);
4446 }
4447 }
4448 if (recentFile.empty()) {
4449 ImGui::Text(_("nothing here yet"));
4450 } else {
4451 ImGui::Separator();
4452 if (ImGui::MenuItem(_("clear history"))) {
4453 showWarning(_("Are you sure you want to clear the recent file list?"),GUI_WARN_CLEAR_HISTORY);
4454 }
4455 }
4456 ImGui::EndMenu();
4457 }
4458 ImGui::Separator();
4459 if (ImGui::MenuItem(_("save"),BIND_FOR(GUI_ACTION_SAVE))) {
4460 if (curFileName=="" || (curFileName.find(backupPath)==0) || e->song.version>=0xff00) {
4461 openFileDialog(GUI_FILE_SAVE);
4462 } else {
4463 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
4464 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
4465 }
4466 }
4467 }
4468 if (ImGui::MenuItem(_("save as..."),BIND_FOR(GUI_ACTION_SAVE_AS))) {
4469 openFileDialog(GUI_FILE_SAVE);
4470 }
4471 ImGui::Separator();
4472 if (settings.exportOptionsLayout==0) {
4473 if (ImGui::BeginMenu(_("export audio..."))) {
4474 drawExportAudio();
4475 ImGui::EndMenu();
4476 }
4477 if (ImGui::BeginMenu(_("export VGM..."))) {
4478 drawExportVGM();
4479 ImGui::EndMenu();
4480 }
4481 if (romExportExists) {
4482 if (ImGui::BeginMenu(_("export ROM..."))) {
4483 drawExportROM();
4484 ImGui::EndMenu();
4485 }
4486 }
4487 if (ImGui::BeginMenu(_("export text..."))) {
4488 drawExportText();
4489 ImGui::EndMenu();
4490 }
4491 if (ImGui::BeginMenu(_("export command stream..."))) {
4492 drawExportCommand();
4493 ImGui::EndMenu();
4494 }
4495 if (ImGui::BeginMenu(_("export .dmf..."))) {
4496 drawExportDMF();
4497 ImGui::EndMenu();
4498 }
4499 } else if (settings.exportOptionsLayout==2) {
4500 if (ImGui::MenuItem(_("export audio..."))) {
4501 curExportType=GUI_EXPORT_AUDIO;
4502 displayExport=true;
4503 }
4504 if (ImGui::MenuItem(_("export VGM..."))) {
4505 curExportType=GUI_EXPORT_VGM;
4506 displayExport=true;
4507 }
4508 if (romExportExists) {
4509 if (ImGui::MenuItem(_("export ROM..."))) {
4510 curExportType=GUI_EXPORT_ROM;
4511 displayExport=true;
4512 }
4513 }
4514 if (ImGui::MenuItem(_("export text..."))) {
4515 curExportType=GUI_EXPORT_TEXT;
4516 displayExport=true;
4517 }
4518 if (ImGui::MenuItem(_("export command stream..."))) {
4519 curExportType=GUI_EXPORT_CMD_STREAM;
4520 displayExport=true;
4521 }
4522 if (ImGui::MenuItem(_("export .dmf..."))) {
4523 curExportType=GUI_EXPORT_DMF;
4524 displayExport=true;
4525 }
4526 } else {
4527 if (ImGui::MenuItem(_("export..."),BIND_FOR(GUI_ACTION_EXPORT))) {
4528 displayExport=true;
4529 }
4530 }
4531 ImGui::Separator();
4532 if (!settings.classicChipOptions) {
4533 if (ImGui::MenuItem(_("manage chips"))) {
4534 nextWindow=GUI_WINDOW_SYS_MANAGER;
4535 }
4536 } else {
4537 if (ImGui::BeginMenu(_("add chip..."))) {
4538 exitDisabledTimer=1;
4539 DivSystem picked=systemPicker(false);
4540 if (picked!=DIV_SYSTEM_NULL) {
4541 if (!e->addSystem(picked)) {
4542 showError(fmt::sprintf(_("cannot add chip! (%s)"),e->getLastError()));
4543 } else {
4544 MARK_MODIFIED;
4545 }
4546 ImGui::CloseCurrentPopup();
4547 if (e->song.autoSystem) {
4548 autoDetectSystem();
4549 }
4550 updateWindowTitle();
4551 updateROMExportAvail();
4552 }
4553 ImGui::EndMenu();
4554 }
4555 if (ImGui::BeginMenu(_("configure chip..."))) {
4556 exitDisabledTimer=1;
4557 for (int i=0; i<e->song.systemLen; i++) {
4558 if (ImGui::TreeNode(fmt::sprintf("%d. %s##_SYSP%d",i+1,getSystemName(e->song.system[i]),i).c_str())) {
4559 drawSysConf(i,i,e->song.system[i],e->song.systemFlags[i],true,true);
4560 ImGui::TreePop();
4561 }
4562 }
4563 ImGui::EndMenu();
4564 }
4565 if (ImGui::BeginMenu(_("change chip..."))) {
4566 exitDisabledTimer=1;
4567 ImGui::Checkbox(_("Preserve channel positions"),&preserveChanPos);
4568 for (int i=0; i<e->song.systemLen; i++) {
4569 if (ImGui::BeginMenu(fmt::sprintf("%d. %s##_SYSC%d",i+1,getSystemName(e->song.system[i]),i).c_str())) {
4570 DivSystem picked=systemPicker(false);
4571 if (picked!=DIV_SYSTEM_NULL) {
4572 if (e->changeSystem(i,picked,preserveChanPos)) {
4573 MARK_MODIFIED;
4574 if (e->song.autoSystem) {
4575 autoDetectSystem();
4576 }
4577 updateWindowTitle();
4578 updateROMExportAvail();
4579 } else {
4580 showError(fmt::sprintf(_("cannot change chip! (%s)"),e->getLastError()));
4581 }
4582 ImGui::CloseCurrentPopup();
4583 }
4584 ImGui::EndMenu();
4585 }
4586 }
4587 ImGui::EndMenu();
4588 }
4589 if (ImGui::BeginMenu(_("remove chip..."))) {
4590 exitDisabledTimer=1;
4591 ImGui::Checkbox(_("Preserve channel positions"),&preserveChanPos);
4592 for (int i=0; i<e->song.systemLen; i++) {
4593 if (ImGui::MenuItem(fmt::sprintf("%d. %s##_SYSR%d",i+1,getSystemName(e->song.system[i]),i).c_str())) {
4594 if (!e->removeSystem(i,preserveChanPos)) {
4595 showError(fmt::sprintf(_("cannot remove chip! (%s)"),e->getLastError()));
4596 } else {
4597 MARK_MODIFIED;
4598 }
4599 if (e->song.autoSystem) {
4600 autoDetectSystem();
4601 updateWindowTitle();
4602 }
4603 updateROMExportAvail();
4604 }
4605 }
4606 ImGui::EndMenu();
4607 }
4608 }
4609 #if defined(FURNACE_DATADIR) && defined(SHOW_OPEN_ASSETS_MENU_ENTRY)
4610 if (ImGui::MenuItem(_("open built-in assets directory"))) {
4611 SDL_OpenURL("file://" FURNACE_DATADIR);
4612 }
4613 #endif
4614 ImGui::BeginDisabled(exitDisabledTimer);
4615 ImGui::Separator();
4616 if (ImGui::MenuItem(_("restore backup"),BIND_FOR(GUI_ACTION_OPEN_BACKUP))) {
4617 doAction(GUI_ACTION_OPEN_BACKUP);
4618 }
4619 ImGui::Separator();
4620 if (ImGui::MenuItem(_("exit..."),BIND_FOR(GUI_ACTION_QUIT))) {
4621 requestQuit();
4622 }
4623 ImGui::EndDisabled();
4624 ImGui::EndMenu();
4625 } else {
4626 exitDisabledTimer=0;
4627 }
4628 if (ImGui::BeginMenu(settings.capitalMenuBar?_("Edit"):_("edit"))) {
4629 ImGui::Text("...");
4630 ImGui::Separator();
4631 if (ImGui::MenuItem(_("undo"),BIND_FOR(GUI_ACTION_UNDO))) doUndo();
4632 if (ImGui::MenuItem(_("redo"),BIND_FOR(GUI_ACTION_REDO))) doRedo();
4633 ImGui::Separator();
4634 editOptions(true);
4635 ImGui::Separator();
4636 if (ImGui::MenuItem(_("clear..."))) {
4637 doAction(GUI_ACTION_CLEAR);
4638 }
4639 ImGui::EndMenu();
4640 }
4641 if (ImGui::BeginMenu(settings.capitalMenuBar?_("Settings"):_("settings"))) {
4642 #ifndef IS_MOBILE
4643 if (ImGui::MenuItem(_("full screen"),BIND_FOR(GUI_ACTION_FULLSCREEN),fullScreen)) {
4644 doAction(GUI_ACTION_FULLSCREEN);
4645 }
4646 #endif
4647 if (ImGui::MenuItem(_("lock layout"),NULL,lockLayout)) {
4648 lockLayout=!lockLayout;
4649 }
4650 if (ImGui::MenuItem(_("pattern visualizer"),NULL,fancyPattern)) {
4651 fancyPattern=!fancyPattern;
4652 e->enableCommandStream(fancyPattern);
4653 e->getCommandStream(cmdStream);
4654 cmdStream.clear();
4655 }
4656 if (ImGui::MenuItem(_("reset layout"))) {
4657 showWarning(_("Are you sure you want to reset the workspace layout?"),GUI_WARN_RESET_LAYOUT);
4658 }
4659 #ifdef IS_MOBILE
4660 if (ImGui::MenuItem(_("switch to mobile view"))) {
4661 toggleMobileUI(!mobileUI);
4662 }
4663 #endif
4664 if (ImGui::MenuItem(_("user systems..."),BIND_FOR(GUI_ACTION_WINDOW_USER_PRESETS))) {
4665 userPresetsOpen=true;
4666 }
4667 if (ImGui::MenuItem(_("settings..."),BIND_FOR(GUI_ACTION_WINDOW_SETTINGS))) {
4668 syncSettings();
4669 settingsOpen=true;
4670 }
4671 ImGui::EndMenu();
4672 }
4673 if (ImGui::BeginMenu(settings.capitalMenuBar?_("Window"):_("window"))) {
4674 if (ImGui::BeginMenu(_("song"))) {
4675 if (ImGui::MenuItem(_("song comments"), BIND_FOR(GUI_ACTION_WINDOW_NOTES), notesOpen)) notesOpen = !notesOpen;
4676 if (ImGui::MenuItem(_("song information"), BIND_FOR(GUI_ACTION_WINDOW_SONG_INFO), songInfoOpen)) songInfoOpen = !songInfoOpen;
4677 if (ImGui::MenuItem(_("subsongs"), BIND_FOR(GUI_ACTION_WINDOW_SUBSONGS), subSongsOpen)) subSongsOpen = !subSongsOpen;
4678 ImGui::Separator();
4679 if (ImGui::MenuItem(_("channels"),BIND_FOR(GUI_ACTION_WINDOW_CHANNELS),channelsOpen)) channelsOpen=!channelsOpen;
4680 if (ImGui::MenuItem(_("chip manager"),BIND_FOR(GUI_ACTION_WINDOW_SYS_MANAGER),sysManagerOpen)) sysManagerOpen=!sysManagerOpen;
4681 if (ImGui::MenuItem(_("orders"),BIND_FOR(GUI_ACTION_WINDOW_ORDERS),ordersOpen)) ordersOpen=!ordersOpen;
4682 if (ImGui::MenuItem(_("pattern"),BIND_FOR(GUI_ACTION_WINDOW_PATTERN),patternOpen)) patternOpen=!patternOpen;
4683 if (ImGui::MenuItem(_("pattern manager"),BIND_FOR(GUI_ACTION_WINDOW_PAT_MANAGER),patManagerOpen)) patManagerOpen=!patManagerOpen;
4684 if (ImGui::MenuItem(_("mixer"),BIND_FOR(GUI_ACTION_WINDOW_MIXER),mixerOpen)) mixerOpen=!mixerOpen;
4685 if (ImGui::MenuItem(_("compatibility flags"),BIND_FOR(GUI_ACTION_WINDOW_COMPAT_FLAGS),compatFlagsOpen)) compatFlagsOpen=!compatFlagsOpen;
4686 ImGui::EndMenu();
4687 }
4688 if (ImGui::BeginMenu(_("assets"))) {
4689 if (settings.unifiedDataView) {
4690 if (ImGui::MenuItem(_("assets"), BIND_FOR(GUI_ACTION_WINDOW_INS_LIST), insListOpen)) insListOpen = !insListOpen;
4691 } else {
4692 if (ImGui::MenuItem(_("instruments"), BIND_FOR(GUI_ACTION_WINDOW_INS_LIST), insListOpen)) insListOpen = !insListOpen;
4693 if (ImGui::MenuItem(_("samples"), BIND_FOR(GUI_ACTION_WINDOW_SAMPLE_LIST), sampleListOpen)) sampleListOpen = !sampleListOpen;
4694 if (ImGui::MenuItem(_("wavetables"), BIND_FOR(GUI_ACTION_WINDOW_WAVE_LIST), waveListOpen)) waveListOpen = !waveListOpen;
4695 }
4696 ImGui::Separator();
4697 if (ImGui::MenuItem(_("instrument editor"), BIND_FOR(GUI_ACTION_WINDOW_INS_EDIT), insEditOpen)) insEditOpen = !insEditOpen;
4698 if (ImGui::MenuItem(_("sample editor"), BIND_FOR(GUI_ACTION_WINDOW_SAMPLE_EDIT), sampleEditOpen)) sampleEditOpen = !sampleEditOpen;
4699 if (ImGui::MenuItem(_("wavetable editor"), BIND_FOR(GUI_ACTION_WINDOW_WAVE_EDIT), waveEditOpen)) waveEditOpen = !waveEditOpen;
4700 ImGui::EndMenu();
4701 }
4702 if (ImGui::BeginMenu(_("visualizers"))) {
4703 if (ImGui::MenuItem(_("oscilloscope (master)"),BIND_FOR(GUI_ACTION_WINDOW_OSCILLOSCOPE),oscOpen)) oscOpen=!oscOpen;
4704 if (ImGui::MenuItem(_("oscilloscope (per-channel)"),BIND_FOR(GUI_ACTION_WINDOW_CHAN_OSC),chanOscOpen)) chanOscOpen=!chanOscOpen;
4705 if (ImGui::MenuItem(_("oscilloscope (X-Y)"),BIND_FOR(GUI_ACTION_WINDOW_XY_OSC),xyOscOpen)) xyOscOpen=!xyOscOpen;
4706 if (ImGui::MenuItem(_("volume meter"),BIND_FOR(GUI_ACTION_WINDOW_VOL_METER),volMeterOpen)) volMeterOpen=!volMeterOpen;
4707 ImGui::EndMenu();
4708 }
4709 if (ImGui::BeginMenu(_("tempo"))) {
4710 if (ImGui::MenuItem(_("clock"),BIND_FOR(GUI_ACTION_WINDOW_CLOCK),clockOpen)) clockOpen=!clockOpen;
4711 if (ImGui::MenuItem(_("grooves"),BIND_FOR(GUI_ACTION_WINDOW_GROOVES),groovesOpen)) groovesOpen=!groovesOpen;
4712 if (ImGui::MenuItem(_("speed"),BIND_FOR(GUI_ACTION_WINDOW_SPEED),speedOpen)) speedOpen=!speedOpen;
4713 ImGui::EndMenu();
4714 }
4715 if (ImGui::BeginMenu(_("debug"))) {
4716 if (ImGui::MenuItem(_("log viewer"),BIND_FOR(GUI_ACTION_WINDOW_LOG),logOpen)) logOpen=!logOpen;
4717 if (ImGui::MenuItem(_("register view"),BIND_FOR(GUI_ACTION_WINDOW_REGISTER_VIEW),regViewOpen)) regViewOpen=!regViewOpen;
4718 if (ImGui::MenuItem(_("statistics"),BIND_FOR(GUI_ACTION_WINDOW_STATS),statsOpen)) statsOpen=!statsOpen;
4719 if (ImGui::MenuItem(_("memory composition"),BIND_FOR(GUI_ACTION_WINDOW_MEMORY),memoryOpen)) memoryOpen=!memoryOpen;
4720 if (ImGui::MenuItem(_("command stream player"),BIND_FOR(GUI_ACTION_WINDOW_CS_PLAYER),csPlayerOpen)) csPlayerOpen=!csPlayerOpen;
4721 ImGui::EndMenu();
4722 }
4723 ImGui::Separator();
4724 if (ImGui::MenuItem(_("effect list"),BIND_FOR(GUI_ACTION_WINDOW_EFFECT_LIST),effectListOpen)) effectListOpen=!effectListOpen;
4725 if (ImGui::MenuItem(_("play/edit controls"),BIND_FOR(GUI_ACTION_WINDOW_EDIT_CONTROLS),editControlsOpen)) editControlsOpen=!editControlsOpen;
4726 if (ImGui::MenuItem(_("piano/input pad"),BIND_FOR(GUI_ACTION_WINDOW_PIANO),pianoOpen)) pianoOpen=!pianoOpen;
4727 if (spoilerOpen) if (ImGui::MenuItem(_("spoiler"),NULL,spoilerOpen)) spoilerOpen=!spoilerOpen;
4728
4729 ImGui::EndMenu();
4730 }
4731 if (ImGui::BeginMenu(settings.capitalMenuBar?_("Help"):_("help"))) {
4732 if (ImGui::MenuItem(_("effect list"),BIND_FOR(GUI_ACTION_WINDOW_EFFECT_LIST),effectListOpen)) effectListOpen=!effectListOpen;
4733 if (ImGui::MenuItem(_("debug menu"),BIND_FOR(GUI_ACTION_WINDOW_DEBUG))) debugOpen=!debugOpen;
4734 if (ImGui::MenuItem(_("inspector"))) inspectorOpen=!inspectorOpen;
4735 if (ImGui::MenuItem(_("panic"),BIND_FOR(GUI_ACTION_PANIC))) e->syncReset();
4736 if (ImGui::MenuItem(_("welcome screen"))) tutorial.protoWelcome=false;
4737 if (ImGui::MenuItem(_("about..."),BIND_FOR(GUI_ACTION_WINDOW_ABOUT))) {
4738 aboutOpen=true;
4739 aboutScroll=0;
4740 }
4741 ImGui::EndMenu();
4742 }
4743 ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PLAYBACK_STAT]);
4744 if (e->isPlaying() && settings.playbackTime) {
4745 int totalTicks=e->getTotalTicks();
4746 int totalSeconds=e->getTotalSeconds();
4747
4748 String info;
4749
4750 DivGroovePattern gp=e->getSpeeds();
4751 if (gp.len==2) {
4752 info=fmt::sprintf(_("| Speed %d:%d"),gp.val[0],gp.val[1]);
4753 } else if (gp.len==1) {
4754 info=fmt::sprintf(_("| Speed %d"),gp.val[0]);
4755 } else {
4756 info=_("| Groove");
4757 }
4758
4759 info+=fmt::sprintf(_(" @ %gHz (%g BPM) "),e->getCurHz(),calcBPM(e->getSpeeds(),e->getCurHz(),e->getVirtualTempoN(),e->getVirtualTempoD()));
4760
4761 if (settings.orderRowsBase) {
4762 info+=fmt::sprintf(_("| Order %.2X/%.2X "),playOrder,e->curSubSong->ordersLen-1);
4763 } else {
4764 info+=fmt::sprintf(_("| Order %d/%d "),playOrder,e->curSubSong->ordersLen-1);
4765 }
4766
4767 if (settings.patRowsBase) {
4768 info+=fmt::sprintf(_("| Row %.2X/%.2X "),oldRow,e->curSubSong->patLen);
4769 } else {
4770 info+=fmt::sprintf(_("| Row %d/%d "),oldRow,e->curSubSong->patLen);
4771 }
4772
4773 info+=_("| ");
4774
4775 if (totalSeconds==0x7fffffff) {
4776 info+=_("Don't you have anything better to do?");
4777 } else {
4778 if (totalSeconds>=86400) {
4779 int totalDays=totalSeconds/86400;
4780 int totalYears=totalDays/365;
4781 totalDays%=365;
4782 int totalMonths=totalDays/30;
4783 totalDays%=30;
4784
4785 #ifdef HAVE_LOCALE
4786 info+=fmt::sprintf(ngettext("%d year ","%d years ",totalYears),totalYears);
4787 info+=fmt::sprintf(ngettext("%d month ","%d months ",totalMonths),totalMonths);
4788 info+=fmt::sprintf(ngettext("%d day ","%d days ",totalDays),totalDays);
4789 #else
4790 info+=fmt::sprintf(_GN("%d year ","%d years ",totalYears),totalYears);
4791 info+=fmt::sprintf(_GN("%d month ","%d months ",totalMonths),totalMonths);
4792 info+=fmt::sprintf(_GN("%d day ","%d days ",totalDays),totalDays);
4793 #endif
4794 }
4795
4796 if (totalSeconds>=3600) {
4797 info+=fmt::sprintf("%.2d:",(totalSeconds/3600)%24);
4798 }
4799
4800 info+=fmt::sprintf("%.2d:%.2d.%.2d",(totalSeconds/60)%60,totalSeconds%60,totalTicks/10000);
4801 }
4802
4803 ImGui::TextUnformatted(info.c_str());
4804 } else {
4805 bool hasInfo=false;
4806 String info;
4807 if (cursor.xCoarse>=0 && cursor.xCoarse<e->getTotalChannelCount()) {
4808 DivPattern* p=e->curPat[cursor.xCoarse].getPattern(e->curOrders->ord[cursor.xCoarse][curOrder],false);
4809 if (cursor.xFine>=0) switch (cursor.xFine) {
4810 case 0: // note
4811 if (p->data[cursor.y][0]>0) {
4812 if (p->data[cursor.y][0]==100) {
4813 info=fmt::sprintf(_("Note off (cut)"));
4814 } else if (p->data[cursor.y][0]==101) {
4815 info=fmt::sprintf(_("Note off (release)"));
4816 } else if (p->data[cursor.y][0]==102) {
4817 info=fmt::sprintf(_("Macro release only"));
4818 } else {
4819 info=fmt::sprintf(_("Note on: %s"),noteName(p->data[cursor.y][0],p->data[cursor.y][1]));
4820 }
4821 hasInfo=true;
4822 }
4823 break;
4824 case 1: // instrument
4825 if (p->data[cursor.y][2]>-1) {
4826 if (p->data[cursor.y][2]>=(int)e->song.ins.size()) {
4827 info=fmt::sprintf(_("Ins %d: <invalid>"),p->data[cursor.y][2]);
4828 } else {
4829 DivInstrument* ins=e->getIns(p->data[cursor.y][2]);
4830 info=fmt::sprintf(_("Ins %d: %s"),p->data[cursor.y][2],ins->name);
4831 }
4832 hasInfo=true;
4833 }
4834 break;
4835 case 2: // volume
4836 if (p->data[cursor.y][3]>-1) {
4837 int maxVol=e->getMaxVolumeChan(cursor.xCoarse);
4838 if (maxVol<1 || p->data[cursor.y][3]>maxVol) {
4839 info=fmt::sprintf(_("Set volume: %d (%.2X, INVALID!)"),p->data[cursor.y][3],p->data[cursor.y][3]);
4840 } else {
4841 float realVol=e->getGain(cursor.xCoarse,p->data[cursor.y][3]);
4842 info=fmt::sprintf(_("Set volume: %d (%.2X, %d%%)"),p->data[cursor.y][3],p->data[cursor.y][3],(int)(realVol*100.0f));
4843 }
4844 hasInfo=true;
4845 }
4846 break;
4847 default: // effect
4848 int actualCursor=((cursor.xFine+1)&(~1));
4849 if (p->data[cursor.y][actualCursor]>-1) {
4850 info=e->getEffectDesc(p->data[cursor.y][actualCursor],cursor.xCoarse,true);
4851 hasInfo=true;
4852 }
4853 break;
4854 }
4855 }
4856 if (hasInfo && (settings.statusDisplay==0 || settings.statusDisplay==2)) {
4857 ImGui::Text("| %s",info.c_str());
4858 } else if (settings.statusDisplay==1 || settings.statusDisplay==2) {
4859 if (curFileName!="") ImGui::Text("| %s",curFileName.c_str());
4860 }
4861 }
4862 ImGui::PopStyleColor();
4863 if (modified) {
4864 ImGui::Text(_("| modified"));
4865 }
4866 ImGui::EndMainMenuBar();
4867 }
4868
4869 MEASURE(calcChanOsc,calcChanOsc());
4870
4871 if (mobileUI) {
4872 globalWinFlags=ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoBringToFrontOnFocus;
4873 //globalWinFlags=ImGuiWindowFlags_NoTitleBar;
4874 // scene handling goes here!
4875 MEASURE(mobileControls,drawMobileControls());
4876 switch (mobScene) {
4877 case GUI_SCENE_ORDERS:
4878 ordersOpen=true;
4879 curWindow=GUI_WINDOW_ORDERS;
4880 MEASURE(orders,drawOrders());
4881 MEASURE(piano,drawPiano());
4882 break;
4883 case GUI_SCENE_INSTRUMENT:
4884 insEditOpen=true;
4885 curWindow=GUI_WINDOW_INS_EDIT;
4886 MEASURE(insEdit,drawInsEdit());
4887 MEASURE(piano,drawPiano());
4888 break;
4889 case GUI_SCENE_WAVETABLE:
4890 waveEditOpen=true;
4891 curWindow=GUI_WINDOW_WAVE_EDIT;
4892 MEASURE(waveEdit,drawWaveEdit());
4893 MEASURE(piano,drawPiano());
4894 break;
4895 case GUI_SCENE_SAMPLE:
4896 sampleEditOpen=true;
4897 curWindow=GUI_WINDOW_SAMPLE_EDIT;
4898 MEASURE(sampleEdit,drawSampleEdit());
4899 MEASURE(piano,drawPiano());
4900 break;
4901 case GUI_SCENE_CHANNELS:
4902 channelsOpen=true;
4903 curWindow=GUI_WINDOW_CHANNELS;
4904 MEASURE(channels,drawChannels());
4905 break;
4906 case GUI_SCENE_CHIPS:
4907 sysManagerOpen=true;
4908 curWindow=GUI_WINDOW_SYS_MANAGER;
4909 MEASURE(sysManager,drawSysManager());
4910 break;
4911 case GUI_SCENE_MIXER:
4912 mixerOpen=true;
4913 curWindow=GUI_WINDOW_MIXER;
4914 MEASURE(mixer,drawMixer());
4915 break;
4916 default:
4917 patternOpen=true;
4918 curWindow=GUI_WINDOW_PATTERN;
4919 MEASURE(pattern,drawPattern());
4920 MEASURE(piano,drawPiano());
4921 MEASURE(mobileOrderSel,drawMobileOrderSel());
4922
4923 globalWinFlags=0;
4924 MEASURE(findReplace,drawFindReplace());
4925 break;
4926 }
4927
4928 globalWinFlags=0;
4929 MEASURE(settings,drawSettings());
4930 MEASURE(debug,drawDebug());
4931 MEASURE(csPlayer,drawCSPlayer());
4932 MEASURE(log,drawLog());
4933 MEASURE(compatFlags,drawCompatFlags());
4934 MEASURE(stats,drawStats());
4935 MEASURE(readOsc,readOsc());
4936 MEASURE(osc,drawOsc());
4937 MEASURE(chanOsc,drawChanOsc());
4938 MEASURE(xyOsc,drawXYOsc());
4939 MEASURE(volMeter,drawVolMeter());
4940 MEASURE(grooves,drawGrooves());
4941 MEASURE(regView,drawRegView());
4942 MEASURE(memory,drawMemory());
4943 MEASURE(effectList,drawEffectList());
4944 MEASURE(userPresets,drawUserPresets());
4945 MEASURE(patManager,drawPatManager());
4946 } else {
4947 globalWinFlags=0;
4948 ImGui::DockSpaceOverViewport(0,NULL,lockLayout?(ImGuiDockNodeFlags_NoWindowMenuButton|ImGuiDockNodeFlags_NoMove|ImGuiDockNodeFlags_NoResize|ImGuiDockNodeFlags_NoCloseButton|ImGuiDockNodeFlags_NoDocking|ImGuiDockNodeFlags_NoDockingSplit|ImGuiDockNodeFlags_NoDockingSplitOther):0);
4949
4950 MEASURE(subSongs,drawSubSongs());
4951 MEASURE(findReplace,drawFindReplace());
4952 MEASURE(spoiler,drawSpoiler());
4953 MEASURE(pattern,drawPattern());
4954 MEASURE(editControls,drawEditControls());
4955 MEASURE(speed,drawSpeed());
4956 MEASURE(grooves,drawGrooves());
4957 MEASURE(songInfo,drawSongInfo());
4958 MEASURE(orders,drawOrders());
4959 MEASURE(sampleList,drawSampleList());
4960 MEASURE(sampleEdit,drawSampleEdit());
4961 MEASURE(waveList,drawWaveList());
4962 MEASURE(waveEdit,drawWaveEdit());
4963 MEASURE(insList,drawInsList());
4964 MEASURE(insEdit,drawInsEdit());
4965 MEASURE(mixer,drawMixer());
4966
4967 MEASURE(readOsc,readOsc());
4968
4969 MEASURE(osc,drawOsc());
4970 MEASURE(chanOsc,drawChanOsc());
4971 MEASURE(xyOsc,drawXYOsc());
4972 MEASURE(volMeter,drawVolMeter());
4973 MEASURE(settings,drawSettings());
4974 MEASURE(debug,drawDebug());
4975 MEASURE(csPlayer,drawCSPlayer());
4976 MEASURE(stats,drawStats());
4977 MEASURE(memory,drawMemory());
4978 MEASURE(compatFlags,drawCompatFlags());
4979 MEASURE(piano,drawPiano());
4980 MEASURE(notes,drawNotes());
4981 MEASURE(channels,drawChannels());
4982 MEASURE(patManager,drawPatManager());
4983 MEASURE(sysManager,drawSysManager());
4984 MEASURE(clock,drawClock());
4985 MEASURE(regView,drawRegView());
4986 MEASURE(log,drawLog());
4987 MEASURE(effectList,drawEffectList());
4988 MEASURE(userPresets,drawUserPresets());
4989 }
4990
4991 // release selection if mouse released
4992 if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && selecting) {
4993 if (!selectingFull) cursor=selEnd;
4994 finishSelection();
4995 if (!mobileUI) {
4996 demandScrollX=true;
4997 if (cursor.xCoarse==selStart.xCoarse && cursor.xFine==selStart.xFine && cursor.y==selStart.y && cursor.order==selStart.order &&
4998 cursor.xCoarse==selEnd.xCoarse && cursor.xFine==selEnd.xFine && cursor.y==selEnd.y && cursor.order==selEnd.order) {
4999 if (!settings.cursorMoveNoScroll) {
5000 updateScroll(cursor.y);
5001 }
5002 }
5003 }
5004 }
5005
5006 for (int i=0; i<e->getTotalChannelCount(); i++) {
5007 keyHit1[i]-=0.2f;
5008 if (keyHit1[i]<0.0f) keyHit1[i]=0.0f;
5009 }
5010
5011 if (inspectorOpen) ImGui::ShowMetricsWindow(&inspectorOpen);
5012
5013 if (firstFrame) {
5014 firstFrame=false;
5015 #ifdef IS_MOBILE
5016 SDL_GetWindowSize(sdlWin,&scrW,&scrH);
5017 portrait=(scrW<scrH);
5018 logV("portrait: %d (%dx%d)",portrait,scrW,scrH);
5019
5020 rend->getOutputSize(canvasW,canvasH);
5021 #endif
5022 if (patternOpen) nextWindow=GUI_WINDOW_PATTERN;
5023 #ifdef __APPLE__
5024 SDL_RaiseWindow(sdlWin);
5025 #endif
5026 }
5027
5028 #ifndef NFD_NON_THREADED
5029 #ifndef FLATPAK_WORKAROUNDS
5030 if (fileDialog->isOpen() && settings.sysFileDialog) {
5031 ImGui::OpenPopup(_("System File Dialog Pending"));
5032 }
5033
5034 if (ImGui::BeginPopupModal(_("System File Dialog Pending"),NULL,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoBackground|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove)) {
5035 if (!fileDialog->isOpen()) {
5036 ImGui::CloseCurrentPopup();
5037 }
5038 ImDrawList* dl=ImGui::GetForegroundDrawList();
5039 dl->AddRectFilled(ImVec2(0.0f,0.0f),ImVec2(canvasW,canvasH),ImGui::ColorConvertFloat4ToU32(uiColors[GUI_COLOR_MODAL_BACKDROP]));
5040 ImGui::EndPopup();
5041 }
5042 #endif
5043 #endif
5044
5045 if (fileDialog->render(mobileUI?ImVec2(canvasW-(portrait?0:(60.0*dpiScale)),canvasH-60.0*dpiScale):ImVec2(600.0f*dpiScale,400.0f*dpiScale),ImVec2(canvasW-((mobileUI && !portrait)?(60.0*dpiScale):0),canvasH-(mobileUI?(60.0*dpiScale):0)))) {
5046 bool openOpen=false;
5047 //ImGui::GetIO().ConfigFlags&=~ImGuiConfigFlags_NavEnableKeyboard;
5048 if ((curFileDialog==GUI_FILE_INS_OPEN || curFileDialog==GUI_FILE_INS_OPEN_REPLACE) && prevIns!=-3) {
5049 if (curFileDialog==GUI_FILE_INS_OPEN_REPLACE) {
5050 if (prevInsData!=NULL) {
5051 if (prevIns>=0 && prevIns<(int)e->song.ins.size()) {
5052 *e->song.ins[prevIns]=*prevInsData;
5053 }
5054 }
5055 } else {
5056 curIns=prevIns;
5057 wavePreviewInit=true;
5058 updateFMPreview=true;
5059 }
5060 prevIns=-3;
5061 }
5062 switch (curFileDialog) {
5063 case GUI_FILE_OPEN:
5064 case GUI_FILE_SAVE:
5065 case GUI_FILE_SAVE_DMF:
5066 case GUI_FILE_SAVE_DMF_LEGACY:
5067 workingDirSong=fileDialog->getPath()+DIR_SEPARATOR_STR;
5068 break;
5069 case GUI_FILE_INS_OPEN:
5070 case GUI_FILE_INS_OPEN_REPLACE:
5071 case GUI_FILE_INS_SAVE:
5072 case GUI_FILE_INS_SAVE_DMP:
5073 case GUI_FILE_INS_SAVE_ALL:
5074 workingDirIns=fileDialog->getPath()+DIR_SEPARATOR_STR;
5075 break;
5076 case GUI_FILE_WAVE_OPEN:
5077 case GUI_FILE_WAVE_OPEN_REPLACE:
5078 case GUI_FILE_WAVE_SAVE:
5079 case GUI_FILE_WAVE_SAVE_DMW:
5080 case GUI_FILE_WAVE_SAVE_RAW:
5081 case GUI_FILE_WAVE_SAVE_ALL:
5082 workingDirWave=fileDialog->getPath()+DIR_SEPARATOR_STR;
5083 break;
5084 case GUI_FILE_SAMPLE_OPEN:
5085 case GUI_FILE_SAMPLE_OPEN_RAW:
5086 case GUI_FILE_SAMPLE_OPEN_REPLACE:
5087 case GUI_FILE_SAMPLE_OPEN_REPLACE_RAW:
5088 case GUI_FILE_SAMPLE_SAVE:
5089 case GUI_FILE_SAMPLE_SAVE_RAW:
5090 case GUI_FILE_SAMPLE_SAVE_ALL:
5091 workingDirSample=fileDialog->getPath()+DIR_SEPARATOR_STR;
5092 break;
5093 case GUI_FILE_EXPORT_AUDIO_ONE:
5094 case GUI_FILE_EXPORT_AUDIO_PER_SYS:
5095 case GUI_FILE_EXPORT_AUDIO_PER_CHANNEL:
5096 workingDirAudioExport=fileDialog->getPath()+DIR_SEPARATOR_STR;
5097 break;
5098 case GUI_FILE_EXPORT_VGM:
5099 workingDirVGMExport=fileDialog->getPath()+DIR_SEPARATOR_STR;
5100 break;
5101 case GUI_FILE_EXPORT_ROM:
5102 case GUI_FILE_EXPORT_TEXT:
5103 case GUI_FILE_EXPORT_CMDSTREAM:
5104 workingDirROMExport=fileDialog->getPath()+DIR_SEPARATOR_STR;
5105 break;
5106 case GUI_FILE_LOAD_MAIN_FONT:
5107 case GUI_FILE_LOAD_HEAD_FONT:
5108 case GUI_FILE_LOAD_PAT_FONT:
5109 workingDirFont=fileDialog->getPath()+DIR_SEPARATOR_STR;
5110 break;
5111 case GUI_FILE_IMPORT_COLORS:
5112 case GUI_FILE_EXPORT_COLORS:
5113 workingDirColors=fileDialog->getPath()+DIR_SEPARATOR_STR;
5114 break;
5115 case GUI_FILE_IMPORT_KEYBINDS:
5116 case GUI_FILE_EXPORT_KEYBINDS:
5117 workingDirKeybinds=fileDialog->getPath()+DIR_SEPARATOR_STR;
5118 break;
5119 case GUI_FILE_IMPORT_LAYOUT:
5120 case GUI_FILE_EXPORT_LAYOUT:
5121 workingDirLayout=fileDialog->getPath()+DIR_SEPARATOR_STR;
5122 break;
5123 case GUI_FILE_IMPORT_USER_PRESETS:
5124 case GUI_FILE_IMPORT_USER_PRESETS_REPLACE:
5125 case GUI_FILE_EXPORT_USER_PRESETS:
5126 case GUI_FILE_IMPORT_CONFIG:
5127 case GUI_FILE_EXPORT_CONFIG:
5128 workingDirConfig=fileDialog->getPath()+DIR_SEPARATOR_STR;
5129 break;
5130 case GUI_FILE_YRW801_ROM_OPEN:
5131 case GUI_FILE_TG100_ROM_OPEN:
5132 case GUI_FILE_MU5_ROM_OPEN:
5133 workingDirROM=fileDialog->getPath()+DIR_SEPARATOR_STR;
5134 break;
5135 case GUI_FILE_CMDSTREAM_OPEN:
5136 workingDirROM=fileDialog->getPath()+DIR_SEPARATOR_STR;
5137 break;
5138 case GUI_FILE_TEST_OPEN:
5139 case GUI_FILE_TEST_OPEN_MULTI:
5140 case GUI_FILE_TEST_SAVE:
5141 workingDirTest=fileDialog->getPath()+DIR_SEPARATOR_STR;
5142 break;
5143 case GUI_FILE_OPEN_BACKUP:
5144 break;
5145 }
5146 if (fileDialog->isError()) {
5147 #if defined(_WIN32) || defined(__APPLE__)
5148 showError(_("there was an error in the file dialog! you may want to report this issue to:\nhttps://github.com/tildearrow/furnace/issues\ncheck the Log Viewer (window > log viewer) for more information.\n\nfor now please disable the system file picker in Settings > General."));
5149 #else
5150 #ifdef ANDROID
5151 showError(_("can't do anything without Storage permissions!"));
5152 #else
5153 showError(_("Zenity/KDialog not available!\nplease install one of these, or disable the system file picker in Settings > General."));
5154 #endif
5155 #endif
5156 }
5157 if (fileDialog->accepted()) {
5158 if (fileDialog->getFileName().empty()) {
5159 fileName="";
5160 } else {
5161 fileName=fileDialog->getFileName()[0];
5162 }
5163 if (fileName!="") {
5164 if (curFileDialog==GUI_FILE_SAVE) {
5165 checkExtension(".fur");
5166 }
5167 if (curFileDialog==GUI_FILE_SAVE_DMF) {
5168 checkExtension(".dmf");
5169 }
5170 if (curFileDialog==GUI_FILE_SAVE_DMF_LEGACY) {
5171 checkExtension(".dmf");
5172 }
5173 if (curFileDialog==GUI_FILE_SAMPLE_SAVE ||
5174 curFileDialog==GUI_FILE_EXPORT_AUDIO_ONE ||
5175 curFileDialog==GUI_FILE_EXPORT_AUDIO_PER_SYS ||
5176 curFileDialog==GUI_FILE_EXPORT_AUDIO_PER_CHANNEL) {
5177 checkExtension(".wav");
5178 }
5179 if (curFileDialog==GUI_FILE_INS_SAVE) {
5180 checkExtension(".fui");
5181 }
5182 if (curFileDialog==GUI_FILE_INS_SAVE_DMP) {
5183 checkExtension(".dmp");
5184 }
5185 if (curFileDialog==GUI_FILE_WAVE_SAVE) {
5186 checkExtension(".fuw");
5187 }
5188 if (curFileDialog==GUI_FILE_WAVE_SAVE_DMW) {
5189 checkExtension(".dmw");
5190 }
5191 if (curFileDialog==GUI_FILE_WAVE_SAVE_RAW) {
5192 checkExtension(".raw");
5193 }
5194 if (curFileDialog==GUI_FILE_EXPORT_VGM) {
5195 checkExtension(".vgm");
5196 }
5197 if (curFileDialog==GUI_FILE_EXPORT_ROM) {
5198 checkExtension(romFilterExt.c_str());
5199 }
5200 if (curFileDialog==GUI_FILE_EXPORT_TEXT) {
5201 checkExtension(".txt");
5202 }
5203 if (curFileDialog==GUI_FILE_EXPORT_CMDSTREAM) {
5204 checkExtension(".bin");
5205 }
5206 if (curFileDialog==GUI_FILE_EXPORT_COLORS) {
5207 checkExtension(".cfgc");
5208 }
5209 if (curFileDialog==GUI_FILE_EXPORT_KEYBINDS) {
5210 checkExtension(".cfgk");
5211 }
5212 if (curFileDialog==GUI_FILE_EXPORT_LAYOUT) {
5213 checkExtension(".ini");
5214 }
5215 if (curFileDialog==GUI_FILE_EXPORT_USER_PRESETS) {
5216 checkExtension(".cfgu");
5217 }
5218 if (curFileDialog==GUI_FILE_EXPORT_CONFIG) {
5219 checkExtension(".cfg");
5220 }
5221 String copyOfName=fileName;
5222 switch (curFileDialog) {
5223 case GUI_FILE_OPEN:
5224 case GUI_FILE_OPEN_BACKUP:
5225 if (load(copyOfName)>0) {
5226 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
5227 }
5228 break;
5229 case GUI_FILE_SAVE: {
5230 bool saveWasSuccessful=true;
5231 if (save(copyOfName,0)>0) {
5232 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
5233 saveWasSuccessful=false;
5234 }
5235 if (saveWasSuccessful && postWarnAction!=GUI_WARN_GENERIC) {
5236 switch (postWarnAction) {
5237 case GUI_WARN_QUIT:
5238 quit=true;
5239 break;
5240 case GUI_WARN_NEW:
5241 displayNew=true;
5242 break;
5243 case GUI_WARN_OPEN:
5244 openOpen=true;
5245 break;
5246 case GUI_WARN_OPEN_DROP:
5247 if (load(nextFile)>0) {
5248 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
5249 }
5250 nextFile="";
5251 break;
5252 case GUI_WARN_OPEN_BACKUP:
5253 openFileDialog(GUI_FILE_OPEN_BACKUP);
5254 break;
5255 case GUI_WARN_CV:
5256 cvOpen=true;
5257 break;
5258 default:
5259 break;
5260 }
5261 postWarnAction=GUI_WARN_GENERIC;
5262 } else if (postWarnAction==GUI_WARN_OPEN_DROP) {
5263 nextFile="";
5264 }
5265 break;
5266 }
5267 case GUI_FILE_SAVE_DMF:
5268 logD("saving: %s",copyOfName.c_str());
5269 if (save(copyOfName,26)>0) {
5270 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
5271 }
5272 break;
5273 case GUI_FILE_SAVE_DMF_LEGACY:
5274 logD("saving: %s",copyOfName.c_str());
5275 if (save(copyOfName,24)>0) {
5276 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
5277 }
5278 break;
5279 case GUI_FILE_INS_SAVE:
5280 if (curIns>=0 && curIns<(int)e->song.ins.size()) {
5281 if (e->song.ins[curIns]->save(copyOfName.c_str(),&e->song,settings.writeInsNames)) {
5282 pushRecentSys(copyOfName.c_str());
5283 }
5284 }
5285 break;
5286 case GUI_FILE_INS_SAVE_DMP:
5287 if (curIns>=0 && curIns<(int)e->song.ins.size()) {
5288 if (!e->song.ins[curIns]->saveDMP(copyOfName.c_str())) {
5289 showError(_("error while saving instrument! only the following instrument types are supported:\n- FM (OPN)\n- SN76489/Sega PSG\n- Game Boy\n- PC Engine\n- NES\n- C64\n- FM (OPLL)\n- FDS"));
5290 } else {
5291 pushRecentSys(copyOfName.c_str());
5292 }
5293 }
5294 break;
5295 case GUI_FILE_INS_SAVE_ALL: {
5296 String errors;
5297 for (int i=0; i<e->song.insLen; i++) {
5298 String nextPath=copyOfName;
5299 nextPath+=DIR_SEPARATOR_STR;
5300 nextPath+=fmt::sprintf("%.2X_",i);
5301 for (char j: e->song.ins[i]->name) {
5302 switch (j) {
5303 // these chars are reserved
5304 case '/': case '<': case '>': case ':': case '"': case '\\': case '|': case '?': case '*':
5305 nextPath+='_';
5306 break;
5307 default:
5308 nextPath+=j;
5309 break;
5310 }
5311 }
5312 nextPath+=".fui";
5313 logV("%s",nextPath);
5314 if (!e->song.ins[i]->save(nextPath.c_str(),&e->song,settings.writeInsNames)) {
5315 errors+=fmt::sprintf("%s: could not save!\n",e->song.ins[i]->name);
5316 }
5317 }
5318
5319 if (!errors.empty()) {
5320 showError(errors);
5321 }
5322 break;
5323 }
5324 case GUI_FILE_WAVE_SAVE_ALL: {
5325 String errors;
5326 for (int i=0; i<e->song.waveLen; i++) {
5327 String nextPath=copyOfName;
5328 nextPath+=DIR_SEPARATOR_STR;
5329 nextPath+=fmt::sprintf("%.2X.fuw",i);
5330 logV("%s",nextPath);
5331 if (!e->song.wave[i]->save(nextPath.c_str())) {
5332 errors+=fmt::sprintf("%d: could not save!\n",i);
5333 }
5334 }
5335
5336 if (!errors.empty()) {
5337 showError(errors);
5338 }
5339 break;
5340 }
5341 case GUI_FILE_SAMPLE_SAVE_ALL: {
5342 String errors;
5343 for (int i=0; i<e->song.sampleLen; i++) {
5344 String nextPath=copyOfName;
5345 nextPath+=DIR_SEPARATOR_STR;
5346 nextPath+=fmt::sprintf("%.2X_",i);
5347 for (char j: e->song.sample[i]->name) {
5348 switch (j) {
5349 // these chars are reserved
5350 case '/': case '<': case '>': case ':': case '"': case '\\': case '|': case '?': case '*':
5351 nextPath+='_';
5352 break;
5353 default:
5354 nextPath+=j;
5355 break;
5356 }
5357 }
5358 nextPath+=".wav";
5359 logV("%s",nextPath);
5360 if (!e->song.sample[i]->save(nextPath.c_str())) {
5361 errors+=fmt::sprintf("%s: could not save!\n",e->song.sample[i]->name);
5362 }
5363 }
5364
5365 if (!errors.empty()) {
5366 showError(errors);
5367 }
5368 break;
5369 }
5370 case GUI_FILE_WAVE_SAVE:
5371 if (curWave>=0 && curWave<(int)e->song.wave.size()) {
5372 if (e->song.wave[curWave]->save(copyOfName.c_str())) {
5373 pushRecentSys(copyOfName.c_str());
5374 }
5375 }
5376 break;
5377 case GUI_FILE_WAVE_SAVE_DMW:
5378 if (curWave>=0 && curWave<(int)e->song.wave.size()) {
5379 if (e->song.wave[curWave]->saveDMW(copyOfName.c_str())) {
5380 pushRecentSys(copyOfName.c_str());
5381 }
5382 }
5383 break;
5384 case GUI_FILE_WAVE_SAVE_RAW:
5385 if (curWave>=0 && curWave<(int)e->song.wave.size()) {
5386 if (e->song.wave[curWave]->saveRaw(copyOfName.c_str())) {
5387 pushRecentSys(copyOfName.c_str());
5388 }
5389 }
5390 break;
5391 case GUI_FILE_SAMPLE_OPEN: {
5392 String errs=_("there were some errors while loading samples:\n");
5393 bool warn=false;
5394 for (String i: fileDialog->getFileName()) {
5395 std::vector<DivSample*> samples=e->sampleFromFile(i.c_str());
5396 if (samples.empty()) {
5397 if (fileDialog->getFileName().size()>1) {
5398 warn=true;
5399 errs+=fmt::sprintf("- %s: %s\n",i,e->getLastError());
5400 } else {;
5401 showError(e->getLastError());
5402 }
5403 }
5404 else
5405 {
5406 if((int)samples.size() == 1)
5407 {
5408 if (e->addSamplePtr(samples[0]) == -1)
5409 {
5410 if (fileDialog->getFileName().size()>1)
5411 {
5412 warn=true;
5413 errs+=fmt::sprintf("- %s: %s\n",i,e->getLastError());
5414 }
5415 else
5416 {
5417 showError(e->getLastError());
5418 }
5419 }
5420 else
5421 {
5422 MARK_MODIFIED;
5423 }
5424 }
5425 else
5426 {
5427 for (DivSample* s: samples) { //ask which samples to load!
5428 pendingSamples.push_back(std::make_pair(s,false));
5429 }
5430 displayPendingSamples=true;
5431 replacePendingSample = false;
5432 }
5433 }
5434 }
5435 if (warn) {
5436 showWarning(errs,GUI_WARN_GENERIC);
5437 }
5438 break;
5439 }
5440 case GUI_FILE_SAMPLE_OPEN_REPLACE: {
5441 std::vector<DivSample*> samples=e->sampleFromFile(copyOfName.c_str());
5442 if (samples.empty()) {
5443 showError(e->getLastError());
5444 } else {
5445 if ((int)samples.size()==1) {
5446 if (curSample>=0 && curSample<(int)e->song.sample.size()) {
5447 DivSample* s=samples[0];
5448 e->lockEngine([this,s]() {
5449 // if it crashes here please tell me...
5450 DivSample* oldSample=e->song.sample[curSample];
5451 e->song.sample[curSample]=s;
5452 delete oldSample;
5453 e->renderSamples();
5454 MARK_MODIFIED;
5455 });
5456 updateSampleTex=true;
5457 } else {
5458 showError(_("...but you haven't selected a sample!"));
5459 delete samples[0];
5460 }
5461 } else {
5462 for (DivSample* s: samples) { // ask which samples to load!
5463 pendingSamples.push_back(std::make_pair(s,false));
5464 }
5465 displayPendingSamples=true;
5466 replacePendingSample=true;
5467 }
5468 }
5469 break;
5470 }
5471 case GUI_FILE_SAMPLE_OPEN_RAW:
5472 case GUI_FILE_SAMPLE_OPEN_REPLACE_RAW:
5473 pendingRawSample=copyOfName;
5474 pendingRawSampleReplace=(curFileDialog==GUI_FILE_SAMPLE_OPEN_REPLACE_RAW);
5475 displayPendingRawSample=true;
5476 break;
5477 case GUI_FILE_SAMPLE_SAVE:
5478 if (curSample>=0 && curSample<(int)e->song.sample.size()) {
5479 if (!e->song.sample[curSample]->save(copyOfName.c_str())) {
5480 showError(_("could not save sample! open Log Viewer for more information."));
5481 } else {
5482 pushRecentSys(copyOfName.c_str());
5483 }
5484 }
5485 break;
5486 case GUI_FILE_SAMPLE_SAVE_RAW:
5487 if (curSample>=0 && curSample<(int)e->song.sample.size()) {
5488 if (!e->song.sample[curSample]->saveRaw(copyOfName.c_str())) {
5489 showError(_("could not save sample! open Log Viewer for more information."));
5490 } else {
5491 pushRecentSys(copyOfName.c_str());
5492 }
5493 }
5494 break;
5495 case GUI_FILE_EXPORT_AUDIO_ONE:
5496 exportAudio(copyOfName,DIV_EXPORT_MODE_ONE);
5497 break;
5498 case GUI_FILE_EXPORT_AUDIO_PER_SYS:
5499 exportAudio(copyOfName,DIV_EXPORT_MODE_MANY_SYS);
5500 break;
5501 case GUI_FILE_EXPORT_AUDIO_PER_CHANNEL:
5502 exportAudio(copyOfName,DIV_EXPORT_MODE_MANY_CHAN);
5503 break;
5504 case GUI_FILE_INS_OPEN: {
5505 std::vector<DivInstrument*> instruments;
5506 bool ask=false;
5507 bool warn=false;
5508 String warns=_("there were some warnings/errors while loading instruments:\n");
5509 int sampleCountBefore=e->song.sampleLen;
5510 for (String i: fileDialog->getFileName()) {
5511 std::vector<DivInstrument*> insTemp=e->instrumentFromFile(i.c_str(),true,settings.readInsNames);
5512 if (insTemp.empty()) {
5513 warn=true;
5514 warns+=fmt::sprintf(_("> %s: cannot load instrument! (%s)\n"),i,e->getLastError());
5515 } else if (!e->getWarnings().empty()) {
5516 warn=true;
5517 warns+=fmt::sprintf("> %s:\n%s\n",i,e->getWarnings());
5518 }
5519 if (insTemp.size()>1) ask=true;
5520 for (DivInstrument* j: insTemp) {
5521 instruments.push_back(j);
5522 }
5523 }
5524 if (e->song.sampleLen!=sampleCountBefore) {
5525 e->renderSamplesP();
5526 }
5527 if (warn) {
5528 if (instruments.empty()) {
5529 if (fileDialog->getFileName().size()>1) {
5530 showError(warns);
5531 } else {
5532 showError(fmt::sprintf(_("cannot load instrument! (%s)"),e->getLastError()));
5533 }
5534 } else {
5535 showWarning(warns,GUI_WARN_GENERIC);
5536 }
5537 } else if (instruments.empty()) {
5538 showError(_("congratulations! you managed to load nothing.\nyou are entitled to a bug report."));
5539 }
5540 if (!instruments.empty()) {
5541 if (ask) { // ask which instruments to load
5542 for (DivInstrument* i: instruments) {
5543 pendingIns.push_back(std::make_pair(i,false));
5544 }
5545 displayPendingIns=true;
5546 pendingInsSingle=false;
5547 } else { // load the only instrument
5548 int instrumentCount=-1;
5549 for (DivInstrument* i: instruments) {
5550 instrumentCount=e->addInstrumentPtr(i);
5551 MARK_MODIFIED;
5552 }
5553 if (instrumentCount>=0 && settings.selectAssetOnLoad) {
5554 curIns=instrumentCount-1;
5555 }
5556 }
5557 }
5558 break;
5559 }
5560 case GUI_FILE_INS_OPEN_REPLACE: {
5561 int sampleCountBefore=e->song.sampleLen;
5562 std::vector<DivInstrument*> instruments=e->instrumentFromFile(copyOfName.c_str(),true,settings.readInsNames);
5563 if (!instruments.empty()) {
5564 if (e->song.sampleLen!=sampleCountBefore) {
5565 e->renderSamplesP();
5566 }
5567 if (!e->getWarnings().empty()) {
5568 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
5569 }
5570 if (instruments.size()>1) { // ask which instrument
5571 for (DivInstrument* i: instruments) {
5572 pendingIns.push_back(std::make_pair(i,false));
5573 }
5574 displayPendingIns=true;
5575 pendingInsSingle=true;
5576 } else { // replace with the only instrument
5577 if (curIns>=0 && curIns<(int)e->song.ins.size()) {
5578 *e->song.ins[curIns]=*instruments[0];
5579 // reset macro zoom
5580 memset(e->song.ins[curIns]->temp.vZoom,-1,sizeof(e->song.ins[curIns]->temp.vZoom));
5581 MARK_MODIFIED;
5582 } else {
5583 showError(_("...but you haven't selected an instrument!"));
5584 }
5585 for (DivInstrument* i: instruments) {
5586 delete i;
5587 }
5588 }
5589 } else {
5590 showError(fmt::sprintf(_("cannot load instrument! (%s)"),e->getLastError()));
5591 }
5592 break;
5593 }
5594 case GUI_FILE_WAVE_OPEN: {
5595 String errs=_("there were some errors while loading wavetables:\n");
5596 bool warn=false;
5597 for (String i: fileDialog->getFileName()) {
5598 DivWavetable* wave=e->waveFromFile(i.c_str());
5599 if (wave==NULL) {
5600 if (fileDialog->getFileName().size()>1) {
5601 warn=true;
5602 errs+=fmt::sprintf("- %s: %s\n",i,e->getLastError());
5603 } else {
5604 showError(fmt::sprintf(_("cannot load wavetable! (%s)"),e->getLastError()));
5605 }
5606 } else {
5607 int waveCount=-1;
5608 waveCount=e->addWavePtr(wave);
5609 if (waveCount==-1) {
5610 if (fileDialog->getFileName().size()>1) {
5611 warn=true;
5612 errs+=fmt::sprintf("- %s: %s\n",i,e->getLastError());
5613 } else {
5614 showError(fmt::sprintf(_("cannot load wavetable! (%s)"),e->getLastError()));
5615 }
5616 } else {
5617 if (settings.selectAssetOnLoad) {
5618 curWave=waveCount-1;
5619 }
5620 MARK_MODIFIED;
5621 RESET_WAVE_MACRO_ZOOM;
5622 }
5623 }
5624 }
5625 if (warn) {
5626 showWarning(errs,GUI_WARN_GENERIC);
5627 }
5628 break;
5629 }
5630 case GUI_FILE_WAVE_OPEN_REPLACE: {
5631 DivWavetable* wave=e->waveFromFile(copyOfName.c_str());
5632 if (wave==NULL) {
5633 showError(fmt::sprintf(_("cannot load wavetable! (%s)"),e->getLastError()));
5634 } else {
5635 if (curWave>=0 && curWave<(int)e->song.wave.size()) {
5636 e->lockEngine([this,wave]() {
5637 *e->song.wave[curWave]=*wave;
5638 MARK_MODIFIED;
5639 });
5640 } else {
5641 showError(_("...but you haven't selected a wavetable!"));
5642 }
5643 delete wave;
5644 }
5645 break;
5646 }
5647 case GUI_FILE_EXPORT_VGM: {
5648 SafeWriter* w=e->saveVGM(willExport,vgmExportLoop,vgmExportVersion,vgmExportPatternHints,vgmExportDirectStream,vgmExportTrailingTicks,vgmExportDPCM07,vgmExportCorrectedRate);
5649 if (w!=NULL) {
5650 FILE* f=ps_fopen(copyOfName.c_str(),"wb");
5651 if (f!=NULL) {
5652 fwrite(w->getFinalBuf(),1,w->size(),f);
5653 fclose(f);
5654 pushRecentSys(copyOfName.c_str());
5655 } else {
5656 showError(_("could not open file!"));
5657 }
5658 w->finish();
5659 delete w;
5660 if (!e->getWarnings().empty()) {
5661 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
5662 }
5663 } else {
5664 showError(fmt::sprintf(_("could not write VGM! (%s)"),e->getLastError()));
5665 }
5666 break;
5667 }
5668 case GUI_FILE_EXPORT_ROM:
5669 romExportPath=copyOfName;
5670 pendingExport=e->buildROM(romTarget);
5671 if (pendingExport==NULL) {
5672 showError("could not create exporter! you may want to report this issue...");
5673 } else {
5674 pendingExport->setConf(romConfig);
5675 if (pendingExport->go(e)) {
5676 displayExportingROM=true;
5677 romExportSave=true;
5678 } else {
5679 showError("could not begin exporting process! TODO: elaborate");
5680 }
5681 }
5682 break;
5683 case GUI_FILE_EXPORT_TEXT: {
5684 SafeWriter* w=e->saveText(false);
5685 if (w!=NULL) {
5686 FILE* f=ps_fopen(copyOfName.c_str(),"wb");
5687 if (f!=NULL) {
5688 fwrite(w->getFinalBuf(),1,w->size(),f);
5689 fclose(f);
5690 pushRecentSys(copyOfName.c_str());
5691 } else {
5692 showError(_("could not open file!"));
5693 }
5694 w->finish();
5695 delete w;
5696 if (!e->getWarnings().empty()) {
5697 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
5698 }
5699 } else {
5700 showError(fmt::sprintf(_("could not write text! (%s)"),e->getLastError()));
5701 }
5702 break;
5703 }
5704 case GUI_FILE_EXPORT_CMDSTREAM: {
5705 exportCmdStream(false,copyOfName);
5706 break;
5707 }
5708 case GUI_FILE_LOAD_MAIN_FONT:
5709 settings.mainFontPath=copyOfName;
5710 break;
5711 case GUI_FILE_LOAD_HEAD_FONT:
5712 settings.headFontPath=copyOfName;
5713 break;
5714 case GUI_FILE_LOAD_PAT_FONT:
5715 settings.patFontPath=copyOfName;
5716 break;
5717 case GUI_FILE_IMPORT_COLORS:
5718 importColors(copyOfName);
5719 break;
5720 case GUI_FILE_IMPORT_KEYBINDS:
5721 importKeybinds(copyOfName);
5722 break;
5723 case GUI_FILE_IMPORT_LAYOUT:
5724 importLayout(copyOfName);
5725 break;
5726 case GUI_FILE_IMPORT_USER_PRESETS:
5727 if (!loadUserPresets(false,copyOfName,true)) {
5728 showError(_("could not import user presets!"));
5729 }
5730 break;
5731 case GUI_FILE_IMPORT_USER_PRESETS_REPLACE:
5732 if (!loadUserPresets(false,copyOfName,false)) {
5733 showError(fmt::sprintf(_("could not import user presets! (%s)"),strerror(errno)));
5734 }
5735 break;
5736 case GUI_FILE_IMPORT_CONFIG:
5737 importConfig(copyOfName);
5738 break;
5739 case GUI_FILE_EXPORT_COLORS:
5740 exportColors(copyOfName);
5741 break;
5742 case GUI_FILE_EXPORT_KEYBINDS:
5743 exportKeybinds(copyOfName);
5744 break;
5745 case GUI_FILE_EXPORT_LAYOUT:
5746 exportLayout(copyOfName);
5747 break;
5748 case GUI_FILE_EXPORT_USER_PRESETS:
5749 if (!saveUserPresets(false,copyOfName)) {
5750 showError(fmt::sprintf(_("could not import user presets! (%s)"),strerror(errno)));
5751 }
5752 break;
5753 case GUI_FILE_EXPORT_CONFIG:
5754 exportConfig(copyOfName);
5755 break;
5756 case GUI_FILE_YRW801_ROM_OPEN:
5757 settings.yrw801Path=copyOfName;
5758 break;
5759 case GUI_FILE_TG100_ROM_OPEN:
5760 settings.tg100Path=copyOfName;
5761 break;
5762 case GUI_FILE_MU5_ROM_OPEN:
5763 settings.mu5Path=copyOfName;
5764 break;
5765 case GUI_FILE_CMDSTREAM_OPEN:
5766 if (loadStream(copyOfName)>0) {
5767 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
5768 }
5769 break;
5770 case GUI_FILE_TEST_OPEN:
5771 showWarning(fmt::sprintf(_("You opened: %s"),copyOfName),GUI_WARN_GENERIC);
5772 break;
5773 case GUI_FILE_TEST_OPEN_MULTI: {
5774 String msg=_("You opened:");
5775 for (String i: fileDialog->getFileName()) {
5776 msg+=fmt::sprintf("\n- %s",i);
5777 }
5778 showWarning(msg,GUI_WARN_GENERIC);
5779 break;
5780 }
5781 case GUI_FILE_TEST_SAVE:
5782 showWarning(fmt::sprintf(_("You saved: %s"),copyOfName),GUI_WARN_GENERIC);
5783 break;
5784 }
5785 curFileDialog=GUI_FILE_OPEN;
5786 }
5787 }
5788 fileDialog->close();
5789 postWarnAction=GUI_WARN_GENERIC;
5790
5791 if (openOpen) {
5792 openFileDialog(GUI_FILE_OPEN);
5793 }
5794 }
5795
5796 if (warnQuit && introPos>=11.0) {
5797 warnQuit=false;
5798 ImGui::OpenPopup(_("Warning"));
5799 }
5800
5801 if (displayError && introPos>=11.0) {
5802 displayError=false;
5803 ImGui::OpenPopup(_("Error"));
5804 }
5805
5806 if (displayPendingIns) {
5807 displayPendingIns=false;
5808 ImGui::OpenPopup(_("Select Instrument"));
5809 }
5810
5811 if (displayPendingSamples) {
5812 displayPendingSamples=false;
5813 ImGui::OpenPopup(_("Select Sample"));
5814 }
5815
5816 if (displayPendingRawSample) {
5817 displayPendingRawSample=false;
5818 ImGui::OpenPopup(_("Import Raw Sample"));
5819 }
5820
5821 if (displayInsTypeList) {
5822 displayInsTypeList=false;
5823 ImGui::OpenPopup("InsTypeList");
5824 }
5825
5826 if (displayWaveSizeList) {
5827 displayWaveSizeList=false;
5828 ImGui::OpenPopup("WaveSizeList");
5829 }
5830
5831 if (displayExporting) {
5832 displayExporting=false;
5833 ImGui::OpenPopup(_("Rendering..."));
5834 }
5835
5836 if (displayExportingROM) {
5837 displayExportingROM=false;
5838 ImGui::OpenPopup(_("ROM Export Progress"));
5839 }
5840
5841 if (displayExportingCS) {
5842 displayExportingCS=false;
5843 ImGui::OpenPopup(_("CmdStream Export Progress"));
5844 }
5845
5846 if (displayNew) {
5847 newSongQuery="";
5848 newSongFirstFrame=true;
5849 displayNew=false;
5850 if (settings.newSongBehavior==1) {
5851 e->createNewFromDefaults();
5852 undoHist.clear();
5853 redoHist.clear();
5854 curFileName="";
5855 modified=false;
5856 curNibble=false;
5857 orderNibble=false;
5858 orderCursor=-1;
5859 samplePos=0;
5860 updateSampleTex=true;
5861 selStart=SelectionPoint();
5862 selEnd=SelectionPoint();
5863 cursor=SelectionPoint();
5864 updateWindowTitle();
5865 updateROMExportAvail();
5866 } else {
5867 ImGui::OpenPopup(_("New Song"));
5868 }
5869 }
5870
5871 if (displayPalette) {
5872 paletteSearchResults.clear();
5873 paletteQuery="";
5874 paletteFirstFrame=true;
5875 curPaletteChoice=0;
5876 displayPalette=false;
5877 ImGui::OpenPopup(_("Command Palette"));
5878 }
5879
5880 if (displayExport) {
5881 displayExport=false;
5882 ImGui::OpenPopup(_("Export"));
5883 }
5884
5885 if (displayEditString) {
5886 ImGui::OpenPopup("EditString");
5887 }
5888
5889 if (nextWindow==GUI_WINDOW_ABOUT) {
5890 aboutOpen=true;
5891 nextWindow=GUI_WINDOW_NOTHING;
5892 }
5893 if (aboutOpen) drawAbout();
5894
5895 MEASURE_BEGIN(popup);
5896
5897 centerNextWindow(_("Rendering..."),canvasW,canvasH);
5898 // ImGui::SetNextWindowSize(ImVec2(0.0f,0.0f));
5899 if (ImGui::BeginPopupModal(_("Rendering..."),NULL,ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) {
5900 // WHAT the HELL?!
5901 WAKE_UP;
5902 if (audioExportOptions.mode!=DIV_EXPORT_MODE_MANY_CHAN) {
5903 ImGui::Text(_("Please wait..."));
5904 }
5905 float* progressLambda=&curProgress;
5906 int curPosInRows=0;
5907 int* curPosInRowsLambda=&curPosInRows;
5908 int loopsLeft=0;
5909 int* loopsLeftLambda=&loopsLeft;
5910 int totalLoops=0;
5911 int* totalLoopsLambda=&totalLoops;
5912 int curFile=0;
5913 int* curFileLambda=&curFile;
5914 if (e->isExporting()) {
5915 e->lockEngine(
5916 [this, progressLambda, curPosInRowsLambda, curFileLambda, loopsLeftLambda, totalLoopsLambda] () {
5917 int curRow=0; int curOrder=0;
5918 e->getCurSongPos(curRow, curOrder);
5919 *curFileLambda=0;
5920 e->getCurFileIndex(*curFileLambda);
5921 *curPosInRowsLambda=curRow;
5922 for (int i=0; i<MIN(curOrder,(int)songOrdersLengths.size()); i++) *curPosInRowsLambda+=songOrdersLengths[i];
5923 if (!songHasSongEndCommand) {
5924 e->getLoopsLeft(*loopsLeftLambda);
5925 e->getTotalLoops(*totalLoopsLambda);
5926 if ((*totalLoopsLambda)!=(*loopsLeftLambda)) { // we are going 2nd, 3rd, etc. time through the song
5927 *curPosInRowsLambda-=(songLength-songLoopedSectionLength); // a hack so progress bar does not jump?
5928 }
5929 if (e->getIsFadingOut()) { // we are in fadeout??? why it works like that bruh
5930 // LIVE WITH IT damn it
5931 *curPosInRowsLambda-=(songLength-songLoopedSectionLength); // a hack so progress bar does not jump?
5932 }
5933 }
5934 if (totalLength<0.1) {
5935 // DON'T
5936 *progressLambda=0;
5937 } else {
5938 *progressLambda=(float)((*curPosInRowsLambda)+((*totalLoopsLambda)-(*loopsLeftLambda))*songLength+lengthOfOneFile*(*curFileLambda))/(float)totalLength;
5939 }
5940 }
5941 );
5942 }
5943
5944 ImGui::Text(_("Row %d of %d"),curPosInRows+((totalLoops)-(loopsLeft))*songLength,lengthOfOneFile);
5945 if (audioExportOptions.mode==DIV_EXPORT_MODE_MANY_CHAN) ImGui::Text(_("Channel %d of %d"),curFile+1,totalFiles);
5946
5947 ImGui::ProgressBar(curProgress,ImVec2(320.0f*dpiScale,0),fmt::sprintf("%.2f%%",curProgress*100.0f).c_str());
5948
5949 if (ImGui::Button(_("Abort"))) {
5950 if (e->haltAudioFile()) {
5951 ImGui::CloseCurrentPopup();
5952 }
5953 }
5954 if (!e->isExporting()) {
5955 e->finishAudioFile();
5956 ImGui::CloseCurrentPopup();
5957 }
5958 ImGui::EndPopup();
5959 }
5960
5961 ImVec2 romExportMinSize=mobileUI?ImVec2(canvasW-(portrait?0:(60.0*dpiScale)),canvasH-60.0*dpiScale):ImVec2(400.0f*dpiScale,200.0f*dpiScale);
5962 ImVec2 romExportMaxSize=ImVec2(canvasW-((mobileUI && !portrait)?(60.0*dpiScale):0),canvasH-(mobileUI?(60.0*dpiScale):0));
5963
5964 centerNextWindow(_("ROM Export Progress"),canvasW,canvasH);
5965 ImGui::SetNextWindowSizeConstraints(romExportMinSize,romExportMaxSize);
5966 if (ImGui::BeginPopupModal(_("ROM Export Progress"),NULL)) {
5967 if (pendingExport==NULL) {
5968 ImGui::TextWrapped("%s",_("...ooooor you could try asking me a new ROM export?"));
5969 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
5970 if (ImGui::Button(_("Erm what the sigma???"),ImVec2(ImGui::GetContentRegionAvail().x,0.0f))) {
5971 ImGui::CloseCurrentPopup();
5972 }
5973 } else {
5974 int progIndex=0;
5975 while (true) {
5976 DivROMExportProgress p=pendingExport->getProgress(progIndex);
5977 if (p.name.empty()) break;
5978 ImGui::Text("%s: %d%%",p.name.c_str(),(int)round(p.amount*100.0f));
5979 ImGui::ProgressBar(p.amount,ImVec2(-FLT_MIN,0));
5980 progIndex++;
5981 }
5982 ImVec2 romLogSize=ImGui::GetContentRegionAvail();
5983 romLogSize.y-=ImGui::GetFrameHeightWithSpacing();
5984 if (romLogSize.y<60.0f*dpiScale) romLogSize.y=60.0f*dpiScale;
5985 if (ImGui::BeginChild("Export Log",romLogSize,ImGuiChildFlags_Border)) {
5986 pendingExport->logLock.lock();
5987 ImGui::PushFont(patFont);
5988 for (String& i: pendingExport->exportLog) {
5989 ImGui::TextWrapped("%s",i.c_str());
5990 }
5991 if (romExportSave) {
5992 ImGui::SetScrollY(ImGui::GetScrollMaxY());
5993 }
5994 ImGui::PopFont();
5995 pendingExport->logLock.unlock();
5996 }
5997 ImGui::EndChild();
5998 if (pendingExport->isRunning()) {
5999 WAKE_UP;
6000 if (ImGui::Button(_("Abort"),ImVec2(ImGui::GetContentRegionAvail().x,0.0f))) {
6001 pendingExport->abort();
6002 delete pendingExport;
6003 pendingExport=NULL;
6004 romExportSave=false;
6005 ImGui::CloseCurrentPopup();
6006 }
6007 } else {
6008 if (romExportSave) {
6009 pendingExport->wait();
6010 if (!pendingExport->hasFailed()) {
6011 // save files here (romExportPath)
6012 for (DivROMExportOutput& i: pendingExport->getResult()) {
6013 String path=romExportPath;
6014 if (romMultiFile) {
6015 path+=DIR_SEPARATOR_STR;
6016 path+=i.name;
6017 }
6018 FILE* outFile=ps_fopen(path.c_str(),"wb");
6019 if (outFile!=NULL) {
6020 fwrite(i.data->getFinalBuf(),1,i.data->size(),outFile);
6021 fclose(outFile);
6022 } else {
6023 // TODO: handle failure here
6024 }
6025 i.data->finish();
6026 delete i.data;
6027 }
6028 }
6029 romExportSave=false;
6030 }
6031 if (pendingExport!=NULL) {
6032 if (pendingExport->hasFailed()) {
6033 ImGui::AlignTextToFramePadding();
6034 ImGui::TextUnformatted(_("Error!"));
6035 ImGui::SameLine();
6036 }
6037 }
6038 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
6039 if (ImGui::Button(_("OK"),ImVec2(ImGui::GetContentRegionAvail().x,0.0f))) {
6040 delete pendingExport;
6041 pendingExport=NULL;
6042 ImGui::CloseCurrentPopup();
6043 }
6044 }
6045 }
6046 ImGui::EndPopup();
6047 }
6048
6049 centerNextWindow(_("CmdStream Export Progress"),canvasW,canvasH);
6050 ImGui::SetNextWindowSizeConstraints(romExportMinSize,romExportMaxSize);
6051 if (ImGui::BeginPopupModal(_("CmdStream Export Progress"),NULL)) {
6052 if (csExportThread==NULL) {
6053 ImGui::TextWrapped("%s",_("it appears your Furnace has too many bugs in it. any song you can export?"));
6054 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
6055 if (ImGui::Button(_("Talk With Devs"),ImVec2(ImGui::GetContentRegionAvail().x/3.0f,0.0f))) {
6056 ImGui::CloseCurrentPopup();
6057 }
6058 ImGui::SameLine();
6059 if (ImGui::Button(_("Ask on Bug Report"),ImVec2(ImGui::GetContentRegionAvail().x/3.0f,0.0f))) {
6060 ImGui::CloseCurrentPopup();
6061 }
6062 ImGui::SameLine();
6063 if (ImGui::Button(_("View Issues"),ImVec2(ImGui::GetContentRegionAvail().x/3.0f,0.0f))) {
6064 ImGui::CloseCurrentPopup();
6065 }
6066 } else {
6067 WAKE_UP;
6068 ImGui::Text("Exporting...");
6069 ImGui::Text("opt stage: %d",csProgress.optStage);
6070 ImGui::Text("pass: %d/%d",csProgress.optCurrent,csProgress.optTotal);
6071 ImGui::Text("find: %d/%d",csProgress.findCurrent,csProgress.findTotal);
6072 ImGui::Text("expand: %d/%d",csProgress.expandCurrent,csProgress.optCurrent);
6073 ImGui::Text("benefit: %d/%d",csProgress.origCurrent,csProgress.origCount);
6074
6075 // check whether we're done
6076 if (csExportDone) {
6077 csExportThread->join();
6078 delete csExportThread;
6079 csExportThread=NULL;
6080
6081 if (csExportTarget) { // command stream player
6082 if (csExportResult!=NULL) {
6083 if (!e->playStream(csExportResult->getFinalBuf(),csExportResult->size())) {
6084 showError(e->getLastError());
6085 csExportResult->finish();
6086 delete csExportResult;
6087 } else {
6088 csExportResult->disown();
6089 delete csExportResult;
6090 }
6091 } else {
6092 showError(_("oh no! it broke!"));
6093 }
6094 csExportResult=NULL;
6095 } else { // command stream export
6096 if (csExportResult!=NULL) {
6097 FILE* f=ps_fopen(csExportPath.c_str(),"wb");
6098 if (f!=NULL) {
6099 fwrite(csExportResult->getFinalBuf(),1,csExportResult->size(),f);
6100 fclose(f);
6101 pushRecentSys(csExportPath.c_str());
6102 } else {
6103 showError(_("could not open file!"));
6104 }
6105 csExportResult->finish();
6106 delete csExportResult;
6107 if (!e->getWarnings().empty()) {
6108 showWarning(e->getWarnings(),GUI_WARN_GENERIC);
6109 }
6110 } else {
6111 showError(fmt::sprintf(_("could not write command stream! (%s)"),e->getLastError()));
6112 }
6113 csExportResult=NULL;
6114 }
6115
6116 ImGui::CloseCurrentPopup();
6117 }
6118 }
6119 ImGui::EndPopup();
6120 }
6121
6122 drawTutorial();
6123
6124 ImVec2 newSongMinSize=mobileUI?ImVec2(canvasW-(portrait?0:(60.0*dpiScale)),canvasH-60.0*dpiScale):ImVec2(400.0f*dpiScale,200.0f*dpiScale);
6125 ImVec2 newSongMaxSize=ImVec2(canvasW-((mobileUI && !portrait)?(60.0*dpiScale):0),canvasH-(mobileUI?(60.0*dpiScale):0));
6126 ImGui::SetNextWindowSizeConstraints(newSongMinSize,newSongMaxSize);
6127 if (ImGui::BeginPopupModal(_("New Song"),NULL,ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollWithMouse|ImGuiWindowFlags_NoScrollbar)) {
6128 ImGui::SetWindowPos(ImVec2(((canvasW)-ImGui::GetWindowSize().x)*0.5,((canvasH)-ImGui::GetWindowSize().y)*0.5));
6129 if (ImGui::GetWindowSize().x<newSongMinSize.x || ImGui::GetWindowSize().y<newSongMinSize.y) {
6130 ImGui::SetWindowSize(newSongMinSize,ImGuiCond_Always);
6131 }
6132 drawNewSong();
6133 ImGui::EndPopup();
6134 }
6135
6136 ImVec2 wsize=ImVec2(canvasW*0.9,canvasH*0.4);
6137 ImGui::SetNextWindowPos(ImVec2((canvasW-wsize.x)*0.5,50*dpiScale));
6138 ImGui::SetNextWindowSize(wsize,ImGuiCond_Always);
6139 if (ImGui::BeginPopup(_("Command Palette"),ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings)) {
6140 drawPalette();
6141 ImGui::EndPopup();
6142 }
6143
6144 if (ImGui::BeginPopupModal(_("Export"),NULL,ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollWithMouse|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_AlwaysAutoResize)) {
6145 ImGui::SetWindowPos(ImVec2(((canvasW)-ImGui::GetWindowSize().x)*0.5,((canvasH)-ImGui::GetWindowSize().y)*0.5));
6146 drawExport();
6147 ImGui::EndPopup();
6148 }
6149
6150 centerNextWindow(_("Error"),canvasW,canvasH);
6151 if (ImGui::BeginPopupModal(_("Error"),NULL,ImGuiWindowFlags_AlwaysAutoResize)) {
6152 ImGui::Text(_("%s"),errorString.c_str());
6153 if (ImGui::Button(_("OK"))) {
6154 ImGui::CloseCurrentPopup();
6155 }
6156 ImGui::EndPopup();
6157 }
6158
6159 centerNextWindow(_("Warning"),canvasW,canvasH);
6160 if (ImGui::BeginPopupModal(_("Warning"),NULL,ImGuiWindowFlags_AlwaysAutoResize)) {
6161 ImGui::Text("%s",warnString.c_str());
6162 switch (warnAction) {
6163 case GUI_WARN_QUIT:
6164 if (ImGui::Button(_("Yes"))) {
6165 ImGui::CloseCurrentPopup();
6166 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6167 openFileDialog(GUI_FILE_SAVE);
6168 postWarnAction=GUI_WARN_QUIT;
6169 } else {
6170 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6171 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6172 } else {
6173 quit=true;
6174 }
6175 }
6176 }
6177 ImGui::SameLine();
6178 if (ImGui::Button(_("No"))) {
6179 ImGui::CloseCurrentPopup();
6180 quit=true;
6181 }
6182 ImGui::SameLine();
6183 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6184 ImGui::CloseCurrentPopup();
6185 }
6186 break;
6187 case GUI_WARN_NEW:
6188 if (ImGui::Button(_("Yes"))) {
6189 ImGui::CloseCurrentPopup();
6190 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6191 openFileDialog(GUI_FILE_SAVE);
6192 postWarnAction=GUI_WARN_NEW;
6193 } else {
6194 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6195 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6196 } else {
6197 displayNew=true;
6198 }
6199 }
6200 }
6201 ImGui::SameLine();
6202 if (ImGui::Button(_("No"))) {
6203 ImGui::CloseCurrentPopup();
6204 displayNew=true;
6205 }
6206 ImGui::SameLine();
6207 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6208 ImGui::CloseCurrentPopup();
6209 }
6210 break;
6211 case GUI_WARN_OPEN:
6212 if (ImGui::Button(_("Yes"))) {
6213 ImGui::CloseCurrentPopup();
6214 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6215 openFileDialog(GUI_FILE_SAVE);
6216 postWarnAction=GUI_WARN_OPEN;
6217 } else {
6218 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6219 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6220 } else {
6221 openFileDialog(GUI_FILE_OPEN);
6222 }
6223 }
6224 }
6225 ImGui::SameLine();
6226 if (ImGui::Button(_("No"))) {
6227 ImGui::CloseCurrentPopup();
6228 openFileDialog(GUI_FILE_OPEN);
6229 }
6230 ImGui::SameLine();
6231 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6232 ImGui::CloseCurrentPopup();
6233 }
6234 break;
6235 case GUI_WARN_CV:
6236 if (ImGui::Button(_("Yes"))) {
6237 ImGui::CloseCurrentPopup();
6238 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6239 openFileDialog(GUI_FILE_SAVE);
6240 postWarnAction=GUI_WARN_CV;
6241 } else {
6242 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6243 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6244 } else {
6245 cvOpen=true;
6246 }
6247 }
6248 }
6249 ImGui::SameLine();
6250 if (ImGui::Button(_("No"))) {
6251 ImGui::CloseCurrentPopup();
6252 cvOpen=true;
6253 }
6254 ImGui::SameLine();
6255 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6256 ImGui::CloseCurrentPopup();
6257 }
6258 break;
6259 case GUI_WARN_OPEN_BACKUP:
6260 if (ImGui::Button(_("Yes"))) {
6261 ImGui::CloseCurrentPopup();
6262 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6263 openFileDialog(GUI_FILE_SAVE);
6264 postWarnAction=GUI_WARN_OPEN_BACKUP;
6265 } else {
6266 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6267 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6268 } else {
6269 openFileDialog(GUI_FILE_OPEN_BACKUP);
6270 }
6271 }
6272 }
6273 ImGui::SameLine();
6274 if (ImGui::Button(_("No"))) {
6275 ImGui::CloseCurrentPopup();
6276 openFileDialog(GUI_FILE_OPEN_BACKUP);
6277 }
6278 ImGui::SameLine();
6279 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6280 ImGui::CloseCurrentPopup();
6281 }
6282 break;
6283 case GUI_WARN_OPEN_DROP:
6284 if (ImGui::Button(_("Yes"))) {
6285 ImGui::CloseCurrentPopup();
6286 if (curFileName=="" || curFileName.find(backupPath)==0 || e->song.version>=0xff00) {
6287 openFileDialog(GUI_FILE_SAVE);
6288 postWarnAction=GUI_WARN_OPEN_DROP;
6289 } else {
6290 if (save(curFileName,e->song.isDMF?e->song.version:0)>0) {
6291 showError(fmt::sprintf(_("Error while saving file! (%s)"),lastError));
6292 nextFile="";
6293 } else {
6294 if (load(nextFile)>0) {
6295 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
6296 }
6297 nextFile="";
6298 }
6299 }
6300 }
6301 ImGui::SameLine();
6302 if (ImGui::Button(_("No"))) {
6303 ImGui::CloseCurrentPopup();
6304 if (load(nextFile)>0) {
6305 showError(fmt::sprintf(_("Error while loading file! (%s)"),lastError));
6306 }
6307 nextFile="";
6308 }
6309 ImGui::SameLine();
6310 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6311 ImGui::CloseCurrentPopup();
6312 nextFile="";
6313 }
6314 break;
6315 case GUI_WARN_RESET_LAYOUT:
6316 if (ImGui::Button(_("Yes"))) {
6317 ImGui::CloseCurrentPopup();
6318 if (!mobileUI) {
6319 ImGui::LoadIniSettingsFromMemory(defaultLayout);
6320 if (!ImGui::SaveIniSettingsToDisk(finalLayoutPath,true)) {
6321 reportError(fmt::sprintf(_("could NOT save layout! %s"),strerror(errno)));
6322 }
6323 }
6324 settingsChanged=true;
6325 }
6326 ImGui::SameLine();
6327 if (ImGui::Button(_("No"))) {
6328 ImGui::CloseCurrentPopup();
6329 }
6330 break;
6331 case GUI_WARN_RESET_KEYBINDS:
6332 if (ImGui::Button(_("Yes"))) {
6333 ImGui::CloseCurrentPopup();
6334 resetKeybinds();
6335 settingsChanged=true;
6336 }
6337 ImGui::SameLine();
6338 if (ImGui::Button(_("No"))) {
6339 ImGui::CloseCurrentPopup();
6340 }
6341 break;
6342 case GUI_WARN_RESET_COLORS:
6343 if (ImGui::Button(_("Yes"))) {
6344 ImGui::CloseCurrentPopup();
6345 resetColors();
6346 applyUISettings(false);
6347 settingsChanged=true;
6348 }
6349 ImGui::SameLine();
6350 if (ImGui::Button(_("No"))) {
6351 ImGui::CloseCurrentPopup();
6352 }
6353 break;
6354 case GUI_WARN_CLOSE_SETTINGS:
6355 if (ImGui::Button(_("Yes"))) {
6356 ImGui::CloseCurrentPopup();
6357 settingsOpen=false;
6358 willCommit=true;
6359 settingsChanged=false;
6360 }
6361 ImGui::SameLine();
6362 if (ImGui::Button(_("No"))) {
6363 ImGui::CloseCurrentPopup();
6364 settingsOpen=false;
6365 syncSettings();
6366 settingsChanged=false;
6367 }
6368 ImGui::SameLine();
6369 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6370 ImGui::CloseCurrentPopup();
6371 }
6372 break;
6373 case GUI_WARN_CLEAR:
6374 if (ImGui::BeginTable("EraseOpt",2,ImGuiTableFlags_BordersInnerV)) {
6375 ImGui::TableSetupColumn("c0",ImGuiTableColumnFlags_WidthStretch,0.5f);
6376 ImGui::TableSetupColumn("c1",ImGuiTableColumnFlags_WidthStretch,0.5f);
6377 ImGui::TableNextRow();
6378
6379 ImGui::TableNextColumn();
6380 ImGui::PushFont(headFont);
6381 ImGui::AlignTextToFramePadding();
6382 ImGui::Text(_("Erasing"));
6383 ImGui::PopFont();
6384
6385 if (ImGui::Button(_("All subsongs"))) {
6386 stop();
6387 e->clearSubSongs();
6388 curOrder=0;
6389 cursor.order=0;
6390 selStart.order=0;
6391 selEnd.order=0;
6392 MARK_MODIFIED;
6393 ImGui::CloseCurrentPopup();
6394 }
6395 if (ImGui::Button(_("Current subsong"))) {
6396 stop();
6397 e->lockEngine([this]() {
6398 e->curSubSong->clearData();
6399 });
6400 e->setOrder(0);
6401 curOrder=0;
6402 cursor.order=0;
6403 selStart.order=0;
6404 selEnd.order=0;
6405 MARK_MODIFIED;
6406 ImGui::CloseCurrentPopup();
6407 }
6408 if (ImGui::Button(_("Orders"))) {
6409 stop();
6410 e->lockEngine([this]() {
6411 memset(e->curOrders->ord,0,DIV_MAX_CHANS*DIV_MAX_PATTERNS);
6412 e->curSubSong->ordersLen=1;
6413 });
6414 e->setOrder(0);
6415 curOrder=0;
6416 cursor.order=0;
6417 selStart.order=0;
6418 selEnd.order=0;
6419 MARK_MODIFIED;
6420 ImGui::CloseCurrentPopup();
6421 }
6422 if (ImGui::Button(_("Pattern"))) {
6423 stop();
6424 e->lockEngine([this]() {
6425 for (int i=0; i<e->getTotalChannelCount(); i++) {
6426 DivPattern* pat=e->curPat[i].getPattern(e->curOrders->ord[i][curOrder],true);
6427 memset(pat->data,-1,DIV_MAX_ROWS*DIV_MAX_COLS*sizeof(short));
6428 for (int j=0; j<DIV_MAX_ROWS; j++) {
6429 pat->data[j][0]=0;
6430 pat->data[j][1]=0;
6431 }
6432 }
6433 });
6434 MARK_MODIFIED;
6435 ImGui::CloseCurrentPopup();
6436 }
6437 if (ImGui::Button(_("Instruments"))) {
6438 stop();
6439 e->lockEngine([this]() {
6440 e->song.clearInstruments();
6441 });
6442 curIns=-1;
6443 MARK_MODIFIED;
6444 ImGui::CloseCurrentPopup();
6445 }
6446 if (ImGui::Button(_("Wavetables"))) {
6447 stop();
6448 e->lockEngine([this]() {
6449 e->song.clearWavetables();
6450 });
6451 curWave=0;
6452 MARK_MODIFIED;
6453 ImGui::CloseCurrentPopup();
6454 }
6455 if (ImGui::Button(_("Samples"))) {
6456 stop();
6457 e->lockEngine([this]() {
6458 e->song.clearSamples();
6459 });
6460 curSample=0;
6461 MARK_MODIFIED;
6462 ImGui::CloseCurrentPopup();
6463 }
6464
6465 ImGui::TableNextColumn();
6466 ImGui::PushFont(headFont);
6467 ImGui::AlignTextToFramePadding();
6468 ImGui::Text(_("Optimization"));
6469 ImGui::PopFont();
6470
6471 if (ImGui::Button(_("De-duplicate patterns"))) {
6472 stop();
6473 e->lockEngine([this]() {
6474 e->curSubSong->optimizePatterns();
6475 e->curSubSong->rearrangePatterns();
6476 });
6477 MARK_MODIFIED;
6478 ImGui::CloseCurrentPopup();
6479 }
6480 if (ImGui::Button(_("Remove unused instruments"))) {
6481 stop();
6482 e->delUnusedIns();
6483 MARK_MODIFIED;
6484 ImGui::CloseCurrentPopup();
6485 }
6486 /*
6487 if (ImGui::Button(_("Remove unused wavetables"))) {
6488 stop();
6489 e->delUnusedWaves();
6490 MARK_MODIFIED;
6491 ImGui::CloseCurrentPopup();
6492 }*/
6493 if (ImGui::Button(_("Remove unused samples"))) {
6494 stop();
6495 e->delUnusedSamples();
6496 MARK_MODIFIED;
6497 ImGui::CloseCurrentPopup();
6498 }
6499
6500 ImGui::EndTable();
6501 }
6502
6503 if (ImGui::BeginTable("EraseOptFooter",3)) {
6504 ImGui::TableSetupColumn("c0",ImGuiTableColumnFlags_WidthStretch,0.5f);
6505 ImGui::TableSetupColumn("c1",ImGuiTableColumnFlags_WidthFixed);
6506 ImGui::TableSetupColumn("c2",ImGuiTableColumnFlags_WidthStretch,0.5f);
6507 ImGui::TableNextRow();
6508 ImGui::TableNextColumn();
6509 ImGui::TableNextColumn();
6510 if (ImGui::Button(_("Never mind! Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6511 ImGui::CloseCurrentPopup();
6512 }
6513 ImGui::TableNextColumn();
6514 ImGui::EndTable();
6515 }
6516 break;
6517 case GUI_WARN_SUBSONG_DEL:
6518 if (ImGui::Button(_("Yes"))) {
6519 if (e->removeSubSong(e->getCurrentSubSong())) {
6520 undoHist.clear();
6521 redoHist.clear();
6522 updateScroll(0);
6523 oldRow=0;
6524 cursor.xCoarse=0;
6525 cursor.xFine=0;
6526 cursor.y=0;
6527 cursor.order=0;
6528 selStart=cursor;
6529 selEnd=cursor;
6530 curOrder=0;
6531 MARK_MODIFIED;
6532 }
6533 ImGui::CloseCurrentPopup();
6534 }
6535 ImGui::SameLine();
6536 if (ImGui::Button(_("No"))) {
6537 ImGui::CloseCurrentPopup();
6538 }
6539 break;
6540 case GUI_WARN_SYSTEM_DEL:
6541 if (ImGui::Button(_("Yes"))) {
6542 e->removeSystem(sysToDelete,preserveChanPos);
6543 if (e->song.autoSystem) {
6544 autoDetectSystem();
6545 updateWindowTitle();
6546 MARK_MODIFIED;
6547 }
6548 updateROMExportAvail();
6549 ImGui::CloseCurrentPopup();
6550 }
6551 ImGui::SameLine();
6552 if (ImGui::Button(_("No"))) {
6553 ImGui::CloseCurrentPopup();
6554 }
6555 break;
6556 case GUI_WARN_CLEAR_HISTORY:
6557 if (ImGui::Button(_("Yes"))) {
6558 recentFile.clear();
6559 ImGui::CloseCurrentPopup();
6560 }
6561 ImGui::SameLine();
6562 if (ImGui::Button(_("No"))) {
6563 ImGui::CloseCurrentPopup();
6564 }
6565 break;
6566 case GUI_WARN_RESET_CONFIG:
6567 pushDestColor();
6568 if (ImGui::Button(_("Yes"))) {
6569 e->factoryReset();
6570 quit=true;
6571 quitNoSave=true;
6572 ImGui::CloseCurrentPopup();
6573 }
6574 popDestColor();
6575 ImGui::SameLine();
6576 if (ImGui::Button(_("No"))) {
6577 ImGui::CloseCurrentPopup();
6578 }
6579 break;
6580 case GUI_WARN_IMPORT:
6581 if (ImGui::Button(_("Got it"))) {
6582 switch (e->song.version) {
6583 case DIV_VERSION_MOD:
6584 tutorial.importedMOD=true;
6585 break;
6586 case DIV_VERSION_S3M:
6587 tutorial.importedS3M=true;
6588 break;
6589 case DIV_VERSION_XM:
6590 tutorial.importedXM=true;
6591 break;
6592 case DIV_VERSION_IT:
6593 tutorial.importedIT=true;
6594 break;
6595 }
6596 commitTutorial();
6597 ImGui::CloseCurrentPopup();
6598 }
6599 break;
6600 case GUI_WARN_GENERIC:
6601 if (ImGui::Button(_("OK"))) {
6602 ImGui::CloseCurrentPopup();
6603 }
6604 break;
6605 }
6606 ImGui::EndPopup();
6607 }
6608
6609 if (ImGui::BeginPopup("InsTypeList",ImGuiWindowFlags_NoMove|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings)) {
6610 char temp[1024];
6611 if (displayInsTypeListMakeInsSample==-2) {
6612 ImGui::Text(_("Drum kit mode:"));
6613 if (ImGui::RadioButton(_("Normal"),!makeDrumkitMode)) {
6614 makeDrumkitMode=false;
6615 }
6616 if (ImGui::RadioButton(_("12 samples per octave"),makeDrumkitMode)) {
6617 makeDrumkitMode=true;
6618 }
6619
6620 if (!makeDrumkitMode) {
6621 ImGui::Text(_("Starting octave"));
6622 ImGui::SameLine();
6623 if (ImGui::InputInt("##DKOctave",&makeDrumkitOctave,1,3)) {
6624 if (makeDrumkitOctave<0) makeDrumkitOctave=0;
6625 if (makeDrumkitOctave>9) makeDrumkitOctave=9;
6626 }
6627 }
6628
6629 ImGui::Separator();
6630 }
6631 for (DivInstrumentType& i: makeInsTypeList) {
6632 strncpy(temp,insTypes[i][0],1023);
6633 if (ImGui::MenuItem(temp)) {
6634 // create ins
6635 curIns=e->addInstrument(-1,i);
6636 if (curIns==-1) {
6637 showError(_("too many instruments!"));
6638 } else {
6639 if (displayInsTypeListMakeInsSample==-2) {
6640 e->song.ins[curIns]->type=i;
6641 e->song.ins[curIns]->name=_("Drum Kit");
6642 e->song.ins[curIns]->amiga.useNoteMap=true;
6643 if (i!=DIV_INS_AMIGA) e->song.ins[curIns]->amiga.useSample=true;
6644
6645 if (makeDrumkitMode) {
6646 for (int j=0; j<120; j++) {
6647 e->song.ins[curIns]->amiga.noteMap[j].freq=48;
6648 e->song.ins[curIns]->amiga.noteMap[j].dpcmFreq=15;
6649 e->song.ins[curIns]->amiga.noteMap[j].map=j%12;
6650 if ((j%12)>=e->song.sampleLen) continue;
6651 }
6652 } else {
6653 int index=-makeDrumkitOctave*12;
6654 for (int j=0; j<120; j++) {
6655 e->song.ins[curIns]->amiga.noteMap[j].freq=48;
6656 e->song.ins[curIns]->amiga.noteMap[j].dpcmFreq=15;
6657 if (index<0 || index>=e->song.sampleLen) {
6658 index++;
6659 continue;
6660 }
6661 e->song.ins[curIns]->amiga.noteMap[j].map=index++;
6662 }
6663 }
6664
6665 nextWindow=GUI_WINDOW_INS_EDIT;
6666 wavePreviewInit=true;
6667 updateFMPreview=true;
6668 } else if (displayInsTypeListMakeInsSample>=0 && displayInsTypeListMakeInsSample<(int)e->song.sample.size()) {
6669 e->song.ins[curIns]->type=i;
6670 e->song.ins[curIns]->name=e->song.sample[displayInsTypeListMakeInsSample]->name;
6671 e->song.ins[curIns]->amiga.initSample=displayInsTypeListMakeInsSample;
6672 if (i!=DIV_INS_AMIGA) e->song.ins[curIns]->amiga.useSample=true;
6673 nextWindow=GUI_WINDOW_INS_EDIT;
6674 wavePreviewInit=true;
6675 updateFMPreview=true;
6676 }
6677
6678 if (settings.blankIns) {
6679 e->song.ins[curIns]->fm.fb=0;
6680 for (int i=0; i<4; i++) {
6681 e->song.ins[curIns]->fm.op[i]=DivInstrumentFM::Operator();
6682 e->song.ins[curIns]->fm.op[i].ar=31;
6683 e->song.ins[curIns]->fm.op[i].dr=31;
6684 e->song.ins[curIns]->fm.op[i].rr=15;
6685 e->song.ins[curIns]->fm.op[i].tl=127;
6686 e->song.ins[curIns]->fm.op[i].dt=3;
6687
6688 e->song.ins[curIns]->esfm.op[i].ct=0;
6689 e->song.ins[curIns]->esfm.op[i].dt=0;
6690 e->song.ins[curIns]->esfm.op[i].modIn=0;
6691 e->song.ins[curIns]->esfm.op[i].outLvl=0;
6692 }
6693 }
6694
6695 MARK_MODIFIED;
6696 }
6697 }
6698 }
6699 ImGui::EndPopup();
6700 }
6701
6702 if (ImGui::BeginPopup("WaveSizeList",ImGuiWindowFlags_NoMove|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings)) {
6703 char temp[1024];
6704 for (FurnaceGUIWaveSizeEntry i: waveSizeList) {
6705 snprintf(temp,1023,"%d×%d (%s)",i.width,i.height,i.sys);
6706 if (ImGui::MenuItem(temp)) {
6707 // create wave
6708 curWave=e->addWave();
6709 if (curWave==-1) {
6710 showError(_("too many wavetables!"));
6711 } else {
6712 e->song.wave[curWave]->len=i.width;
6713 e->song.wave[curWave]->max=i.height-1;
6714 for (int j=0; j<i.width; j++) {
6715 e->song.wave[curWave]->data[j]=(j*i.height)/i.width;
6716 }
6717 MARK_MODIFIED;
6718 RESET_WAVE_MACRO_ZOOM;
6719 }
6720 }
6721 }
6722 ImGui::EndPopup();
6723 }
6724
6725 // TODO:
6726 // - multiple selection
6727 // - replace instrument
6728 centerNextWindow(_("Select Instrument"),canvasW,canvasH);
6729 if (ImGui::BeginPopupModal(_("Select Instrument"),NULL,ImGuiWindowFlags_AlwaysAutoResize)) {
6730 bool quitPlease=false;
6731 if (pendingInsSingle) {
6732 ImGui::Text(_("this is an instrument bank! select which one to use:"));
6733 } else {
6734 ImGui::AlignTextToFramePadding();
6735 ImGui::Text(_("this is an instrument bank! select which ones to load:"));
6736 ImGui::SameLine();
6737 if (ImGui::Button(_("All"))) {
6738 for (std::pair<DivInstrument*,bool>& i: pendingIns) {
6739 i.second=true;
6740 }
6741 }
6742 ImGui::SameLine();
6743 if (ImGui::Button(_("None"))) {
6744 for (std::pair<DivInstrument*,bool>& i: pendingIns) {
6745 i.second=false;
6746 }
6747 }
6748 }
6749 bool anySelected=false;
6750 float sizeY=ImGui::GetFrameHeightWithSpacing()*pendingIns.size();
6751 if (sizeY>(canvasH-180.0*dpiScale)) {
6752 sizeY=canvasH-180.0*dpiScale;
6753 if (sizeY<60.0*dpiScale) sizeY=60.0*dpiScale;
6754 }
6755 if (ImGui::BeginTable("PendingInsList",1,ImGuiTableFlags_ScrollY,ImVec2(0.0f,sizeY))) {
6756 for (size_t i=0; i<pendingIns.size(); i++) {
6757 ImGui::TableNextRow();
6758 ImGui::TableNextColumn();
6759 String id=fmt::sprintf("%d: %s",(int)i,pendingIns[i].first->name);
6760 if (pendingInsSingle) {
6761 if (ImGui::Selectable(id.c_str())) {
6762 pendingIns[i].second=true;
6763 quitPlease=true;
6764 }
6765 } else {
6766 ImGui::Checkbox(id.c_str(),&pendingIns[i].second);
6767 }
6768 if (pendingIns[i].second) anySelected=true;
6769 }
6770 ImGui::EndTable();
6771 }
6772 if (!pendingInsSingle) {
6773 ImGui::BeginDisabled(!anySelected);
6774 if (ImGui::Button(_("OK"))) {
6775 quitPlease=true;
6776 }
6777 ImGui::EndDisabled();
6778 ImGui::SameLine();
6779 }
6780 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6781 for (std::pair<DivInstrument*,bool>& i: pendingIns) {
6782 i.second=false;
6783 }
6784 quitPlease=true;
6785 }
6786 if (quitPlease) {
6787 ImGui::CloseCurrentPopup();
6788 for (std::pair<DivInstrument*,bool>& i: pendingIns) {
6789 if (!i.second || pendingInsSingle) {
6790 if (i.second) {
6791 if (curIns>=0 && curIns<(int)e->song.ins.size()) {
6792 *e->song.ins[curIns]=*i.first;
6793 // reset macro zoom
6794 memset(e->song.ins[curIns]->temp.vZoom,-1,sizeof(e->song.ins[curIns]->temp.vZoom));
6795 } else {
6796 showError(_("...but you haven't selected an instrument!"));
6797 }
6798 }
6799 delete i.first;
6800 } else {
6801 e->addInstrumentPtr(i.first);
6802 }
6803 }
6804 pendingIns.clear();
6805 }
6806 ImGui::EndPopup();
6807 }
6808
6809 // TODO: fix style
6810 centerNextWindow(_("Select Sample"),canvasW,canvasH);
6811 if (ImGui::BeginPopupModal(_("Select Sample"),NULL,ImGuiWindowFlags_AlwaysAutoResize)) {
6812 bool quitPlease=false;
6813
6814 ImGui::AlignTextToFramePadding();
6815 ImGui::Text(_("this is a sample bank! select which ones to load:"));
6816 ImGui::SameLine();
6817 if (ImGui::Button(_("All"))) {
6818 for (std::pair<DivSample*,bool>& i: pendingSamples) {
6819 i.second=true;
6820 }
6821 }
6822 ImGui::SameLine();
6823 if (ImGui::Button(_("None"))) {
6824 for (std::pair<DivSample*,bool>& i: pendingSamples) {
6825 i.second=false;
6826 }
6827 }
6828 bool reissueSearch=false;
6829
6830 bool anySelected=false;
6831 float sizeY=ImGui::GetFrameHeightWithSpacing()*pendingSamples.size();
6832 if (sizeY>(canvasH-180.0*dpiScale))
6833 {
6834 sizeY=canvasH-180.0*dpiScale;
6835 if (sizeY<60.0*dpiScale) sizeY=60.0*dpiScale;
6836 }
6837 if (ImGui::BeginTable("PendingSamplesList",1,ImGuiTableFlags_ScrollY,ImVec2(0.0f,sizeY)))
6838 {
6839 if (sampleBankSearchQuery.empty())
6840 {
6841 for (size_t i=0; i<pendingSamples.size(); i++)
6842 {
6843 ImGui::TableNextRow();
6844 ImGui::TableNextColumn();
6845 String id=fmt::sprintf("%d: %s",(int)i,pendingSamples[i].first->name);
6846 if (pendingInsSingle)
6847 {
6848 if (ImGui::Selectable(id.c_str()))
6849 {
6850 pendingSamples[i].second=true;
6851 quitPlease=true;
6852 }
6853 }
6854 else
6855 {
6856 // TODO:fixstyle from hereonwards
6857 ImGuiIO& io = ImGui::GetIO();
6858 if(ImGui::Checkbox(id.c_str(),&pendingSamples[i].second) && io.KeyShift)
6859 {
6860 for(int jj = (int)i - 1; jj >= 0; jj--)
6861 {
6862 if(pendingSamples[jj].second) //pressed shift and there's selected item above
6863 {
6864 for(int k = jj; k < (int)i; k++)
6865 {
6866 pendingSamples[k].second = true;
6867 }
6868
6869 break;
6870 }
6871 }
6872 }
6873 }
6874 if (pendingSamples[i].second) anySelected=true;
6875 }
6876 }
6877 else //display search results
6878 {
6879 if(reissueSearch)
6880 {
6881 String lowerCase=sampleBankSearchQuery;
6882
6883 for (char& ii: lowerCase)
6884 {
6885 if (ii>='A' && ii<='Z') ii+='a'-'A';
6886 }
6887
6888 sampleBankSearchResults.clear();
6889 for (int j=0; j < (int)pendingSamples.size(); j++)
6890 {
6891 String lowerCase1 = pendingSamples[j].first->name;
6892
6893 for (char& ii: lowerCase1)
6894 {
6895 if (ii>='A' && ii<='Z') ii+='a'-'A';
6896 }
6897
6898 if (lowerCase1.find(lowerCase)!=String::npos)
6899 {
6900 sampleBankSearchResults.push_back(std::make_pair(pendingSamples[j].first, pendingSamples[j].second));
6901 }
6902 }
6903 }
6904
6905 for (size_t i=0; i<sampleBankSearchResults.size(); i++)
6906 {
6907 ImGui::TableNextRow();
6908 ImGui::TableNextColumn();
6909 String id=fmt::sprintf("%d: %s",(int)i,sampleBankSearchResults[i].first->name);
6910
6911 ImGuiIO& io = ImGui::GetIO();
6912 if(ImGui::Checkbox(id.c_str(),&sampleBankSearchResults[i].second) && io.KeyShift)
6913 {
6914 for(int jj = (int)i - 1; jj >= 0; jj--)
6915 {
6916 if(sampleBankSearchResults[jj].second) //pressed shift and there's selected item above
6917 {
6918 for(int k = jj; k < (int)i; k++)
6919 {
6920 sampleBankSearchResults[k].second = true;
6921 }
6922
6923 break;
6924 }
6925 }
6926 }
6927 if (sampleBankSearchResults[i].second) anySelected=true;
6928 }
6929
6930 for (size_t i=0; i<pendingSamples.size(); i++)
6931 {
6932 if(sampleBankSearchResults.size() > 0)
6933 {
6934 for (size_t j=0; j<sampleBankSearchResults.size(); j++)
6935 {
6936 if(sampleBankSearchResults[j].first == pendingSamples[i].first && sampleBankSearchResults[j].second && pendingSamples[i].first != NULL)
6937 {
6938 pendingSamples[i].second = true;
6939 if (pendingSamples[i].second) anySelected=true;
6940 break;
6941 }
6942 }
6943 }
6944 }
6945 }
6946 ImGui::EndTable();
6947 }
6948
6949 ImGui::BeginDisabled(!anySelected);
6950 if (ImGui::Button(_("OK"))) {
6951 quitPlease=true;
6952 }
6953 ImGui::EndDisabled();
6954 ImGui::SameLine();
6955
6956 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
6957 for (std::pair<DivSample*,bool>& i: pendingSamples) {
6958 i.second=false;
6959 }
6960 quitPlease=true;
6961 }
6962 if (quitPlease)
6963 {
6964 ImGui::CloseCurrentPopup();
6965 int counter = 0;
6966 for (std::pair<DivSample*,bool>& i: pendingSamples)
6967 {
6968 if (!i.second)
6969 {
6970 delete i.first;
6971 }
6972 else
6973 {
6974 if(counter == 0 && replacePendingSample)
6975 {
6976 *e->song.sample[curSample]=*i.first;
6977 replacePendingSample = false;
6978 }
6979 else
6980 {
6981 e->addSamplePtr(i.first);
6982 }
6983 }
6984 counter++;
6985 }
6986
6987 curSample = (int)e->song.sample.size() - 1;
6988 pendingSamples.clear();
6989 }
6990
6991 ImGui::EndPopup();
6992 }
6993
6994 centerNextWindow(_("Import Raw Sample"),canvasW,canvasH);
6995 if (ImGui::BeginPopupModal(_("Import Raw Sample"),NULL,ImGuiWindowFlags_AlwaysAutoResize)) {
6996 ImGui::Text(_("Data type:"));
6997 for (int i=0; i<DIV_SAMPLE_DEPTH_MAX; i++) {
6998 if (sampleDepths[i]==NULL) continue;
6999 if (ImGui::RadioButton(sampleDepths[i],pendingRawSampleDepth==i)) pendingRawSampleDepth=i;
7000 }
7001
7002 if (pendingRawSampleDepth!=DIV_SAMPLE_DEPTH_8BIT && pendingRawSampleDepth!=DIV_SAMPLE_DEPTH_16BIT) {
7003 pendingRawSampleChannels=1;
7004 pendingRawSampleBigEndian=false;
7005 }
7006
7007 ImGui::AlignTextToFramePadding();
7008 ImGui::Text(_("Sample rate"));
7009 ImGui::SameLine();
7010 ImGui::SetNextItemWidth(120.0f*dpiScale);
7011 if (ImGui::InputInt("##RSRate",&pendingRawSampleRate,100,1000)) {
7012 if (pendingRawSampleRate<100) pendingRawSampleRate=100;
7013 if (pendingRawSampleRate>384000) pendingRawSampleRate=384000;
7014 }
7015
7016 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_8BIT || pendingRawSampleDepth==DIV_SAMPLE_DEPTH_16BIT) {
7017 ImGui::AlignTextToFramePadding();
7018 ImGui::Text(_("Channels"));
7019 ImGui::SameLine();
7020 ImGui::SetNextItemWidth(120.0f*dpiScale);
7021 if (ImGui::InputInt("##RSChans",&pendingRawSampleChannels,1,2)) {
7022 if (pendingRawSampleChannels<1) pendingRawSampleChannels=1;
7023 }
7024 ImGui::Text(_("(will be mixed down to mono)"));
7025 ImGui::Checkbox(_("Unsigned"),&pendingRawSampleUnsigned);
7026 }
7027
7028 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_16BIT) {
7029 ImGui::Checkbox(_("Big endian"),&pendingRawSampleBigEndian);
7030 }
7031
7032 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_YMZ_ADPCM ||
7033 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_QSOUND_ADPCM ||
7034 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_ADPCM_A ||
7035 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_ADPCM_B ||
7036 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_VOX ||
7037 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_4BIT) {
7038 ImGui::Checkbox(_("Swap nibbles"),&pendingRawSampleSwapNibbles);
7039 }
7040
7041 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_8BIT) {
7042 ImGui::Checkbox(_("Swap words"),&pendingRawSampleBigEndian);
7043 }
7044
7045 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_MULAW) {
7046 ImGui::Text(_("Encoding:"));
7047 ImGui::Indent();
7048 if (ImGui::RadioButton("G.711",pendingRawSampleSwapNibbles==0)) {
7049 pendingRawSampleSwapNibbles=0;
7050 }
7051 if (ImGui::RadioButton("Namco",pendingRawSampleSwapNibbles==1)) {
7052 pendingRawSampleSwapNibbles=1;
7053 }
7054 ImGui::Unindent();
7055 }
7056
7057 if (pendingRawSampleDepth==DIV_SAMPLE_DEPTH_1BIT ||
7058 pendingRawSampleDepth==DIV_SAMPLE_DEPTH_1BIT_DPCM) {
7059 ImGui::Checkbox(_("Reverse bit order"),&pendingRawSampleSwapNibbles);
7060 }
7061
7062 if (ImGui::Button(_("OK"))) {
7063 DivSample* s=e->sampleFromFileRaw(pendingRawSample.c_str(),(DivSampleDepth)pendingRawSampleDepth,pendingRawSampleChannels,pendingRawSampleBigEndian,pendingRawSampleUnsigned,pendingRawSampleSwapNibbles,pendingRawSampleRate);
7064 if (s==NULL) {
7065 showError(e->getLastError());
7066 } else {
7067 if (pendingRawSampleReplace) {
7068 if (curSample>=0 && curSample<(int)e->song.sample.size()) {
7069 e->lockEngine([this,s]() {
7070 // if it crashes here please tell me...
7071 DivSample* oldSample=e->song.sample[curSample];
7072 e->song.sample[curSample]=s;
7073 delete oldSample;
7074 e->renderSamples();
7075 MARK_MODIFIED;
7076 });
7077 updateSampleTex=true;
7078 } else {
7079 showError(_("...but you haven't selected a sample!"));
7080 delete s;
7081 }
7082 } else {
7083 if (e->addSamplePtr(s)==-1) {
7084 showError(e->getLastError());
7085 } else {
7086 MARK_MODIFIED;
7087 }
7088 }
7089 }
7090 ImGui::CloseCurrentPopup();
7091 }
7092 ImGui::SameLine();
7093 if (ImGui::Button(_("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
7094 ImGui::CloseCurrentPopup();
7095 }
7096 ImGui::EndPopup();
7097 }
7098
7099 if (ImGui::BeginPopup("EditString",ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings)) {
7100 if (editString==NULL) {
7101 ImGui::Text(_("Error! No string provided!"));
7102 } else {
7103 if (displayEditString) {
7104 ImGui::SetItemDefaultFocus();
7105 ImGui::SetKeyboardFocusHere();
7106 }
7107 ImGui::InputText("##StringVal",editString);
7108 }
7109 displayEditString=false;
7110 ImGui::SameLine();
7111 if (ImGui::Button(_("OK")) || ImGui::IsKeyPressed(ImGuiKey_Enter,false)) {
7112 editString=NULL;
7113 ImGui::CloseCurrentPopup();
7114 }
7115 ImGui::EndPopup();
7116 } else {
7117 editString=NULL;
7118 }
7119
7120 MEASURE_END(popup);
7121
7122 #ifdef NO_INTRO
7123 introPos=12.0;
7124 #else
7125 if ((!tutorial.introPlayed || settings.alwaysPlayIntro!=0) && renderBackend!=GUI_BACKEND_SOFTWARE) {
7126 MEASURE_BEGIN(intro);
7127 initialScreenWipe=0;
7128 if (settings.alwaysPlayIntro==1) {
7129 shortIntro=true;
7130 }
7131 drawIntro(introPos);
7132 MEASURE_END(intro);
7133 } else {
7134 introPos=12.0;
7135 }
7136 #endif
7137
7138 #ifdef DIV_UNSTABLE
7139 {
7140 ImDrawList* dl=ImGui::GetForegroundDrawList();
7141 ImVec2 markPos=ImVec2(canvasW-ImGui::CalcTextSize(DIV_VERSION).x-6.0*dpiScale,4.0*dpiScale);
7142 ImVec4 markColor=uiColors[GUI_COLOR_TEXT];
7143 markColor.w=0.67f;
7144
7145 dl->AddText(markPos,ImGui::ColorConvertFloat4ToU32(markColor),DIV_VERSION);
7146 }
7147 #endif
7148
7149 if (settings.displayRenderTime) {
7150 String renderTime=fmt::sprintf("%.0fµs",ImGui::GetIO().DeltaTime*1000000.0);
7151 String renderTime2=fmt::sprintf("%.1f FPS",1.0/ImGui::GetIO().DeltaTime);
7152 ImDrawList* dl=ImGui::GetForegroundDrawList();
7153 ImVec2 markPos=ImVec2(canvasW-ImGui::CalcTextSize(renderTime.c_str()).x-60.0*dpiScale,4.0*dpiScale);
7154 ImVec2 markPos2=ImVec2(canvasW-ImGui::CalcTextSize(renderTime2.c_str()).x-160.0*dpiScale,4.0*dpiScale);
7155
7156 dl->AddText(markPos,0xffffffff,renderTime.c_str());
7157 dl->AddText(markPos2,0xffffffff,renderTime2.c_str());
7158
7159 //logV("%s (%s)",renderTime,renderTime2);
7160 }
7161
7162 layoutTimeEnd=SDL_GetPerformanceCounter();
7163
7164 // backup trigger
7165 if (modified && settings.backupEnable) {
7166 if (backupTimer>0) {
7167 backupTimer=(backupTimer-ImGui::GetIO().DeltaTime);
7168 if (backupTimer<=0) {
7169 backupTask=std::async(std::launch::async,[this]() -> bool {
7170 backupLock.lock();
7171 logV("backupPath: %s",backupPath);
7172 logV("curFileName: %s",curFileName);
7173 if (curFileName.find(backupPath)==0) {
7174 logD("backup file open. not saving backup.");
7175 backupTimer=settings.backupInterval;
7176 backupLock.unlock();
7177 return true;
7178 }
7179 if (!dirExists(backupPath.c_str())) {
7180 if (!makeDir(backupPath.c_str())) {
7181 logW("could not create backup directory!");
7182 backupTimer=settings.backupInterval;
7183 backupLock.unlock();
7184 return false;
7185 }
7186 }
7187 logD("saving backup...");
7188 SafeWriter* w=e->saveFur(true,true);
7189 logV("writing file...");
7190
7191 if (w!=NULL) {
7192 size_t sepPos=curFileName.rfind(DIR_SEPARATOR);
7193 String backupPreBaseName;
7194 String backupBaseName;
7195 String backupFileName;
7196 if (sepPos==String::npos) {
7197 backupPreBaseName=curFileName;
7198 } else {
7199 backupPreBaseName=curFileName.substr(sepPos+1);
7200 }
7201
7202 size_t dotPos=backupPreBaseName.rfind('.');
7203 if (dotPos!=String::npos) {
7204 backupPreBaseName=backupPreBaseName.substr(0,dotPos);
7205 }
7206
7207 for (char i: backupPreBaseName) {
7208 if (backupBaseName.size()>=48) break;
7209 if ((i>='0' && i<='9') || (i>='A' && i<='Z') || (i>='a' && i<='z') || i=='_' || i=='-' || i==' ') backupBaseName+=i;
7210 }
7211
7212 if (backupBaseName.empty()) backupBaseName="untitled";
7213
7214 backupFileName=backupBaseName;
7215
7216 time_t curTime=time(NULL);
7217 struct tm curTM;
7218 #ifdef _WIN32
7219 struct tm* tempTM=localtime(&curTime);
7220 if (tempTM==NULL) {
7221 backupFileName+="-unknownTime.fur";
7222 } else {
7223 curTM=*tempTM;
7224 backupFileName+=fmt::sprintf("-%d%.2d%.2d-%.2d%.2d%.2d.fur",curTM.tm_year+1900,curTM.tm_mon+1,curTM.tm_mday,curTM.tm_hour,curTM.tm_min,curTM.tm_sec);
7225 }
7226 #else
7227 if (localtime_r(&curTime,&curTM)==NULL) {
7228 backupFileName+="-unknownTime.fur";
7229 } else {
7230 backupFileName+=fmt::sprintf("-%d%.2d%.2d-%.2d%.2d%.2d.fur",curTM.tm_year+1900,curTM.tm_mon+1,curTM.tm_mday,curTM.tm_hour,curTM.tm_min,curTM.tm_sec);
7231 }
7232 #endif
7233
7234 String finalPath=backupPath+String(DIR_SEPARATOR_STR)+backupFileName;
7235
7236 FILE* outFile=ps_fopen(finalPath.c_str(),"wb");
7237 if (outFile!=NULL) {
7238 if (fwrite(w->getFinalBuf(),1,w->size(),outFile)!=w->size()) {
7239 logW("did not write backup entirely: %s!",strerror(errno));
7240 }
7241 fclose(outFile);
7242 } else {
7243 logW("could not save backup: %s!",strerror(errno));
7244 }
7245 w->finish();
7246
7247 // delete previous backup if there are too many
7248 delFirstBackup(backupBaseName);
7249 }
7250 logD("backup saved.");
7251 backupTimer=settings.backupInterval;
7252 backupLock.unlock();
7253 return true;
7254 });
7255 }
7256 }
7257 }
7258
7259 sampleMapWaitingInput=(curWindow==GUI_WINDOW_INS_EDIT && sampleMapFocused);
7260
7261 curWindowThreadSafe=curWindow;
7262
7263 if (curWindow!=curWindowLast) {
7264 int curWindowCat=0;
7265 int lastWindowCat=0;
7266
7267 switch (curWindow) {
7268 case GUI_WINDOW_WAVE_LIST:
7269 case GUI_WINDOW_WAVE_EDIT:
7270 curWindowCat=1;
7271 break;
7272 case GUI_WINDOW_SAMPLE_LIST:
7273 case GUI_WINDOW_SAMPLE_EDIT:
7274 curWindowCat=2;
7275 break;
7276 default:
7277 curWindowCat=0;
7278 break;
7279 }
7280 switch (curWindowLast) {
7281 case GUI_WINDOW_WAVE_LIST:
7282 case GUI_WINDOW_WAVE_EDIT:
7283 lastWindowCat=1;
7284 break;
7285 case GUI_WINDOW_SAMPLE_LIST:
7286 case GUI_WINDOW_SAMPLE_EDIT:
7287 lastWindowCat=2;
7288 break;
7289 default:
7290 lastWindowCat=0;
7291 break;
7292 }
7293
7294 if (curWindowCat!=lastWindowCat) {
7295 switch (lastWindowCat) {
7296 case 0:
7297 e->autoNoteOffAll();
7298 failedNoteOn=false;
7299 break;
7300 case 1:
7301 e->stopWavePreview();
7302 break;
7303 case 2:
7304 e->stopSamplePreview();
7305 break;
7306 }
7307 }
7308 }
7309
7310 if (!settings.renderClearPos || renderBackend==GUI_BACKEND_METAL) {
7311 rend->clear(uiColors[GUI_COLOR_BACKGROUND]);
7312 }
7313 renderTimeBegin=SDL_GetPerformanceCounter();
7314 ImGui::Render();
7315 renderTimeEnd=SDL_GetPerformanceCounter();
7316 drawTimeBegin=SDL_GetPerformanceCounter();
7317 rend->renderGUI();
7318 if (mustClear) {
7319 rend->clear(ImVec4(0,0,0,0));
7320 mustClear--;
7321 if (mustClear==0) e->everythingOK();
7322 } else {
7323 if (initialScreenWipe>0.0f && !settings.disableFadeIn) {
7324 WAKE_UP;
7325 initialScreenWipe-=ImGui::GetIO().DeltaTime*5.0f;
7326 if (initialScreenWipe>0.0f) {
7327 rend->wipe(pow(initialScreenWipe,2.0f));
7328 }
7329 } else if (settings.disableFadeIn) {
7330 initialScreenWipe=0.0f;
7331 }
7332 }
7333 drawTimeEnd=SDL_GetPerformanceCounter();
7334 swapTimeBegin=SDL_GetPerformanceCounter();
7335 if (!settings.vsync || !rend->canVSync()) {
7336 if (settings.frameRateLimit>0) {
7337 unsigned int presentDelay=SDL_GetPerformanceFrequency()/settings.frameRateLimit;
7338 if ((nextPresentTime-swapTimeBegin)<presentDelay) {
7339 #ifdef _WIN32
7340 unsigned int mDivider=SDL_GetPerformanceFrequency()/1000;
7341 Sleep((unsigned int)(nextPresentTime-swapTimeBegin)/mDivider);
7342 #else
7343 unsigned int mDivider=SDL_GetPerformanceFrequency()/1000000;
7344 usleep((unsigned int)(nextPresentTime-swapTimeBegin)/mDivider);
7345 #endif
7346 nextPresentTime+=presentDelay;
7347 } else {
7348 nextPresentTime=swapTimeBegin+presentDelay;
7349 }
7350 }
7351 }
7352 rend->present();
7353 if (settings.renderClearPos && renderBackend!=GUI_BACKEND_METAL) {
7354 rend->clear(uiColors[GUI_COLOR_BACKGROUND]);
7355 }
7356 swapTimeEnd=SDL_GetPerformanceCounter();
7357
7358 layoutTimeDelta=layoutTimeEnd-layoutTimeBegin;
7359 renderTimeDelta=renderTimeEnd-renderTimeBegin;
7360 drawTimeDelta=drawTimeEnd-drawTimeBegin;
7361 swapTimeDelta=swapTimeEnd-swapTimeBegin;
7362 eventTimeDelta=eventTimeEnd-eventTimeBegin;
7363
7364 soloTimeout-=ImGui::GetIO().DeltaTime;
7365 if (soloTimeout<0) {
7366 soloTimeout=0;
7367 } else {
7368 WAKE_UP;
7369 }
7370
7371 if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
7372 exitDisabledTimer=0;
7373 }
7374
7375 wheelX=0;
7376 wheelY=0;
7377 wantScrollListIns=false;
7378 wantScrollListWave=false;
7379 wantScrollListSample=false;
7380
7381 pressedPoints.clear();
7382 releasedPoints.clear();
7383
7384 if (willCommit) {
7385 commitSettings();
7386 willCommit=false;
7387 }
7388
7389 // To check for instrument editor modification, we need an up-to-date `insEditMayBeDirty`
7390 // (based on incoming user input events), and we want any possible instrument modifications
7391 // to already have been made.
7392 checkRecordInstrumentUndoStep();
7393
7394 // the following code handles order lock (if it is enabled).
7395 if (orderLock) {
7396 cursor.order=curOrder;
7397 selStart.order=curOrder;
7398 selEnd.order=curOrder;
7399 }
7400
7401 if (shallDetectScale) {
7402 if (--shallDetectScale<1) {
7403 if (settings.dpiScale<0.5f) {
7404 const char* videoBackend=SDL_GetCurrentVideoDriver();
7405 double newScale=getScaleFactor(videoBackend,sdlWin);
7406 if (newScale<0.1f) {
7407 logW("scale what?");
7408 newScale=1.0f;
7409 }
7410
7411 if (newScale!=dpiScale) {
7412 logD("auto UI scale changed (%f != %f) - applying settings...",newScale,dpiScale);
7413 ImGui::GetIO().Fonts->Clear();
7414
7415 applyUISettings();
7416 }
7417 }
7418 }
7419 }
7420
7421 if (fontsFailed) {
7422 showError(_("it appears I couldn't load these fonts. any setting you can check?"));
7423 logE("couldn't load fonts");
7424 ImGui::GetIO().Fonts->Clear();
7425 mainFont=ImGui::GetIO().Fonts->AddFontDefault();
7426 patFont=mainFont;
7427 bigFont=mainFont;
7428 headFont=mainFont;
7429 }
7430
7431 if (!editOptsVisible) {
7432 latchTarget=0;
7433 latchNibble=false;
7434 }
7435
7436 if (SDL_GetWindowFlags(sdlWin)&SDL_WINDOW_MINIMIZED) {
7437 SDL_Delay(100);
7438 }
7439 }
7440 return false;
7441 }
7442
7443 bool FurnaceGUI::init() {
7444 logI("initializing GUI.");
7445
7446 opTouched=new bool[DIV_MAX_PATTERNS*DIV_MAX_ROWS];
7447
7448 syncState();
7449 syncSettings();
7450 syncTutorial();
7451
7452 recentFile.clear();
7453 for (int i=0; i<settings.maxRecentFile; i++) {
7454 String r=e->getConfString(fmt::sprintf("recentFile%d",i),"");
7455 if (!r.empty()) {
7456 recentFile.push_back(r);
7457 }
7458 }
7459
7460 if (!settings.persistFadeOut) {
7461 audioExportOptions.loops=settings.exportLoops;
7462 audioExportOptions.fadeOut=settings.exportFadeOut;
7463 }
7464
7465 initSystemPresets();
7466
7467 e->setAutoNotePoly(noteInputPoly);
7468
7469 SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,"1");
7470 #if SDL_VERSION_ATLEAST(2,0,17)
7471 SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS,"0");
7472 #endif
7473 SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS,"0");
7474 // don't disable compositing on KWin
7475 #if SDL_VERSION_ATLEAST(2,0,22)
7476 logV("setting window type to NORMAL.");
7477 SDL_SetHint(SDL_HINT_X11_WINDOW_TYPE,"_NET_WM_WINDOW_TYPE_NORMAL");
7478 #endif
7479
7480 // This sets the icon in wayland
7481 SDL_setenv("SDL_VIDEO_WAYLAND_WMCLASS", FURNACE_APP_ID, 0);
7482
7483 // initialize SDL
7484 logD("initializing video...");
7485 if (SDL_Init(SDL_INIT_VIDEO)!=0) {
7486 logE("could not initialize video! %s",SDL_GetError());
7487 return false;
7488 }
7489
7490 #ifdef IS_MOBILE
7491 logD("initializing haptic...");
7492 if (SDL_Init(SDL_INIT_HAPTIC)!=0) {
7493 logW("could not initialize haptic! %s",SDL_GetError());
7494 }
7495 #endif
7496
7497 const char* videoBackend=SDL_GetCurrentVideoDriver();
7498 if (videoBackend!=NULL) {
7499 logV("video backend: %s",videoBackend);
7500 if (strcmp(videoBackend,"wayland")==0 ||
7501 strcmp(videoBackend,"cocoa")==0 ||
7502 strcmp(videoBackend,"uikit")==0) {
7503 sysManagedScale=true;
7504 logV("scaling managed by system.");
7505 } else {
7506 logV("scaling managed by application.");
7507 }
7508 } else {
7509 logV("could not get video backend name!");
7510 }
7511
7512 // get scale factor
7513 if (settings.dpiScale>=0.5f) {
7514 logD("setting UI scale factor from config (%f).",settings.dpiScale);
7515 dpiScale=settings.dpiScale;
7516 } else {
7517 logD("auto-detecting UI scale factor.");
7518 dpiScale=getScaleFactor(videoBackend,sdlWin);
7519 logD("scale factor: %f",dpiScale);
7520 if (dpiScale<0.1f) {
7521 logW("scale what?");
7522 dpiScale=1.0f;
7523 }
7524 }
7525
7526 #if !(defined(__APPLE__) || defined(_WIN32))
7527 // get the icon (on macOS and Windows the icon is bundled with the app)
7528 const FurnaceGUIImage* furIcon=getImage(GUI_IMAGE_ICON);
7529 SDL_Surface* icon=NULL;
7530 if (furIcon!=NULL) {
7531 icon=SDL_CreateRGBSurfaceFrom(furIcon->data,furIcon->width,furIcon->height,32,256*4,0xff,0xff00,0xff0000,0xff000000);
7532 } else {
7533 logE("furIcon is NULL!");
7534 }
7535 #endif
7536
7537 #ifdef IS_MOBILE
7538 scrW=960;
7539 scrH=540;
7540 scrX=0;
7541 scrY=0;
7542 #else
7543 scrW=scrConfW=e->getConfInt("lastWindowWidth",GUI_WIDTH_DEFAULT);
7544 scrH=scrConfH=e->getConfInt("lastWindowHeight",GUI_HEIGHT_DEFAULT);
7545 scrX=scrConfX=e->getConfInt("lastWindowX",SDL_WINDOWPOS_CENTERED);
7546 scrY=scrConfY=e->getConfInt("lastWindowY",SDL_WINDOWPOS_CENTERED);
7547 scrMax=e->getConfBool("lastWindowMax",false);
7548 #endif
7549 portrait=(scrW<scrH);
7550 logV("portrait: %d (%dx%d)",portrait,scrW,scrH);
7551
7552 // if old config, scale size as it was stored unscaled before
7553 if (e->getConfInt("configVersion",0)<122 && !sysManagedScale) {
7554 logD("scaling window size to scale factor because configVersion is not present.");
7555 scrW*=dpiScale;
7556 scrH*=dpiScale;
7557 }
7558
7559 // predict the canvas size
7560 if (sysManagedScale) {
7561 canvasW=scrW*dpiScale;
7562 canvasH=scrH*dpiScale;
7563 } else {
7564 canvasW=scrW;
7565 canvasH=scrH;
7566 }
7567
7568 #ifndef IS_MOBILE
7569 SDL_Rect displaySize;
7570 #endif
7571
7572 #ifndef IS_MOBILE
7573 // if window would spawn out of bounds, force it to be get default position
7574 SDL_Rect bounds;
7575 if (!detectOutOfBoundsWindow(bounds)) {
7576 scrMax=false;
7577 scrX=scrConfX=SDL_WINDOWPOS_CENTERED;
7578 scrY=scrConfY=SDL_WINDOWPOS_CENTERED;
7579
7580 // make sure our window isn't big
7581 /*if (bounds.w<scrW) {
7582 logD("resizing width because it does not fit");
7583 scrW=bounds.w-OOB_PIXELS_SAFETY*2;
7584 if (scrW<200) scrW=200;
7585 }
7586 if (bounds.h<scrH) {
7587 logD("resizing height because it does not fit");
7588 scrH=bounds.h-OOB_PIXELS_SAFETY*2;
7589 if (scrH<100) scrH=100;
7590 }*/
7591 }
7592 #endif
7593
7594 logV("window size: %dx%d",scrW,scrH);
7595
7596 if (!initRender()) {
7597 if (settings.renderBackend!="Software") {
7598 settings.renderBackend="Software";
7599 e->setConf("renderBackend","Software");
7600 e->saveConf();
7601 lastError=fmt::sprintf(_("could not init renderer!\nfalling back to software renderer. please restart Furnace."));
7602 } else if (settings.renderBackend=="SDL") {
7603 lastError=fmt::sprintf(_("could not init renderer! %s\nfalling back to software renderer. please restart Furnace."),SDL_GetError());
7604 settings.renderBackend="Software";
7605 e->setConf("renderBackend","Software");
7606 e->saveConf();
7607 } else {
7608 lastError=fmt::sprintf(_("could not init renderer!"));
7609 }
7610 return false;
7611 }
7612
7613 rend->preInit(e->getConfObject());
7614
7615 logD("creating window...");
7616 sdlWin=SDL_CreateWindow("Furnace",scrX,scrY,scrW,scrH,SDL_WINDOW_RESIZABLE|SDL_WINDOW_ALLOW_HIGHDPI|(scrMax?SDL_WINDOW_MAXIMIZED:0)|(fullScreen?SDL_WINDOW_FULLSCREEN_DESKTOP:0)|rend->getWindowFlags());
7617 if (sdlWin==NULL) {
7618 const char* sdlErr=SDL_GetError();
7619 lastError=fmt::sprintf(_("could not open window! %s"),sdlErr);
7620 if (settings.renderBackend!="Software" && strstr(sdlErr,"matching")!=NULL) {
7621 settings.renderBackend="Software";
7622 e->setConf("renderBackend","Software");
7623 e->saveConf();
7624 lastError+=_("\nfalling back to software renderer. please restart Furnace.");
7625 }
7626 return false;
7627 }
7628
7629 #ifndef IS_MOBILE
7630 if (SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(sdlWin),&displaySize)==0) {
7631 bool mustChange=false;
7632 if (scrW>((displaySize.w)-48) && scrH>((displaySize.h)-64)) {
7633 // maximize
7634 if (!settings.noMaximizeWorkaround) {
7635 SDL_MaximizeWindow(sdlWin);
7636 logD("maximizing as it doesn't fit (%dx%d+%d+%d).",displaySize.w,displaySize.h,displaySize.x,displaySize.y);
7637 }
7638 }
7639 if (scrW>displaySize.w) {
7640 scrW=(displaySize.w)-32;
7641 mustChange=true;
7642 }
7643 if (scrH>displaySize.h) {
7644 scrH=(displaySize.h)-32;
7645 mustChange=true;
7646 }
7647 if (mustChange) {
7648 portrait=(scrW<scrH);
7649 logV("portrait: %d (%dx%d)",portrait,scrW,scrH);
7650 if (!fullScreen) {
7651 logD("setting window size to %dx%d as it goes off bounds (%dx%d+%d+%d).",scrW,scrH,displaySize.w,displaySize.h,displaySize.x,displaySize.y);
7652 SDL_SetWindowSize(sdlWin,scrW,scrH);
7653 }
7654 }
7655 }
7656 #endif
7657
7658 #ifdef IS_MOBILE
7659 SDL_GetWindowSize(sdlWin,&scrW,&scrH);
7660 portrait=(scrW<scrH);
7661 logV("portrait: %d (%dx%d)",portrait,scrW,scrH);
7662 #endif
7663
7664 #if !(defined(__APPLE__) || defined(_WIN32))
7665 if (icon!=NULL) {
7666 SDL_SetWindowIcon(sdlWin,icon);
7667 SDL_FreeSurface(icon);
7668 } else {
7669 logW("could not create icon!");
7670 }
7671 #endif
7672
7673 int numDriversA=SDL_GetNumAudioDrivers();
7674 if (numDriversA<0) {
7675 logW("could not list audio drivers! %s",SDL_GetError());
7676 } else {
7677 for (int i=0; i<numDriversA; i++) {
7678 const char* r=SDL_GetAudioDriver(i);
7679 if (r==NULL) continue;
7680 if (strcmp(r,"disk")==0) continue;
7681 if (strcmp(r,"dummy")==0) continue;
7682 availAudioDrivers.push_back(String(r));
7683 }
7684 }
7685
7686 int numDrivers=SDL_GetNumRenderDrivers();
7687 if (numDrivers<0) {
7688 logW("could not list render drivers! %s",SDL_GetError());
7689 } else {
7690 SDL_RendererInfo ri;
7691 logV("available render drivers:");
7692 for (int i=0; i<numDrivers; i++) {
7693 int r=SDL_GetRenderDriverInfo(i,&ri);
7694 if (r!=0) continue;
7695 availRenderDrivers.push_back(String(ri.name));
7696 logV("- %s",ri.name);
7697 }
7698 }
7699
7700 if (!settings.renderDriver.empty()) {
7701 SDL_SetHint(SDL_HINT_RENDER_DRIVER,settings.renderDriver.c_str());
7702 }
7703
7704 logD("starting render backend...");
7705 if (!rend->init(sdlWin,settings.vsync)) {
7706 logE("it failed...");
7707 if (settings.renderBackend!="Software") {
7708 settings.renderBackend="Software";
7709 e->setConf("renderBackend","Software");
7710 e->saveConf();
7711 lastError=fmt::sprintf(_("could not init renderer!\nfalling back to software renderer. please restart Furnace."));
7712 } else if (settings.renderBackend=="SDL") {
7713 lastError=fmt::sprintf(_("could not init renderer! %s\nfalling back to software renderer. please restart Furnace."),SDL_GetError());
7714 settings.renderBackend="Software";
7715 e->setConf("renderBackend","Software");
7716 e->saveConf();
7717 } else {
7718 lastError=fmt::sprintf(_("could not init renderer!"));
7719 }
7720 return false;
7721 }
7722 logV("render backend started");
7723
7724 // set best texture format
7725 unsigned int availTexFormats=rend->getTextureFormats();
7726 if (availTexFormats&GUI_TEXFORMAT_ABGR32) {
7727 bestTexFormat=GUI_TEXFORMAT_ABGR32;
7728 } else if (availTexFormats&GUI_TEXFORMAT_ARGB32) {
7729 bestTexFormat=GUI_TEXFORMAT_ARGB32;
7730 } else if (availTexFormats&GUI_TEXFORMAT_RGBA32) {
7731 bestTexFormat=GUI_TEXFORMAT_RGBA32;
7732 } else if (availTexFormats&GUI_TEXFORMAT_BGRA32) {
7733 bestTexFormat=GUI_TEXFORMAT_BGRA32;
7734 }
7735
7736 // try acquiring the canvas size
7737 if (!rend->getOutputSize(canvasW,canvasH)) {
7738 logW("could not get renderer output size!");
7739 } else {
7740 logV("canvas size: %dx%d",canvasW,canvasH);
7741 }
7742
7743 // special consideration for Wayland
7744 if (settings.dpiScale<0.5f) {
7745 if (strcmp(videoBackend,"wayland")==0) {
7746 int realW=scrW;
7747 int realH=scrH;
7748
7749 SDL_GetWindowSize(sdlWin,&realW,&realH);
7750
7751 if (realW<1) {
7752 logW("screen width is zero!\n");
7753 dpiScale=1.0;
7754 } else {
7755 dpiScale=(double)canvasW/(double)realW;
7756 logV("we're on Wayland... scaling factor: %f",dpiScale);
7757 }
7758 }
7759 }
7760
7761 updateWindowTitle();
7762 updateROMExportAvail();
7763
7764 logV("max texture size: %dx%d",rend->getMaxTextureWidth(),rend->getMaxTextureHeight());
7765
7766 rend->clear(ImVec4(0.0,0.0,0.0,1.0));
7767 rend->present();
7768
7769 logD("preparing user interface...");
7770 IMGUI_CHECKVERSION();
7771 ImGui::CreateContext();
7772 rend->initGUI(sdlWin);
7773
7774 ImGuiLocEntry guiLocalization[12];
7775
7776 guiLocalization[0].Key=ImGuiLocKey_TableSizeOne;
7777 guiLocalization[0].Text=_("Size column to fit###SizeOne");
7778 guiLocalization[1].Key=ImGuiLocKey_TableSizeAllFit;
7779 guiLocalization[1].Text=_("Size all columns to fit###SizeAll");
7780 guiLocalization[2].Key=ImGuiLocKey_TableSizeAllDefault;
7781 guiLocalization[2].Text=_("Size all columns to default###SizeAll");
7782 guiLocalization[3].Key=ImGuiLocKey_TableResetOrder;
7783 guiLocalization[3].Text=_("Reset order###ResetOrder");
7784 guiLocalization[4].Key=ImGuiLocKey_WindowingMainMenuBar;
7785 guiLocalization[4].Text=_("(Main menu bar)");
7786 guiLocalization[5].Key=ImGuiLocKey_WindowingPopup;
7787 guiLocalization[5].Text=_("(Popup)");
7788 guiLocalization[6].Key=ImGuiLocKey_WindowingUntitled;
7789 guiLocalization[6].Text=_("(Untitled)");
7790 guiLocalization[7].Key=ImGuiLocKey_OpenLink_s;
7791 guiLocalization[7].Text=_("Open '%s'");
7792 guiLocalization[8].Key=ImGuiLocKey_CopyLink;
7793 guiLocalization[8].Text=_("Copy Link###CopyLink");
7794 guiLocalization[9].Key=ImGuiLocKey_DockingHideTabBar;
7795 guiLocalization[9].Text=_("Hide tab bar###HideTabBar");
7796 guiLocalization[10].Key=ImGuiLocKey_DockingHoldShiftToDock;
7797 guiLocalization[10].Text=_("Hold SHIFT to enable Docking window.");
7798 guiLocalization[11].Key=ImGuiLocKey_DockingDragToUndockOrMoveNode,
7799 guiLocalization[11].Text=_("Click and drag to move or undock whole node.");
7800
7801 ImGui::LocalizeRegisterEntries(guiLocalization,12);
7802
7803 const char* localeSettings=_("LocaleSettings: ccjk");
7804 if (strlen(localeSettings)<20) {
7805 logE("the LocaleSettings string is incomplete!");
7806 } else {
7807 localeRequiresChinese=(localeSettings[16]=='C');
7808 localeRequiresChineseTrad=(localeSettings[17]=='C');
7809 localeRequiresJapanese=(localeSettings[18]=='J');
7810 localeRequiresKorean=(localeSettings[19]=='K');
7811 if (strlen(localeSettings)>21) {
7812 if (localeSettings[20]==' ') {
7813 ImWchar next=0;
7814 for (const char* i=&localeSettings[21]; *i; i++) {
7815 if (((*i)>='0' && (*i)<='9') || ((*i)>='A' && (*i)<='F')) {
7816 next<<=4;
7817 if ((*i)>='0' && (*i)<='9') {
7818 next|=(*i)-'0';
7819 } else {
7820 next|=(*i)-'A'+10;
7821 }
7822 } else {
7823 localeExtraRanges.push_back(next);
7824 next=0;
7825 }
7826 }
7827 if (next!=0) {
7828 localeExtraRanges.push_back(next);
7829 }
7830 localeExtraRanges.push_back(0);
7831 }
7832 }
7833 }
7834 if (!localeExtraRanges.empty()) {
7835 logV("locale extra ranges:");
7836 for (ImWchar i: localeExtraRanges) {
7837 logV("%x",i);
7838 }
7839 }
7840
7841 loadUserPresets(true);
7842
7843 applyUISettings();
7844
7845 logD("building font...");
7846 if (rend->areTexturesSquare()) {
7847 ImGui::GetIO().Fonts->Flags|=ImFontAtlasFlags_Square;
7848 }
7849
7850 logD("preparing layout...");
7851 strncpy(finalLayoutPath,(e->getConfigPath()+String(LAYOUT_INI)).c_str(),4095);
7852 backupPath=e->getConfigPath();
7853 if (backupPath.size()>0) {
7854 if (backupPath[backupPath.size()-1]==DIR_SEPARATOR) backupPath.resize(backupPath.size()-1);
7855 }
7856 backupPath+=String(BACKUPS_DIR);
7857 prepareLayout();
7858
7859 ImGui::GetIO().ConfigFlags|=ImGuiConfigFlags_DockingEnable;
7860 toggleMobileUI(mobileUI,true);
7861
7862 firstFrame=true;
7863
7864 userEvents=SDL_RegisterEvents(1);
7865
7866 e->setMidiCallback([this](const TAMidiMessage& msg) -> int {
7867 if (introPos<11.0) return -3;
7868 midiLock.lock();
7869 midiQueue.push(msg);
7870 if (userEvents!=0xffffffff && midiWakeUp) {
7871 midiWakeUp=false;
7872 userEvent.user.type=userEvents;
7873 userEvent.user.code=0;
7874 userEvent.user.data1=NULL;
7875 userEvent.user.data2=NULL;
7876 SDL_PushEvent(&userEvent);
7877 }
7878 midiLock.unlock();
7879 e->setMidiBaseChan(cursor.xCoarse);
7880 if (msg.type==TA_MIDI_SYSEX) return -3;
7881 if (midiMap.valueInputStyle!=0 && cursor.xFine!=0 && edit) return -3;
7882 if (!midiMap.noteInput) return -3;
7883 if (learning!=-1) return -3;
7884 if (midiMap.at(msg)) return -3;
7885
7886 if (curWindowThreadSafe==GUI_WINDOW_WAVE_EDIT || curWindowThreadSafe==GUI_WINDOW_WAVE_LIST) {
7887 if ((msg.type&0xf0)==TA_MIDI_NOTE_ON) {
7888 e->previewWaveNoLock(curWave,msg.data[0]-12);
7889 wavePreviewNote=msg.data[0]-12;
7890 } else if ((msg.type&0xf0)==TA_MIDI_NOTE_OFF) {
7891 if (wavePreviewNote==msg.data[0]-12) {
7892 e->stopWavePreviewNoLock();
7893 }
7894 }
7895 return -3;
7896 }
7897
7898 if (curWindowThreadSafe==GUI_WINDOW_SAMPLE_EDIT || curWindowThreadSafe==GUI_WINDOW_SAMPLE_LIST) {
7899 if ((msg.type&0xf0)==TA_MIDI_NOTE_ON) {
7900 e->previewSampleNoLock(curSample,msg.data[0]-12);
7901 samplePreviewNote=msg.data[0]-12;
7902 } else if ((msg.type&0xf0)==TA_MIDI_NOTE_OFF) {
7903 if (samplePreviewNote==msg.data[0]-12) {
7904 e->stopSamplePreviewNoLock();
7905 }
7906 }
7907 return -3;
7908 }
7909
7910 if (midiMap.directChannel && midiMap.directProgram) return -1;
7911 return curIns;
7912 });
7913
7914 #ifdef IS_MOBILE
7915 vibrator=SDL_HapticOpen(0);
7916 if (vibrator==NULL) {
7917 logD("could not open vibration device: %s",SDL_GetError());
7918 } else {
7919 if (SDL_HapticRumbleInit(vibrator)==0) {
7920 vibratorAvailable=true;
7921 } else {
7922 logD("vibration not available: %s",SDL_GetError());
7923 }
7924 }
7925 #endif
7926
7927 cpuCores=SDL_GetCPUCount();
7928 if (cpuCores<1) cpuCores=1;
7929
7930 time_t thisMakesNoSense=time(NULL);
7931 struct tm curTime;
7932 #ifdef _WIN32
7933 struct tm* tempTM=localtime(&thisMakesNoSense);
7934 if (tempTM==NULL) {
7935 memset(&curTime,0,sizeof(struct tm));
7936 } else {
7937 memcpy(&curTime,tempTM,sizeof(struct tm));
7938 purgeYear=1900+curTime.tm_year-1;
7939 purgeMonth=curTime.tm_mon+1;
7940 purgeDay=curTime.tm_mday;
7941 }
7942 #else
7943 if (localtime_r(&thisMakesNoSense,&curTime)==NULL) {
7944 memset(&curTime,0,sizeof(struct tm));
7945 } else {
7946 purgeYear=1900+curTime.tm_year-1;
7947 purgeMonth=curTime.tm_mon+1;
7948 purgeDay=curTime.tm_mday;
7949 }
7950 #endif
7951
7952 // initialize audio formats
7953 String compatFormats;
7954
7955 audioLoadFormats.push_back(_("compatible files"));
7956 audioLoadFormats.push_back("");
7957
7958 #ifdef HAVE_SNDFILE
7959 int value=0;
7960 sf_command(NULL,SFC_GET_FORMAT_MAJOR_COUNT,&value,sizeof(int));
7961 logV("simple formats: %d",value);
7962
7963 for (int i=0; i<value; i++) {
7964 SF_FORMAT_INFO f;
7965 f.format=i;
7966 if (sf_command(NULL,SFC_GET_FORMAT_MAJOR,&f,sizeof(SF_FORMAT_INFO))!=0) continue;
7967 logV("format %d: %s (%s)\n",i,f.name,f.extension);
7968 // these two are/will be handled somewhere else
7969 if (strcmp(f.extension,"raw")==0) continue;
7970 if (strcmp(f.extension,"xi")==0) continue;
7971 // just in case
7972 if (strcmp(f.extension,"dmc")==0) continue;
7973 if (strcmp(f.extension,"brr")==0) continue;
7974 audioLoadFormats.push_back(f.name);
7975 audioLoadFormats.push_back(fmt::sprintf("*.%s",f.extension));
7976 compatFormats+=fmt::sprintf("*.%s ",f.extension);
7977 }
7978 #endif
7979
7980 compatFormats+="*.dmc ";
7981 compatFormats+="*.brr ";
7982
7983 compatFormats+="*.ppc ";
7984 compatFormats+="*.pps ";
7985 compatFormats+="*.pvi ";
7986 compatFormats+="*.pdx ";
7987 compatFormats+="*.pzi ";
7988 compatFormats+="*.p86 ";
7989 compatFormats+="*.p";
7990 audioLoadFormats[1]=compatFormats;
7991
7992 audioLoadFormats.push_back(_("NES DPCM data"));
7993 audioLoadFormats.push_back("*.dmc");
7994
7995 audioLoadFormats.push_back(_("SNES Bit Rate Reduction"));
7996 audioLoadFormats.push_back("*.brr");
7997
7998 audioLoadFormats.push_back(_("PMD YM2608 ADPCM-B sample bank"));
7999 audioLoadFormats.push_back("*.ppc");
8000
8001 audioLoadFormats.push_back(_("PDR 4-bit AY-3-8910 sample bank"));
8002 audioLoadFormats.push_back("*.pps");
8003
8004 audioLoadFormats.push_back(_("FMP YM2608 ADPCM-B sample bank"));
8005 audioLoadFormats.push_back("*.pvi");
8006
8007 audioLoadFormats.push_back(_("MDX OKI ADPCM sample bank"));
8008 audioLoadFormats.push_back("*.pdx");
8009
8010 audioLoadFormats.push_back(_("FMP 8-bit PCM sample bank"));
8011 audioLoadFormats.push_back("*.pzi");
8012
8013 audioLoadFormats.push_back(_("PMD 8-bit PCM sample bank"));
8014 audioLoadFormats.push_back("*.p86");
8015
8016 audioLoadFormats.push_back(_("PMD OKI ADPCM sample bank"));
8017 audioLoadFormats.push_back("*.p");
8018
8019 audioLoadFormats.push_back(_("all files"));
8020 audioLoadFormats.push_back("*");
8021
8022 logI("done!");
8023 return true;
8024 }
8025
8026 void FurnaceGUI::syncState() {
8027 String homeDir=getHomeDir();
8028 workingDir=e->getConfString("lastDir",homeDir);
8029 workingDirSong=e->getConfString("lastDirSong",workingDir);
8030 workingDirIns=e->getConfString("lastDirIns",workingDir);
8031 workingDirWave=e->getConfString("lastDirWave",workingDir);
8032 workingDirSample=e->getConfString("lastDirSample",workingDir);
8033 workingDirAudioExport=e->getConfString("lastDirAudioExport",workingDir);
8034 workingDirVGMExport=e->getConfString("lastDirVGMExport",workingDir);
8035 workingDirROMExport=e->getConfString("lastDirROMExport",workingDir);
8036 workingDirFont=e->getConfString("lastDirFont",workingDir);
8037 workingDirColors=e->getConfString("lastDirColors",workingDir);
8038 workingDirKeybinds=e->getConfString("lastDirKeybinds",workingDir);
8039 workingDirLayout=e->getConfString("lastDirLayout",workingDir);
8040 workingDirConfig=e->getConfString("lastDirConfig",workingDir);
8041 workingDirTest=e->getConfString("lastDirTest",workingDir);
8042
8043 editControlsOpen=e->getConfBool("editControlsOpen",true);
8044 ordersOpen=e->getConfBool("ordersOpen",true);
8045 insListOpen=e->getConfBool("insListOpen",true);
8046 songInfoOpen=e->getConfBool("songInfoOpen",true);
8047 patternOpen=e->getConfBool("patternOpen",true);
8048 insEditOpen=e->getConfBool("insEditOpen",false);
8049 waveListOpen=e->getConfBool("waveListOpen",true);
8050 waveEditOpen=e->getConfBool("waveEditOpen",false);
8051 sampleListOpen=e->getConfBool("sampleListOpen",true);
8052 sampleEditOpen=e->getConfBool("sampleEditOpen",false);
8053 settingsOpen=e->getConfBool("settingsOpen",false);
8054 mixerOpen=e->getConfBool("mixerOpen",false);
8055 oscOpen=e->getConfBool("oscOpen",true);
8056 chanOscOpen=e->getConfBool("chanOscOpen",false);
8057 xyOscOpen=e->getConfBool("xyOscOpen",false);
8058 memoryOpen=e->getConfBool("memoryOpen",false);
8059 csPlayerOpen=e->getConfBool("csPlayerOpen",false);
8060 volMeterOpen=e->getConfBool("volMeterOpen",true);
8061 statsOpen=e->getConfBool("statsOpen",false);
8062 compatFlagsOpen=e->getConfBool("compatFlagsOpen",false);
8063 #ifdef IS_MOBILE
8064 pianoOpen=e->getConfBool("pianoOpen",true);
8065 #else
8066 pianoOpen=e->getConfBool("pianoOpen",false);
8067 #endif
8068 notesOpen=e->getConfBool("notesOpen",false);
8069 channelsOpen=e->getConfBool("channelsOpen",false);
8070 patManagerOpen=e->getConfBool("patManagerOpen",false);
8071 sysManagerOpen=e->getConfBool("sysManagerOpen",false);
8072 clockOpen=e->getConfBool("clockOpen",false);
8073 speedOpen=e->getConfBool("speedOpen",true);
8074 groovesOpen=e->getConfBool("groovesOpen",false);
8075 regViewOpen=e->getConfBool("regViewOpen",false);
8076 logOpen=e->getConfBool("logOpen",false);
8077 effectListOpen=e->getConfBool("effectListOpen",true);
8078 subSongsOpen=e->getConfBool("subSongsOpen",true);
8079 findOpen=e->getConfBool("findOpen",false);
8080 spoilerOpen=e->getConfBool("spoilerOpen",false);
8081 userPresetsOpen=e->getConfBool("userPresetsOpen",false);
8082
8083 insListDir=e->getConfBool("insListDir",false);
8084 waveListDir=e->getConfBool("waveListDir",false);
8085 sampleListDir=e->getConfBool("sampleListDir",false);
8086
8087 tempoView=e->getConfBool("tempoView",true);
8088 waveHex=e->getConfBool("waveHex",false);
8089 waveSigned=e->getConfBool("waveSigned",false);
8090 waveGenVisible=e->getConfBool("waveGenVisible",false);
8091 waveEditStyle=e->getConfInt("waveEditStyle",0);
8092 int extraChannelButtons=e->getConfInt("extraChannelButtons",0);
8093 if (!e->hasConf("patExtraButtons")) {
8094 patExtraButtons=(extraChannelButtons==1);
8095 } else {
8096 patExtraButtons=e->getConfBool("patExtraButtons",false);
8097 }
8098 if (!e->hasConf("patChannelNames")) {
8099 patChannelNames=(extraChannelButtons==2);
8100 } else {
8101 patChannelNames=e->getConfBool("patChannelNames",false);
8102 }
8103 patChannelPairs=e->getConfBool("patChannelPairs",true);
8104 patChannelHints=e->getConfInt("patChannelHints",0);
8105 lockLayout=e->getConfBool("lockLayout",false);
8106 #ifdef IS_MOBILE
8107 fullScreen=true;
8108 #else
8109 fullScreen=e->getConfBool("fullScreen",false);
8110 #endif
8111 mobileUI=e->getConfBool("mobileUI",MOBILE_UI_DEFAULT);
8112 edit=e->getConfBool("edit",false);
8113 orderLock=e->getConfBool("orderLock",false);
8114 followOrders=e->getConfBool("followOrders",true);
8115 followPattern=e->getConfBool("followPattern",true);
8116 noteInputPoly=e->getConfBool("noteInputPoly",true);
8117 audioExportOptions.loops=e->getConfInt("exportLoops",0);
8118 if (audioExportOptions.loops<0) audioExportOptions.loops=0;
8119 audioExportOptions.fadeOut=e->getConfDouble("exportFadeOut",0.0);
8120 if (audioExportOptions.fadeOut<0.0) audioExportOptions.fadeOut=0.0;
8121 orderEditMode=e->getConfInt("orderEditMode",0);
8122 if (orderEditMode<0) orderEditMode=0;
8123 if (orderEditMode>3) orderEditMode=3;
8124
8125 oscZoom=e->getConfFloat("oscZoom",0.5f);
8126 oscZoomSlider=e->getConfBool("oscZoomSlider",false);
8127 oscWindowSize=e->getConfFloat("oscWindowSize",20.0f);
8128
8129 pianoOctaves=e->getConfInt("pianoOctaves",pianoOctaves);
8130 pianoOctavesEdit=e->getConfInt("pianoOctavesEdit",pianoOctavesEdit);
8131 pianoOptions=e->getConfBool("pianoOptions",pianoOptions);
8132 pianoSharePosition=e->getConfBool("pianoSharePosition",pianoSharePosition);
8133 pianoOptionsSet=e->getConfBool("pianoOptionsSet",pianoOptionsSet);
8134 pianoReadonly=e->getConfBool("pianoReadonly",false);
8135 pianoOffset=e->getConfInt("pianoOffset",pianoOffset);
8136 pianoOffsetEdit=e->getConfInt("pianoOffsetEdit",pianoOffsetEdit);
8137 pianoView=e->getConfInt("pianoView",pianoView);
8138 pianoInputPadMode=e->getConfInt("pianoInputPadMode",pianoInputPadMode);
8139
8140 chanOscCols=e->getConfInt("chanOscCols",3);
8141 chanOscAutoColsType=e->getConfInt("chanOscAutoColsType",0);
8142 chanOscColorX=e->getConfInt("chanOscColorX",GUI_OSCREF_CENTER);
8143 chanOscColorY=e->getConfInt("chanOscColorY",GUI_OSCREF_CENTER);
8144 chanOscCenterStrat=e->getConfInt("chanOscCenterStrat",1);
8145 chanOscTextX=e->getConfFloat("chanOscTextX",0.0f);
8146 chanOscTextY=e->getConfFloat("chanOscTextY",0.0f);
8147 chanOscAmplify=e->getConfFloat("chanOscAmplify",0.95f);
8148 chanOscLineSize=e->getConfFloat("chanOscLineSize",1.0f);
8149 chanOscWindowSize=e->getConfFloat("chanOscWindowSize",20.0f);
8150 chanOscWaveCorr=e->getConfBool("chanOscWaveCorr",true);
8151 chanOscOptions=e->getConfBool("chanOscOptions",false);
8152 chanOscNormalize=e->getConfBool("chanOscNormalize",false);
8153 chanOscRandomPhase=e->getConfBool("chanOscRandomPhase",false);
8154 chanOscTextFormat=e->getConfString("chanOscTextFormat","%c");
8155 chanOscColor.x=e->getConfFloat("chanOscColorR",1.0f);
8156 chanOscColor.y=e->getConfFloat("chanOscColorG",1.0f);
8157 chanOscColor.z=e->getConfFloat("chanOscColorB",1.0f);
8158 chanOscColor.w=e->getConfFloat("chanOscColorA",1.0f);
8159 chanOscTextColor.x=e->getConfFloat("chanOscTextColorR",1.0f);
8160 chanOscTextColor.y=e->getConfFloat("chanOscTextColorG",1.0f);
8161 chanOscTextColor.z=e->getConfFloat("chanOscTextColorB",1.0f);
8162 chanOscTextColor.w=e->getConfFloat("chanOscTextColorA",0.75f);
8163 chanOscUseGrad=e->getConfBool("chanOscUseGrad",false);
8164 chanOscGrad.fromString(e->getConfString("chanOscGrad",""));
8165 chanOscGrad.render();
8166
8167 xyOscXChannel=e->getConfInt("xyOscXChannel",0);
8168 xyOscXInvert=e->getConfBool("xyOscXInvert",false);
8169 xyOscYChannel=e->getConfInt("xyOscYChannel",1);
8170 xyOscYInvert=e->getConfBool("xyOscYInvert",false);
8171 xyOscZoom=e->getConfFloat("xyOscZoom",1.0f);
8172 xyOscSamples=e->getConfInt("xyOscSamples",32768);
8173 xyOscDecayTime=e->getConfFloat("xyOscDecayTime",10.0f);
8174 xyOscIntensity=e->getConfFloat("xyOscIntensity",2.0f);
8175 xyOscThickness=e->getConfFloat("xyOscThickness",2.0f);
8176
8177 cvHiScore=e->getConfInt("cvHiScore",25000);
8178 }
8179
8180 void FurnaceGUI::commitState(DivConfig& conf) {
8181 if (!mobileUI) {
8182 if (!ImGui::SaveIniSettingsToDisk(finalLayoutPath,true)) {
8183 reportError(fmt::sprintf(_("could NOT save layout! %s"),strerror(errno)));
8184 }
8185 }
8186
8187 conf.set("configVersion",(int)DIV_ENGINE_VERSION);
8188
8189 conf.set("lastDir",workingDir);
8190 conf.set("lastDirSong",workingDirSong);
8191 conf.set("lastDirIns",workingDirIns);
8192 conf.set("lastDirWave",workingDirWave);
8193 conf.set("lastDirSample",workingDirSample);
8194 conf.set("lastDirAudioExport",workingDirAudioExport);
8195 conf.set("lastDirVGMExport",workingDirVGMExport);
8196 conf.set("lastDirROMExport",workingDirROMExport);
8197 conf.set("lastDirFont",workingDirFont);
8198 conf.set("lastDirColors",workingDirColors);
8199 conf.set("lastDirKeybinds",workingDirKeybinds);
8200 conf.set("lastDirLayout",workingDirLayout);
8201 conf.set("lastDirConfig",workingDirConfig);
8202 conf.set("lastDirTest",workingDirTest);
8203
8204 // commit last open windows
8205 conf.set("editControlsOpen",editControlsOpen);
8206 conf.set("ordersOpen",ordersOpen);
8207 conf.set("insListOpen",insListOpen);
8208 conf.set("songInfoOpen",songInfoOpen);
8209 conf.set("patternOpen",patternOpen);
8210 conf.set("insEditOpen",insEditOpen);
8211 conf.set("waveListOpen",waveListOpen);
8212 conf.set("waveEditOpen",waveEditOpen);
8213 conf.set("sampleListOpen",sampleListOpen);
8214 conf.set("sampleEditOpen",sampleEditOpen);
8215 conf.set("settingsOpen",settingsOpen);
8216 conf.set("mixerOpen",mixerOpen);
8217 conf.set("oscOpen",oscOpen);
8218 conf.set("chanOscOpen",chanOscOpen);
8219 conf.set("xyOscOpen",xyOscOpen);
8220 conf.set("memoryOpen",memoryOpen);
8221 conf.set("csPlayerOpen",csPlayerOpen);
8222 conf.set("volMeterOpen",volMeterOpen);
8223 conf.set("statsOpen",statsOpen);
8224 conf.set("compatFlagsOpen",compatFlagsOpen);
8225 conf.set("pianoOpen",pianoOpen);
8226 conf.set("notesOpen",notesOpen);
8227 conf.set("channelsOpen",channelsOpen);
8228 conf.set("patManagerOpen",patManagerOpen);
8229 conf.set("sysManagerOpen",sysManagerOpen);
8230 conf.set("clockOpen",clockOpen);
8231 conf.set("speedOpen",speedOpen);
8232 conf.set("groovesOpen",groovesOpen);
8233 conf.set("regViewOpen",regViewOpen);
8234 conf.set("logOpen",logOpen);
8235 conf.set("effectListOpen",effectListOpen);
8236 conf.set("subSongsOpen",subSongsOpen);
8237 conf.set("findOpen",findOpen);
8238 conf.set("spoilerOpen",spoilerOpen);
8239 conf.set("userPresetsOpen",userPresetsOpen);
8240
8241 // commit dir state
8242 conf.set("insListDir",insListDir);
8243 conf.set("waveListDir",waveListDir);
8244 conf.set("sampleListDir",sampleListDir);
8245
8246 // commit last window size
8247 conf.set("lastWindowWidth",scrConfW);
8248 conf.set("lastWindowHeight",scrConfH);
8249 conf.set("lastWindowX",settings.saveWindowPos?scrConfX:(int)SDL_WINDOWPOS_CENTERED);
8250 conf.set("lastWindowY",settings.saveWindowPos?scrConfY:(int)SDL_WINDOWPOS_CENTERED);
8251 conf.set("lastWindowMax",scrMax);
8252
8253 conf.set("tempoView",tempoView);
8254 conf.set("waveHex",waveHex);
8255 conf.set("waveSigned",waveSigned);
8256 conf.set("waveGenVisible",waveGenVisible);
8257 conf.set("waveEditStyle",waveEditStyle);
8258 conf.set("patExtraButtons",patExtraButtons);
8259 conf.set("patChannelNames",patChannelNames);
8260 conf.set("patChannelPairs",patChannelPairs);
8261 conf.set("patChannelHints",(int)patChannelHints);
8262 conf.set("lockLayout",lockLayout);
8263 conf.set("fullScreen",fullScreen);
8264 conf.set("mobileUI",mobileUI);
8265 conf.set("edit",edit);
8266 conf.set("orderLock",orderLock);
8267 conf.set("followOrders",followOrders);
8268 conf.set("followPattern",followPattern);
8269 conf.set("orderEditMode",orderEditMode);
8270 conf.set("noteInputPoly",noteInputPoly);
8271 if (settings.persistFadeOut) {
8272 conf.set("exportLoops",audioExportOptions.loops);
8273 conf.set("exportFadeOut",audioExportOptions.fadeOut);
8274 }
8275
8276 // commit oscilloscope state
8277 conf.set("oscZoom",oscZoom);
8278 conf.set("oscZoomSlider",oscZoomSlider);
8279 conf.set("oscWindowSize",oscWindowSize);
8280
8281 // commit piano state
8282 conf.set("pianoOctaves",pianoOctaves);
8283 conf.set("pianoOctavesEdit",pianoOctavesEdit);
8284 conf.set("pianoOptions",pianoOptions);
8285 conf.set("pianoSharePosition",pianoSharePosition);
8286 conf.set("pianoOptionsSet",pianoOptionsSet);
8287 conf.set("pianoReadonly",pianoReadonly);
8288 conf.set("pianoOffset",pianoOffset);
8289 conf.set("pianoOffsetEdit",pianoOffsetEdit);
8290 conf.set("pianoView",pianoView);
8291 conf.set("pianoInputPadMode",pianoInputPadMode);
8292
8293 // commit per-chan osc state
8294 conf.set("chanOscCols",chanOscCols);
8295 conf.set("chanOscAutoColsType",chanOscAutoColsType);
8296 conf.set("chanOscColorX",chanOscColorX);
8297 conf.set("chanOscColorY",chanOscColorY);
8298 conf.set("chanOscCenterStrat",chanOscCenterStrat);
8299 conf.set("chanOscTextX",chanOscTextX);
8300 conf.set("chanOscTextY",chanOscTextY);
8301 conf.set("chanOscAmplify",chanOscAmplify);
8302 conf.set("chanOscLineSize",chanOscLineSize);
8303 conf.set("chanOscWindowSize",chanOscWindowSize);
8304 conf.set("chanOscWaveCorr",chanOscWaveCorr);
8305 conf.set("chanOscOptions",chanOscOptions);
8306 conf.set("chanOscNormalize",chanOscNormalize);
8307 conf.set("chanOscRandomPhase",chanOscRandomPhase);
8308 conf.set("chanOscTextFormat",chanOscTextFormat);
8309 conf.set("chanOscColorR",chanOscColor.x);
8310 conf.set("chanOscColorG",chanOscColor.y);
8311 conf.set("chanOscColorB",chanOscColor.z);
8312 conf.set("chanOscColorA",chanOscColor.w);
8313 conf.set("chanOscTextColorR",chanOscTextColor.x);
8314 conf.set("chanOscTextColorG",chanOscTextColor.y);
8315 conf.set("chanOscTextColorB",chanOscTextColor.z);
8316 conf.set("chanOscTextColorA",chanOscTextColor.w);
8317 conf.set("chanOscUseGrad",chanOscUseGrad);
8318 conf.set("chanOscGrad",chanOscGrad.toString());
8319
8320 // commit x-y osc state
8321 conf.set("xyOscXChannel",xyOscXChannel);
8322 conf.set("xyOscXInvert",xyOscXInvert);
8323 conf.set("xyOscYChannel",xyOscYChannel);
8324 conf.set("xyOscYInvert",xyOscYInvert);
8325 conf.set("xyOscZoom",xyOscZoom);
8326 conf.set("xyOscSamples",xyOscSamples);
8327 conf.set("xyOscDecayTime",xyOscDecayTime);
8328 conf.set("xyOscIntensity",xyOscIntensity);
8329 conf.set("xyOscThickness",xyOscThickness);
8330
8331 // commit recent files
8332 for (int i=0; i<30; i++) {
8333 String key=fmt::sprintf("recentFile%d",i);
8334 if (i>=settings.maxRecentFile || i>=(int)recentFile.size()) {
8335 conf.set(key,"");
8336 } else {
8337 conf.set(key,recentFile[i]);
8338 }
8339 }
8340
8341 conf.set("cvHiScore",cvHiScore);
8342 }
8343
8344 bool FurnaceGUI::finish(bool saveConfig) {
8345 if (!quitNoSave) {
8346 commitState(e->getConfObject());
8347 if (userPresetsOpen) {
8348 saveUserPresets(true);
8349 }
8350 if (saveConfig) {
8351 logI("saving config.");
8352 e->saveConf();
8353 }
8354 }
8355 rend->quitGUI();
8356 ImGui_ImplSDL2_Shutdown();
8357 quitRender();
8358 ImGui::DestroyContext();
8359 SDL_DestroyWindow(sdlWin);
8360
8361 if (vibrator) {
8362 SDL_HapticClose(vibrator);
8363 }
8364
8365 for (int i=0; i<DIV_MAX_OUTPUTS; i++) {
8366 if (oscValues[i]) {
8367 delete[] oscValues[i];
8368 oscValues[i]=NULL;
8369 }
8370 }
8371 if (oscValuesAverage) {
8372 delete[] oscValuesAverage;
8373 oscValuesAverage=NULL;
8374 }
8375
8376 if (backupTask.valid()) {
8377 backupTask.get();
8378 }
8379
8380 if (chanOscWorkPool!=NULL) {
8381 delete chanOscWorkPool;
8382 }
8383
8384 delete[] opTouched;
8385 opTouched=NULL;
8386
8387 return true;
8388 }
8389
8390 bool FurnaceGUI::requestQuit() {
8391 if (modified && !cvOpen) {
8392 showWarning(_("Unsaved changes! Save changes before quitting?"),GUI_WARN_QUIT);
8393 } else {
8394 quit=true;
8395 }
8396 return quit;
8397 }
8398
8399 FurnaceGUI::FurnaceGUI():
8400 e(NULL),
8401 renderBackend(GUI_BACKEND_SDL),
8402 rend(NULL),
8403 sdlWin(NULL),
8404 vibrator(NULL),
8405 vibratorAvailable(false),
8406 cv(NULL),
8407 lastCVFrame(0),
8408 cvFrameTime(100000),
8409 cvFrameHold(0),
8410 sampleTex(NULL),
8411 sampleTexW(0),
8412 sampleTexH(0),
8413 updateSampleTex(true),
8414 quit(false),
8415 warnQuit(false),
8416 willCommit(false),
8417 edit(false),
8418 editClone(false),
8419 isPatUnique(false),
8420 modified(false),
8421 displayError(false),
8422 displayExporting(false),
8423 vgmExportLoop(true),
8424 vgmExportPatternHints(false),
8425 vgmExportDPCM07(false),
8426 vgmExportDirectStream(false),
8427 displayInsTypeList(false),
8428 portrait(false),
8429 injectBackUp(false),
8430 mobileMenuOpen(false),
8431 warnColorPushed(false),
8432 wantCaptureKeyboard(false),
8433 oldWantCaptureKeyboard(false),
8434 displayMacroMenu(false),
8435 displayNew(false),
8436 displayPalette(false),
8437 fullScreen(false),
8438 preserveChanPos(false),
8439 sysDupCloneChannels(true),
8440 sysDupEnd(false),
8441 noteInputPoly(true),
8442 notifyWaveChange(false),
8443 wantScrollListIns(false),
8444 wantScrollListWave(false),
8445 wantScrollListSample(false),
8446 displayPendingIns(false),
8447 pendingInsSingle(false),
8448 displayPendingRawSample(false),
8449 snesFilterHex(false),
8450 modTableHex(false),
8451 displayEditString(false),
8452 displayPendingSamples(false),
8453 replacePendingSample(false),
8454 displayExportingROM(false),
8455 displayExportingCS(false),
8456 quitNoSave(false),
8457 changeCoarse(false),
8458 orderLock(false),
8459 mobileEdit(false),
8460 killGraphics(false),
8461 safeMode(false),
8462 midiWakeUp(true),
8463 makeDrumkitMode(false),
8464 audioEngineChanged(false),
8465 settingsChanged(false),
8466 debugFFT(false),
8467 vgmExportVersion(0x171),
8468 vgmExportTrailingTicks(-1),
8469 vgmExportCorrectedRate(44100),
8470 drawHalt(10),
8471 macroPointSize(16),
8472 waveEditStyle(0),
8473 displayInsTypeListMakeInsSample(-1),
8474 makeDrumkitOctave(3),
8475 mobileEditPage(0),
8476 wheelCalmDown(0),
8477 shallDetectScale(0),
8478 cpuCores(0),
8479 secondTimer(0.0f),
8480 userEvents(0xffffffff),
8481 mobileMenuPos(0.0f),
8482 autoButtonSize(0.0f),
8483 mobileEditAnim(0.0f),
8484 mobileEditButtonPos(0.7f,0.7f),
8485 mobileEditButtonSize(60.0f,60.0f),
8486 curSysSection(NULL),
8487 updateFMPreview(true),
8488 fmPreviewOn(false),
8489 fmPreviewPaused(false),
8490 fmPreviewOPN(NULL),
8491 fmPreviewOPM(NULL),
8492 fmPreviewOPL(NULL),
8493 fmPreviewOPLL(NULL),
8494 fmPreviewOPZ(NULL),
8495 fmPreviewOPZInterface(NULL),
8496 editString(NULL),
8497 pendingRawSampleDepth(8),
8498 pendingRawSampleChannels(1),
8499 pendingRawSampleRate(32000),
8500 pendingRawSampleUnsigned(false),
8501 pendingRawSampleBigEndian(false),
8502 pendingRawSampleSwapNibbles(false),
8503 pendingRawSampleReplace(false),
8504 globalWinFlags(0),
8505 curFileDialog(GUI_FILE_OPEN),
8506 warnAction(GUI_WARN_OPEN),
8507 postWarnAction(GUI_WARN_GENERIC),
8508 mobScene(GUI_SCENE_PATTERN),
8509 fileDialog(NULL),
8510 scrW(GUI_WIDTH_DEFAULT),
8511 scrH(GUI_HEIGHT_DEFAULT),
8512 scrConfW(GUI_WIDTH_DEFAULT),
8513 scrConfH(GUI_HEIGHT_DEFAULT),
8514 canvasW(GUI_WIDTH_DEFAULT),
8515 canvasH(GUI_HEIGHT_DEFAULT),
8516 scrX(SDL_WINDOWPOS_CENTERED),
8517 scrY(SDL_WINDOWPOS_CENTERED),
8518 scrConfX(SDL_WINDOWPOS_CENTERED),
8519 scrConfY(SDL_WINDOWPOS_CENTERED),
8520 scrMax(false),
8521 sysManagedScale(false),
8522 dpiScale(1),
8523 aboutScroll(0),
8524 aboutSin(0),
8525 aboutHue(0.0f),
8526 backupTimer(0.0),
8527 totalBackupSize(0),
8528 refreshBackups(true),
8529 learning(-1),
8530 mainFont(NULL),
8531 iconFont(NULL),
8532 furIconFont(NULL),
8533 patFont(NULL),
8534 bigFont(NULL),
8535 headFont(NULL),
8536 songLength(0),
8537 songLoopedSectionLength(0),
8538 songFadeoutSectionLength(0),
8539 songHasSongEndCommand(false),
8540 lengthOfOneFile(0),
8541 totalLength(0),
8542 curProgress(0.0f),
8543 totalFiles(0),
8544 localeRequiresJapanese(false),
8545 localeRequiresChinese(false),
8546 localeRequiresChineseTrad(false),
8547 localeRequiresKorean(false),
8548 prevInsData(NULL),
8549 cachedCurInsPtr(NULL),
8550 insEditMayBeDirty(false),
8551 pendingLayoutImport(NULL),
8552 pendingLayoutImportLen(0),
8553 pendingLayoutImportStep(0),
8554 curIns(0),
8555 curWave(0),
8556 curSample(0),
8557 curOctave(3),
8558 curOrder(0),
8559 playOrder(0),
8560 prevIns(0),
8561 oldRow(0),
8562 editStep(1),
8563 editStepCoarse(16),
8564 soloChan(-1),
8565 orderEditMode(0),
8566 orderCursor(-1),
8567 loopOrder(-1),
8568 loopRow(-1),
8569 loopEnd(-1),
8570 isClipping(0),
8571 newSongCategory(0),
8572 latchTarget(0),
8573 undoOrder(0),
8574 wheelX(0),
8575 wheelY(0),
8576 dragSourceX(0),
8577 dragSourceXFine(0),
8578 dragSourceY(0),
8579 dragSourceOrder(0),
8580 dragDestinationX(0),
8581 dragDestinationXFine(0),
8582 dragDestinationY(0),
8583 dragDestinationOrder(0),
8584 oldBeat(-1),
8585 oldBar(-1),
8586 curGroove(-1),
8587 exitDisabledTimer(0),
8588 curPaletteChoice(0),
8589 curPaletteType(0),
8590 soloTimeout(0.0f),
8591 purgeYear(2021),
8592 purgeMonth(4),
8593 purgeDay(4),
8594 patExtraButtons(false),
8595 patChannelNames(false),
8596 patChannelPairs(true),
8597 patChannelHints(0),
8598 newSongFirstFrame(false),
8599 oldRowChanged(false),
8600 editControlsOpen(true),
8601 ordersOpen(true),
8602 insListOpen(true),
8603 songInfoOpen(true),
8604 patternOpen(true),
8605 insEditOpen(false),
8606 waveListOpen(true),
8607 waveEditOpen(false),
8608 sampleListOpen(true),
8609 sampleEditOpen(false),
8610 aboutOpen(false),
8611 settingsOpen(false),
8612 mixerOpen(false),
8613 debugOpen(false),
8614 inspectorOpen(false),
8615 oscOpen(true),
8616 volMeterOpen(true),
8617 statsOpen(false),
8618 compatFlagsOpen(false),
8619 pianoOpen(false),
8620 notesOpen(false),
8621 channelsOpen(false),
8622 regViewOpen(false),
8623 logOpen(false),
8624 effectListOpen(false),
8625 chanOscOpen(false),
8626 subSongsOpen(true),
8627 findOpen(false),
8628 spoilerOpen(false),
8629 patManagerOpen(false),
8630 sysManagerOpen(false),
8631 clockOpen(false),
8632 speedOpen(true),
8633 groovesOpen(false),
8634 xyOscOpen(false),
8635 memoryOpen(false),
8636 csPlayerOpen(false),
8637 cvOpen(false),
8638 userPresetsOpen(false),
8639 cvNotSerious(false),
8640 shortIntro(false),
8641 insListDir(false),
8642 waveListDir(false),
8643 sampleListDir(false),
8644 clockShowReal(true),
8645 clockShowRow(true),
8646 clockShowBeat(true),
8647 clockShowMetro(true),
8648 clockShowTime(true),
8649 selecting(false),
8650 selectingFull(false),
8651 dragging(false),
8652 curNibble(false),
8653 orderNibble(false),
8654 followOrders(true),
8655 followPattern(true),
8656 wasFollowing(false),
8657 changeAllOrders(false),
8658 mobileUI(MOBILE_UI_DEFAULT),
8659 collapseWindow(false),
8660 demandScrollX(false),
8661 fancyPattern(false),
8662 firstFrame(true),
8663 tempoView(true),
8664 waveHex(false),
8665 waveSigned(false),
8666 waveGenVisible(false),
8667 lockLayout(false),
8668 editOptsVisible(false),
8669 latchNibble(false),
8670 nonLatchNibble(false),
8671 keepLoopAlive(false),
8672 keepGrooveAlive(false),
8673 orderScrollLocked(false),
8674 orderScrollTolerance(false),
8675 dragMobileMenu(false),
8676 dragMobileEditButton(false),
8677 wantGrooveListFocus(false),
8678 mobilePatSel(false),
8679 lastAssetType(0),
8680 curWindow(GUI_WINDOW_NOTHING),
8681 nextWindow(GUI_WINDOW_NOTHING),
8682 curWindowLast(GUI_WINDOW_NOTHING),
8683 curWindowThreadSafe(GUI_WINDOW_NOTHING),
8684 failedNoteOn(false),
8685 lastPatternWidth(0.0f),
8686 longThreshold(0.48f),
8687 buttonLongThreshold(0.20f),
8688 lastAudioLoadsPos(0),
8689 latchNote(-1),
8690 latchIns(-2),
8691 latchVol(-1),
8692 latchEffect(-1),
8693 latchEffectVal(-1),
8694 wavePreviewLen(32),
8695 wavePreviewHeight(255),
8696 wavePreviewInit(true),
8697 wavePreviewPaused(false),
8698 pgSys(0),
8699 pgAddr(0),
8700 pgVal(0),
8701 curQueryRangeX(false),
8702 curQueryBackwards(false),
8703 curQueryRangeXMin(0), curQueryRangeXMax(0),
8704 curQueryRangeY(0),
8705 curQueryEffectPos(0),
8706 queryReplaceEffectCount(0),
8707 queryReplaceEffectPos(1),
8708 queryReplaceNoteMode(0),
8709 queryReplaceInsMode(0),
8710 queryReplaceVolMode(0),
8711 queryReplaceNote(0),
8712 queryReplaceIns(0),
8713 queryReplaceVol(0),
8714 queryReplaceNoteDo(false),
8715 queryReplaceInsDo(false),
8716 queryReplaceVolDo(false),
8717 queryViewingResults(false),
8718 wavePreviewOn(false),
8719 wavePreviewKey((SDL_Scancode)0),
8720 wavePreviewNote(0),
8721 samplePreviewOn(false),
8722 samplePreviewKey((SDL_Scancode)0),
8723 samplePreviewNote(0),
8724 sampleMapSelStart(-1),
8725 sampleMapSelEnd(-1),
8726 sampleMapDigit(0),
8727 sampleMapColumn(0),
8728 sampleMapFocused(false),
8729 sampleMapWaitingInput(false),
8730 macroDragStart(0,0),
8731 macroDragAreaSize(0,0),
8732 macroDragCTarget(NULL),
8733 macroDragTarget(NULL),
8734 macroDragLen(0),
8735 macroDragMin(0),
8736 macroDragMax(0),
8737 macroDragLastX(-1),
8738 macroDragLastY(-1),
8739 macroDragScroll(0),
8740 macroDragBitMode(false),
8741 macroDragInitialValueSet(false),
8742 macroDragInitialValue(false),
8743 macroDragChar(false),
8744 macroDragBit30(false),
8745 macroDragSettingBit30(false),
8746 macroDragLineMode(false),
8747 macroDragMouseMoved(false),
8748 macroDragLineInitial(0,0),
8749 macroDragLineInitialV(0,0),
8750 macroDragActive(false),
8751 lastMacroDesc(NULL,NULL,0,0,0.0f),
8752 macroOffX(0),
8753 macroOffY(0),
8754 macroScaleX(100.0f),
8755 macroScaleY(100.0f),
8756 macroRandMin(0),
8757 macroRandMax(0),
8758 macroLoopDragStart(0,0),
8759 macroLoopDragAreaSize(0,0),
8760 macroLoopDragTarget(NULL),
8761 macroLoopDragLen(0),
8762 macroLoopDragActive(false),
8763 waveDragStart(0,0),
8764 waveDragAreaSize(0,0),
8765 waveDragTarget(NULL),
8766 waveDragLen(0),
8767 waveDragMin(0),
8768 waveDragMax(0),
8769 waveDragActive(false),
8770 bindSetTarget(0),
8771 bindSetTargetIdx(0),
8772 bindSetPrevValue(0),
8773 bindSetActive(false),
8774 bindSetPending(false),
8775 nextScroll(-1.0f),
8776 nextAddScroll(0.0f),
8777 orderScroll(0.0f),
8778 orderScrollSlideOrigin(0.0f),
8779 patScroll(-1.0f),
8780 orderScrollRealOrigin(0.0f,0.0f),
8781 dragMobileMenuOrigin(0.0f,0.0f),
8782 layoutTimeBegin(0),
8783 layoutTimeEnd(0),
8784 layoutTimeDelta(0),
8785 renderTimeBegin(0),
8786 renderTimeEnd(0),
8787 renderTimeDelta(0),
8788 drawTimeBegin(0),
8789 drawTimeEnd(0),
8790 drawTimeDelta(0),
8791 swapTimeBegin(0),
8792 swapTimeEnd(0),
8793 swapTimeDelta(0),
8794 eventTimeBegin(0),
8795 eventTimeEnd(0),
8796 eventTimeDelta(0),
8797 nextPresentTime(0),
8798 perfMetricsLen(0),
8799 chanToMove(-1),
8800 sysToMove(-1),
8801 sysToDelete(-1),
8802 opToMove(-1),
8803 assetToMove(-1),
8804 dirToMove(-1),
8805 insToMove(-1),
8806 waveToMove(-1),
8807 sampleToMove(-1),
8808 transposeAmount(0),
8809 randomizeMin(0),
8810 randomizeMax(255),
8811 fadeMin(0),
8812 fadeMax(255),
8813 collapseAmount(2),
8814 randomizeEffectVal(0),
8815 topMostOrder(-1),
8816 topMostRow(-1),
8817 bottomMostOrder(-1),
8818 bottomMostRow(-1),
8819 playheadY(0.0f),
8820 scaleMax(100.0f),
8821 fadeMode(false),
8822 randomMode(false),
8823 haveHitBounds(false),
8824 randomizeEffect(false),
8825 pendingStepUpdate(0),
8826 oldOrdersLen(0),
8827 opTouched(NULL),
8828 sampleZoom(1.0),
8829 prevSampleZoom(1.0),
8830 minSampleZoom(1.0),
8831 samplePos(0),
8832 resizeSize(1024),
8833 silenceSize(1024),
8834 resampleTarget(32000),
8835 resampleStrat(5),
8836 amplifyVol(100.0),
8837 sampleSelStart(-1),
8838 sampleSelEnd(-1),
8839 sampleInfo(true),
8840 sampleCompatRate(false),
8841 sampleDragActive(false),
8842 sampleDragMode(false),
8843 sampleDrag16(false),
8844 sampleZoomAuto(true),
8845 sampleCheckLoopStart(true),
8846 sampleCheckLoopEnd(true),
8847 sampleSelTarget(0),
8848 sampleDragTarget(NULL),
8849 sampleDragStart(0,0),
8850 sampleDragAreaSize(0,0),
8851 sampleDragLen(0),
8852 sampleFilterL(1.0f),
8853 sampleFilterB(0.0f),
8854 sampleFilterH(0.0f),
8855 sampleFilterRes(0.25f),
8856 sampleFilterCutStart(16000.0f),
8857 sampleFilterCutEnd(100.0f),
8858 sampleFilterSweep(false),
8859 sampleFilterFirstFrame(true),
8860 sampleCrossFadeLoopLength(0),
8861 sampleCrossFadeLoopLaw(50),
8862 sampleFilterPower(1),
8863 sampleClipboard(NULL),
8864 sampleClipboardLen(0),
8865 openSampleResizeOpt(false),
8866 openSampleResampleOpt(false),
8867 openSampleAmplifyOpt(false),
8868 openSampleSilenceOpt(false),
8869 openSampleFilterOpt(false),
8870 openSampleCrossFadeOpt(false),
8871 selectedPortSet(0x1fff),
8872 selectedSubPort(-1),
8873 hoveredPortSet(0x1fff),
8874 hoveredSubPort(-1),
8875 portDragActive(false),
8876 displayHiddenPorts(false),
8877 displayInternalPorts(false),
8878 subPortPos(0.0f,0.0f),
8879 oscTotal(0),
8880 oscWidth(512),
8881 oscValuesAverage(NULL),
8882 oscZoom(0.5f),
8883 oscWindowSize(20.0f),
8884 oscInput(0.0f),
8885 oscInput1(0.0f),
8886 oscZoomSlider(false),
8887 chanOscCols(3),
8888 chanOscAutoColsType(0),
8889 chanOscColorX(GUI_OSCREF_CENTER),
8890 chanOscColorY(GUI_OSCREF_CENTER),
8891 chanOscCenterStrat(1),
8892 chanOscWindowSize(20.0f),
8893 chanOscTextX(0.0f),
8894 chanOscTextY(0.0f),
8895 chanOscAmplify(0.95f),
8896 chanOscLineSize(1.0f),
8897 chanOscWaveCorr(true),
8898 chanOscOptions(false),
8899 updateChanOscGradTex(true),
8900 chanOscUseGrad(false),
8901 chanOscNormalize(false),
8902 chanOscRandomPhase(false),
8903 chanOscTextFormat("%c"),
8904 chanOscColor(1.0f,1.0f,1.0f,1.0f),
8905 chanOscTextColor(1.0f,1.0f,1.0f,0.75f),
8906 chanOscGrad(64,64),
8907 chanOscGradTex(NULL),
8908 chanOscWorkPool(NULL),
8909 xyOscPointTex(NULL),
8910 xyOscOptions(false),
8911 xyOscXChannel(0),
8912 xyOscXInvert(false),
8913 xyOscYChannel(1),
8914 xyOscYInvert(false),
8915 xyOscZoom(1.0f),
8916 xyOscSamples(32768),
8917 xyOscDecayTime(10.0f),
8918 xyOscIntensity(2.0f),
8919 xyOscThickness(2.0f),
8920 followLog(true),
8921 #ifdef IS_MOBILE
8922 pianoOctaves(7),
8923 pianoOctavesEdit(2),
8924 pianoOptions(true),
8925 pianoSharePosition(false),
8926 pianoOptionsSet(false),
8927 pianoReadonly(false),
8928 pianoOffset(6),
8929 pianoOffsetEdit(9),
8930 pianoView(PIANO_LAYOUT_AUTOMATIC),
8931 pianoInputPadMode(PIANO_INPUT_PAD_SPLIT_AUTO),
8932 #else
8933 pianoOctaves(7),
8934 pianoOctavesEdit(4),
8935 pianoOptions(false),
8936 pianoSharePosition(true),
8937 pianoReadonly(false),
8938 pianoOffset(6),
8939 pianoOffsetEdit(6),
8940 pianoView(PIANO_LAYOUT_STANDARD),
8941 pianoInputPadMode(PIANO_INPUT_PAD_DISABLE),
8942 #endif
8943 hasACED(false),
8944 waveGenBaseShape(0),
8945 waveInterpolation(0),
8946 waveGenDuty(0.5f),
8947 waveGenPower(1),
8948 waveGenInvertPoint(1.0f),
8949 waveGenScaleX(32),
8950 waveGenScaleY(32),
8951 waveGenOffsetX(0),
8952 waveGenOffsetY(0),
8953 waveGenSmooth(1),
8954 waveGenAmplify(1.0f),
8955 waveGenFM(false),
8956 introPos(0.0),
8957 introSkip(0.0),
8958 monitorPos(0.0),
8959 mustClear(2),
8960 initialScreenWipe(1.0f),
8961 introSkipDo(false),
8962 introStopped(false),
8963 curTutorial(-1),
8964 curTutorialStep(0),
8965 csDisAsmAddr(0),
8966 csExportThread(NULL),
8967 csExportResult(NULL),
8968 csExportTarget(false),
8969 csExportDone(false),
8970 dmfExportVersion(0),
8971 curExportType(GUI_EXPORT_NONE),
8972 romTarget(DIV_ROM_ABSTRACT),
8973 romMultiFile(false),
8974 romExportSave(false),
8975 pendingExport(NULL),
8976 romExportExists(false) {
8977 // value keys
8978 valueKeys[SDLK_0]=0;
8979 valueKeys[SDLK_1]=1;
8980 valueKeys[SDLK_2]=2;
8981 valueKeys[SDLK_3]=3;
8982 valueKeys[SDLK_4]=4;
8983 valueKeys[SDLK_5]=5;
8984 valueKeys[SDLK_6]=6;
8985 valueKeys[SDLK_7]=7;
8986 valueKeys[SDLK_8]=8;
8987 valueKeys[SDLK_9]=9;
8988 valueKeys[SDLK_a]=10;
8989 valueKeys[SDLK_b]=11;
8990 valueKeys[SDLK_c]=12;
8991 valueKeys[SDLK_d]=13;
8992 valueKeys[SDLK_e]=14;
8993 valueKeys[SDLK_f]=15;
8994 valueKeys[SDLK_KP_0]=0;
8995 valueKeys[SDLK_KP_1]=1;
8996 valueKeys[SDLK_KP_2]=2;
8997 valueKeys[SDLK_KP_3]=3;
8998 valueKeys[SDLK_KP_4]=4;
8999 valueKeys[SDLK_KP_5]=5;
9000 valueKeys[SDLK_KP_6]=6;
9001 valueKeys[SDLK_KP_7]=7;
9002 valueKeys[SDLK_KP_8]=8;
9003 valueKeys[SDLK_KP_9]=9;
9004
9005 memset(willExport,1,DIV_MAX_CHIPS*sizeof(bool));
9006
9007 memset(peak,0,DIV_MAX_OUTPUTS*sizeof(float));
9008
9009 opMaskTransposeNote.note=true;
9010 opMaskTransposeNote.ins=false;
9011 opMaskTransposeNote.vol=false;
9012 opMaskTransposeNote.effect=false;
9013 opMaskTransposeNote.effectVal=false;
9014
9015 opMaskTransposeValue.note=false;
9016 opMaskTransposeValue.ins=true;
9017 opMaskTransposeValue.vol=true;
9018 opMaskTransposeValue.effect=false;
9019 opMaskTransposeValue.effectVal=true;
9020
9021 memset(patChanX,0,sizeof(float)*(DIV_MAX_CHANS+1));
9022 memset(patChanSlideY,0,sizeof(float)*(DIV_MAX_CHANS+1));
9023 memset(lastIns,-1,sizeof(int)*DIV_MAX_CHANS);
9024 memset(oscValues,0,sizeof(void*)*DIV_MAX_OUTPUTS);
9025
9026 memset(chanOscLP0,0,sizeof(float)*DIV_MAX_CHANS);
9027 memset(chanOscLP1,0,sizeof(float)*DIV_MAX_CHANS);
9028 memset(chanOscVol,0,sizeof(float)*DIV_MAX_CHANS);
9029 for (int i=0; i<DIV_MAX_CHANS; i++) {
9030 chanOscChan[i].pitch=0.0f;
9031 }
9032 memset(chanOscBright,0,sizeof(float)*DIV_MAX_CHANS);
9033 memset(lastCorrPos,0,sizeof(short)*DIV_MAX_CHANS);
9034
9035 memset(acedData,0,23);
9036
9037 memset(waveGenAmp,0,sizeof(float)*16);
9038 memset(waveGenPhase,0,sizeof(float)*16);
9039 waveGenTL[0]=0.0f;
9040 waveGenTL[1]=0.0f;
9041 waveGenTL[2]=0.0f;
9042 waveGenTL[3]=1.0f;
9043 fmWaveform[0]=0;
9044 fmWaveform[1]=0;
9045 fmWaveform[2]=0;
9046 fmWaveform[3]=0;
9047 waveGenMult[0]=1;
9048 waveGenMult[1]=1;
9049 waveGenMult[2]=1;
9050 waveGenMult[3]=1;
9051 memset(waveGenFB,0,sizeof(int)*4);
9052 memset(waveGenFMCon0,0,sizeof(bool)*5);
9053 memset(waveGenFMCon1,0,sizeof(bool)*5);
9054 memset(waveGenFMCon2,0,sizeof(bool)*5);
9055 memset(waveGenFMCon3, 0, sizeof(bool) * 5);
9056 memset(waveGenFMCon4,0,sizeof(bool)*5);
9057
9058 waveGenAmp[0]=1.0f;
9059 waveGenFMCon0[0]=false;
9060 waveGenFMCon1[0]=true;
9061 waveGenFMCon2[1]=true;
9062 waveGenFMCon3[2]=true;
9063 waveGenFMCon4[0]=false;
9064
9065 waveGenFMCon0[4]=false;
9066 waveGenFMCon1[4]=false;
9067 waveGenFMCon2[4]=false;
9068 waveGenFMCon3[4]=true;
9069
9070 memset(keyHit,0,sizeof(float)*DIV_MAX_CHANS);
9071 memset(keyHit1,0,sizeof(float)*DIV_MAX_CHANS);
9072
9073 memset(lastAudioLoads,0,sizeof(float)*120);
9074
9075 memset(pianoKeyHit,0,sizeof(float)*180);
9076 memset(pianoKeyPressed,0,sizeof(bool)*180);
9077
9078 memset(queryReplaceEffectMode,0,sizeof(int)*8);
9079 memset(queryReplaceEffectValMode,0,sizeof(int)*8);
9080 memset(queryReplaceEffect,0,sizeof(int)*8);
9081 memset(queryReplaceEffectVal,0,sizeof(int)*8);
9082 memset(queryReplaceEffectDo,0,sizeof(bool)*8);
9083 memset(queryReplaceEffectValDo,0,sizeof(bool)*8);
9084
9085 chanOscGrad.bgColor=ImVec4(0.0f,0.0f,0.0f,1.0f);
9086
9087 memset(noteOffLabel,0,32);
9088 memset(noteRelLabel,0,32);
9089 memset(macroRelLabel,0,32);
9090 memset(emptyLabel,0,32);
9091 memset(emptyLabel2,0,32);
9092 // effect sorting
9093 memset(effectsShow,1,sizeof(bool)*10);
9094
9095 memset(romExportAvail,0,sizeof(bool)*DIV_ROM_MAX);
9096
9097 songOrdersLengths.clear();
9098
9099 strncpy(noteOffLabel,"OFF",32);
9100 strncpy(noteRelLabel,"===",32);
9101 strncpy(macroRelLabel,"REL",32);
9102 strncpy(emptyLabel,"...",32);
9103 strncpy(emptyLabel2,"..",32);
9104 }