Debian Codegraph @

src/gui/userPresets.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "gui.h"
21 #include "../baseutils.h"
22 #include "../fileutils.h"
23 #include <fmt/printf.h>
24 #include "IconsFontAwesome4.h"
25 #include <imgui.h>
26 #include "misc/cpp/imgui_stdlib.h"
27
28 #ifdef _WIN32
29 #define PRESETS_FILE "\\presets.cfg"
30 #else
31 #define PRESETS_FILE "/presets.cfg"
32 #endif
33
34 #define REDUNDANCY_NUM_ATTEMPTS 5
35 #define CHECK_BUF_SIZE 8192
36
37 std::vector<FurnaceGUISysDef>* digDeep(std::vector<FurnaceGUISysDef>& entries, int depth) {
38 if (depth==0) return &entries;
39 std::vector<FurnaceGUISysDef>& result=entries;
40
41 for (int i=0; i<depth; i++) {
42 if (result.empty()) {
43 logW("digDeep: %d is as far as it goes!",depth);
44 break;
45 }
46 result=result.at(result.size()).subDefs;
47 }
48 return &result;
49 }
50
51 bool FurnaceGUI::loadUserPresets(bool redundancy, String path, bool append) {
52 if (path.empty()) path=e->getConfigPath()+PRESETS_FILE;
53 String line, lineStr;
54 logD("opening user presets: %s",path);
55
56 FILE* f=NULL;
57
58 if (redundancy) {
59 unsigned char* readBuf=new unsigned char[CHECK_BUF_SIZE];
60 size_t readBufLen=0;
61 for (int i=0; i<REDUNDANCY_NUM_ATTEMPTS; i++) {
62 bool viable=false;
63 if (i>0) {
64 line=fmt::sprintf("%s.%d",path,i);
65 } else {
66 line=path;
67 }
68 logV("trying: %s",line);
69
70 // try to open config
71 f=ps_fopen(line.c_str(),"rb");
72 // check whether we could open it
73 if (f==NULL) {
74 logV("fopen(): %s",strerror(errno));
75 continue;
76 }
77
78 // check whether there's something
79 while (!feof(f)) {
80 readBufLen=fread(readBuf,1,CHECK_BUF_SIZE,f);
81 if (ferror(f)) {
82 logV("fread(): %s",strerror(errno));
83 break;
84 }
85
86 for (size_t j=0; j<readBufLen; j++) {
87 if (readBuf[j]==0) {
88 viable=false;
89 logW("a zero?");
90 break;
91 }
92 if (readBuf[j]!='\r' && readBuf[j]!='\n' && readBuf[j]!=' ') {
93 viable=true;
94 }
95 }
96
97 if (viable) break;
98 }
99
100 // there's something
101 if (viable) {
102 if (fseek(f,0,SEEK_SET)==-1) {
103 logV("fseek(): %s",strerror(errno));
104 viable=false;
105 } else {
106 break;
107 }
108 }
109
110 // close it (because there's nothing)
111 fclose(f);
112 f=NULL;
113 }
114 delete[] readBuf;
115
116 // we couldn't read at all
117 if (f==NULL) {
118 logD("presets file does not exist");
119 return false;
120 }
121 } else {
122 f=ps_fopen(path.c_str(),"rb");
123 if (f==NULL) {
124 logD("presets file does not exist");
125 return false;
126 }
127 }
128
129 // now read stuff
130 FurnaceGUISysCategory* userCategory=NULL;
131
132 for (FurnaceGUISysCategory& i: sysCategories) {
133 if (strcmp(i.name,_("User"))==0) {
134 userCategory=&i;
135 break;
136 }
137 }
138
139 if (userCategory==NULL) {
140 logE("could not find user category!");
141 fclose(f);
142 return false;
143 }
144
145 if (!append) userCategory->systems.clear();
146
147 char nextLine[4096];
148 lineStr="";
149 while (!feof(f)) {
150 if (fgets(nextLine,4095,f)==NULL) {
151 break;
152 }
153 lineStr+=nextLine;
154 if (!lineStr.empty() && !feof(f)) {
155 if (lineStr[lineStr.size()-1]!='\n') {
156 continue;
157 }
158 }
159
160 int indent=0;
161 bool readIndent=true;
162 bool keyOrValue=false;
163 String key="";
164 String value="";
165 for (char i: lineStr) {
166 if (i=='\n') break;
167 if (readIndent) {
168 if (i==' ') {
169 indent++;
170 } else {
171 readIndent=false;
172 }
173 }
174 if (!readIndent) {
175 if (keyOrValue) {
176 value+=i;
177 } else {
178 if (i=='=') {
179 keyOrValue=true;
180 } else {
181 key+=i;
182 }
183 }
184 }
185 }
186 indent>>=1;
187
188 if (!key.empty()) {
189 std::vector<FurnaceGUISysDef>* where=digDeep(userCategory->systems,indent);
190 where->push_back(FurnaceGUISysDef(key.c_str(),value.c_str(),e));
191 }
192
193 lineStr="";
194 lineStr.reserve(4096);
195 }
196
197 fclose(f);
198 return true;
199 }
200
201 void writeSubEntries(FILE* f, std::vector<FurnaceGUISysDef>& entries, int depth) {
202 for (FurnaceGUISysDef& i: entries) {
203 String safeName;
204 safeName.reserve(i.name.size());
205 bool beginning=false;
206 for (unsigned char j: i.name) {
207 if (beginning && j==' ') continue;
208 if (j=='=') continue;
209 if (j<0x20) continue;
210 safeName+=j;
211 }
212
213 String data;
214 for (int i=0; i<depth; i++) {
215 data+=" ";
216 }
217 data+=fmt::sprintf("%s=%s\n",safeName,taEncodeBase64(i.definition));
218 fputs(data.c_str(),f);
219
220 writeSubEntries(f,i.subDefs,depth+1);
221 }
222 }
223
224 bool FurnaceGUI::saveUserPresets(bool redundancy, String path) {
225 if (path.empty()) path=e->getConfigPath()+PRESETS_FILE;
226 FurnaceGUISysCategory* userCategory=NULL;
227
228 for (FurnaceGUISysCategory& i: sysCategories) {
229 if (strcmp(i.name,_("User"))==0) {
230 userCategory=&i;
231 break;
232 }
233 }
234
235 if (userCategory==NULL) {
236 logE("could not find user category!");
237 return false;
238 }
239
240 if (redundancy) {
241 char oldPath[4096];
242 char newPath[4096];
243
244 if (fileExists(path.c_str())==1) {
245 logD("rotating preset files...");
246 for (int i=4; i>=0; i--) {
247 if (i>0) {
248 snprintf(oldPath,4095,"%s.%d",path.c_str(),i);
249 } else {
250 strncpy(oldPath,path.c_str(),4095);
251 }
252 snprintf(newPath,4095,"%s.%d",path.c_str(),i+1);
253
254 if (i>=4) {
255 logV("remove %s",oldPath);
256 deleteFile(oldPath);
257 } else {
258 logV("move %s to %s",oldPath,newPath);
259 moveFiles(oldPath,newPath);
260 }
261 }
262 }
263 }
264 logD("saving user presets: %s",path);
265 FILE* f=ps_fopen(path.c_str(),"wb");
266 if (f==NULL) {
267 logW("could not write presets! %s",strerror(errno));
268 return false;
269 }
270
271 writeSubEntries(f,userCategory->systems,0);
272
273 fclose(f);
274 logD("presets written successfully.");
275 return true;
276 }
277
278 // user presets management
279 void FurnaceGUI::printPresets(std::vector<FurnaceGUISysDef>& items, size_t depth, std::vector<int>& depthStack) {
280 if (depth>0) ImGui::Indent();
281 int index=0;
282 for (FurnaceGUISysDef& i: items) {
283 bool isSelected=(selectedUserPreset.size()==(depth+1));
284 if (isSelected) {
285 for (size_t j=0; j<=depth; j++) {
286 int item=-1;
287 if (j>=depthStack.size()) {
288 item=index;
289 } else {
290 item=depthStack[j];
291 }
292
293 if (selectedUserPreset[j]!=item) {
294 isSelected=false;
295 break;
296 }
297 }
298 }
299 ImGui::PushID(index+1);
300 if (ImGui::Selectable(i.name.c_str(),isSelected)) {
301 selectedUserPreset=depthStack;
302 selectedUserPreset.push_back(index);
303 }
304 ImGui::PopID();
305 if (!i.subDefs.empty()) {
306 depthStack.push_back(index);
307 ImGui::PushID(index);
308 printPresets(i.subDefs,depth+1,depthStack);
309 ImGui::PopID();
310 depthStack.pop_back();
311 }
312 index++;
313 }
314 if (depth>0) ImGui::Unindent();
315 }
316
317 FurnaceGUISysDef* FurnaceGUI::selectPreset(std::vector<FurnaceGUISysDef>& items) {
318 FurnaceGUISysDef* ret=NULL;
319 for (size_t i=0; i<selectedUserPreset.size(); i++) {
320 if (selectedUserPreset[i]<0 || selectedUserPreset[i]>=(int)items.size()) return NULL;
321 ret=&items[selectedUserPreset[i]];
322 if (i<selectedUserPreset.size()-1) {
323 items=ret->subDefs;
324 }
325 }
326 return ret;
327 }
328
329 void FurnaceGUI::drawUserPresets() {
330 if (nextWindow==GUI_WINDOW_USER_PRESETS) {
331 userPresetsOpen=true;
332 ImGui::SetNextWindowFocus();
333 nextWindow=GUI_WINDOW_NOTHING;
334 }
335 if (!userPresetsOpen) return;
336 if (ImGui::Begin("User Systems",&userPresetsOpen,globalWinFlags,_("User Systems"))) {
337 FurnaceGUISysCategory* userCategory=NULL;
338 for (FurnaceGUISysCategory& i: sysCategories) {
339 if (strcmp(i.name,_("User"))==0) {
340 userCategory=&i;
341 break;
342 }
343 }
344
345 std::vector<int> depthStack;
346
347 if (userCategory==NULL) {
348 ImGui::Text(_("Error! User category does not exist!"));
349 } else if (ImGui::BeginTable("UserPresets",2,ImGuiTableFlags_BordersInnerV,ImVec2(ImGui::GetContentRegionAvail().x,ImGui::GetContentRegionAvail().y-ImGui::GetFrameHeightWithSpacing()))) {
350 ImGui::TableSetupColumn("c0",ImGuiTableColumnFlags_WidthStretch,0.25f);
351 ImGui::TableSetupColumn("c1",ImGuiTableColumnFlags_WidthStretch,0.75f);
352 // preset list
353 ImGui::TableNextRow();
354 ImGui::TableNextColumn();
355 if (ImGui::BeginChild("UList",ImVec2(ImGui::GetContentRegionAvail().x,ImGui::GetContentRegionAvail().y-ImGui::GetFrameHeightWithSpacing()))) {
356 ImGui::AlignTextToFramePadding();
357 ImGui::Text(_("Systems"));
358 ImGui::SameLine();
359 if (ImGui::Button(ICON_FA_PLUS "##AddPreset")) {
360 userCategory->systems.push_back(FurnaceGUISysDef(_("New Preset"),{}));
361 selectedUserPreset.clear();
362 selectedUserPreset.push_back(userCategory->systems.size()-1);
363 }
364 if (ImGui::IsItemHovered()) {
365 ImGui::SetTooltip(_("Add a new preset"));
366 }
367 ImGui::SameLine();
368 if (ImGui::Button(ICON_FA_UPLOAD)) {
369 userCategory->systems.push_back(FurnaceGUISysDef(e->song.systemName.c_str(),{}));
370 FurnaceGUISysDef* cur = &userCategory->systems[userCategory->systems.size()-1];
371 for (int i=0; i<e->song.systemLen; i++) { // get systems and flags
372 cur->orig.push_back(FurnaceGUISysDefChip(
373 e->song.system[i],
374 e->song.systemVol[i],
375 e->song.systemPan[i],
376 e->song.systemFlags[i].toString().c_str(),
377 e->song.systemPanFR[i]
378 ));
379 }
380 // get preset flags
381 DivConfig curFlags;
382 curFlags.set("tickRate", e->curSubSong->hz);
383 String chanMask;
384 for (int i=0; i<e->getTotalChannelCount(); i++) {
385 if (!e->curSubSong->chanShow[i]) {
386 if (chanMask.size()>0) chanMask+=", ";
387 chanMask+=fmt::sprintf("%d", i+1);
388 }
389 }
390 if (chanMask.size()>0) curFlags.set("chanMask", chanMask);
391 cur->extra=curFlags.toString().c_str();
392 cur->bake();
393 }
394 if (ImGui::IsItemHovered()) {
395 ImGui::SetTooltip(_("Create a preset from this song"));
396 }
397 printPresets(userCategory->systems,0,depthStack);
398 }
399 ImGui::EndChild();
400
401 // editor
402 ImGui::TableNextColumn();
403 if (ImGui::BeginChild("UEdit",ImVec2(ImGui::GetContentRegionAvail().x,ImGui::GetContentRegionAvail().y-ImGui::GetFrameHeightWithSpacing()))) {
404 if (selectedUserPreset.empty()) {
405 ImGui::Text(_("select a preset"));
406 } else {
407 FurnaceGUISysDef* preset=selectPreset(userCategory->systems);
408 bool doRemovePreset=false;
409
410 if (preset!=NULL) {
411 ImGui::AlignTextToFramePadding();
412 ImGui::Text(_("Name"));
413 ImGui::SameLine();
414 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x-ImGui::CalcTextSize(_("Remove")).x-ImGui::GetStyle().ItemSpacing.x*2.0-ImGui::GetStyle().ItemInnerSpacing.x*2.0);
415 ImGui::InputText("##PName",&preset->name);
416 ImGui::SameLine();
417 pushDestColor();
418 if (ImGui::Button(_("Remove##UPresetRemove"))) {
419 doRemovePreset=true;
420 }
421 popDestColor();
422
423 ImGui::Separator();
424
425 int doRemove=-1;
426 bool mustBake=false;
427
428 for (size_t i=0; i<preset->orig.size(); i++) {
429 String tempID;
430 FurnaceGUISysDefChip& chip=preset->orig[i];
431
432 bool doInvert=(chip.vol<0);
433 float vol=fabs(chip.vol);
434 ImGui::PushID(i);
435
436 tempID=fmt::sprintf("%s##USystem",getSystemName(chip.sys));
437 ImGui::Button(tempID.c_str(),ImVec2(ImGui::GetContentRegionAvail().x-ImGui::CalcTextSize(_("Invert")).x-ImGui::GetFrameHeightWithSpacing()*2.0-ImGui::GetStyle().ItemSpacing.x*2.0,0));
438 if (ImGui::BeginPopupContextItem("SysPickerCU",ImGuiPopupFlags_MouseButtonLeft)) {
439 DivSystem picked=systemPicker(false);
440 if (picked!=DIV_SYSTEM_NULL) {
441 chip.sys=picked;
442 mustBake=true;
443 ImGui::CloseCurrentPopup();
444 }
445 ImGui::EndPopup();
446 }
447
448 ImGui::SameLine();
449 if (ImGui::Checkbox(_("Invert"),&doInvert)) {
450 chip.vol=-chip.vol;
451 mustBake=true;
452 }
453 ImGui::SameLine();
454 pushDestColor();
455 if (ImGui::Button(ICON_FA_MINUS "##USysRemove")) {
456 doRemove=i;
457 mustBake=true;
458 }
459 popDestColor();
460 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x-ImGui::GetFrameHeightWithSpacing()*2.0-ImGui::GetStyle().ItemSpacing.x*2.0);
461 if (CWSliderFloat(_("Volume"),&vol,0.0f,3.0f)) {
462 if (doInvert) {
463 if (vol<0.0001) vol=0.0001;
464 }
465 if (vol<0) vol=0;
466 if (vol>10) vol=10;
467 chip.vol=doInvert?-vol:vol;
468 mustBake=true;
469 } rightClickable
470 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x-ImGui::GetFrameHeightWithSpacing()*2.0-ImGui::GetStyle().ItemSpacing.x*2.0);
471 if (CWSliderFloat(_("Panning"),&chip.pan,-1.0f,1.0f)) {
472 if (chip.pan<-1.0f) chip.pan=-1.0f;
473 if (chip.pan>1.0f) chip.pan=1.0f;
474 mustBake=true;
475 } rightClickable
476 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x-ImGui::GetFrameHeightWithSpacing()*2.0-ImGui::GetStyle().ItemSpacing.x*2.0);
477 if (CWSliderFloat(_("Front/Rear"),&chip.panFR,-1.0f,1.0f)) {
478 if (chip.panFR<-1.0f) chip.panFR=-1.0f;
479 if (chip.panFR>1.0f) chip.panFR=1.0f;
480 mustBake=true;
481 } rightClickable
482
483 if (ImGui::TreeNode(_("Configure"))) {
484 DivConfig sysFlags;
485 sysFlags.loadFromMemory(chip.flags.c_str());
486 if (drawSysConf(-1,i,chip.sys,sysFlags,false)) {
487 chip.flags=sysFlags.toString();
488 mustBake=true;
489 }
490 ImGui::TreePop();
491 }
492
493 ImGui::PopID();
494 }
495
496 if (doRemove>=0) {
497 preset->orig.erase(preset->orig.begin()+doRemove);
498 mustBake=true;
499 }
500
501 ImGui::Button(ICON_FA_PLUS "##SysAddU");
502 if (ImGui::BeginPopupContextItem("SysPickerU",ImGuiPopupFlags_MouseButtonLeft)) {
503 DivSystem picked=systemPicker(false);
504 if (picked!=DIV_SYSTEM_NULL) {
505 preset->orig.push_back(FurnaceGUISysDefChip(picked,1.0f,0.0f,""));
506 mustBake=true;
507 ImGui::CloseCurrentPopup();
508 }
509 ImGui::EndPopup();
510 }
511
512 ImGui::Separator();
513
514 ImGui::Text(_("Advanced"));
515 if (ImGui::InputTextMultiline("##UExtra",&preset->extra,ImVec2(ImGui::GetContentRegionAvail().x,120.0f*dpiScale),ImGuiInputTextFlags_UndoRedo)) {
516 mustBake=true;
517 }
518 if (ImGui::IsItemHovered()) {
519 ImGui::SetTooltip(_(
520 "insert additional settings in `option=value` format.\n"
521 "available options:\n"
522 "- tickRate \n"
523 "- chanMask \n"
524 ));
525 }
526
527 if (mustBake) preset->bake();
528 } else {
529 selectedUserPreset.clear();
530 }
531
532 if (doRemovePreset) {
533 std::vector<FurnaceGUISysDef>& items=userCategory->systems;
534 FurnaceGUISysDef* target=NULL;
535 for (size_t i=0; i<selectedUserPreset.size(); i++) {
536 if (selectedUserPreset[i]<0 || selectedUserPreset[i]>(int)items.size()) break;
537 target=&items[selectedUserPreset[i]];
538 if (i<selectedUserPreset.size()-1) {
539 items=target->subDefs;
540 } else {
541 items.erase(items.begin()+selectedUserPreset[i]);
542 }
543 }
544
545 selectedUserPreset.clear();
546 }
547 }
548 }
549 ImGui::EndChild();
550
551 ImGui::EndTable();
552 }
553
554 if (ImGui::Button(_("Save and Close"))) {
555 userPresetsOpen=false;
556 }
557 ImGui::SameLine();
558 ImGui::Dummy(ImVec2(8.0f*dpiScale,1.0f));
559 ImGui::SameLine();
560 if (ImGui::Button(_("Import"))) {
561 openFileDialog(GUI_FILE_IMPORT_USER_PRESETS);
562 }
563 ImGui::SameLine();
564 if (ImGui::Button(_("Import (replace)"))) {
565 openFileDialog(GUI_FILE_IMPORT_USER_PRESETS_REPLACE);
566 }
567 ImGui::SameLine();
568 if (ImGui::Button(_("Export"))) {
569 openFileDialog(GUI_FILE_EXPORT_USER_PRESETS);
570 }
571 }
572 if (!userPresetsOpen) {
573 saveUserPresets(true);
574 }
575 if (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows)) curWindow=GUI_WINDOW_USER_PRESETS;
576 ImGui::End();
577 }