forked from timre13/sdl_file_chooser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsdl_file_chooser.cpp
730 lines (628 loc) · 22.6 KB
/
sdl_file_chooser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#include "sdl_file_chooser.h"
#include <cmath>
#include <stdint.h>
#include <iostream>
void FileChooser::renderCounter(SDL_Renderer *renderer, int currentOption, int totalOptions)
{
// Define text color (white for example)
SDL_Color textColor = {255, 255, 255, 255}; // RGBA format: white
// Load a smaller font for the counter (e.g., size 12)
TTF_Font *smallFont = TTF_OpenFont("./Anonymous_Pro.ttf", 24); // Adjust the path and size as needed
if (smallFont == nullptr)
{
std::cerr << "Failed to load small font: " << TTF_GetError() << std::endl;
return;
}
// Create the counter text: "currentOption/totalOptions"
std::string counterText = std::to_string(currentOption) + "/" + std::to_string(totalOptions);
// Render the text into an SDL_Surface using the smaller font
SDL_Surface *textSurface = TTF_RenderText_Solid(smallFont, counterText.c_str(), textColor);
if (textSurface == nullptr)
{
std::cerr << "Failed to create text surface: " << TTF_GetError() << std::endl;
TTF_CloseFont(smallFont); // Clean up the small font
return;
}
// Convert the SDL_Surface to SDL_Texture
SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
if (textTexture == nullptr)
{
std::cerr << "Failed to create texture: " << SDL_GetError() << std::endl;
SDL_FreeSurface(textSurface);
TTF_CloseFont(smallFont); // Clean up the small font
return;
}
// Get window size to position the counter in the bottom right corner
int windowWidth, windowHeight;
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
// Get text width and height from the surface
int textWidth = textSurface->w;
int textHeight = textSurface->h;
// Define destination rectangle for rendering the counter (bottom-right corner)
SDL_Rect dstRect = {windowWidth - textWidth - 10, windowHeight - textHeight - 10, textWidth, textHeight};
// Render the text texture onto the screen
SDL_RenderCopy(renderer, textTexture, nullptr, &dstRect);
// Clean up
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
TTF_CloseFont(smallFont); // Clean up the small font
}
// Number of files displayed per page
Mix_Chunk *FileChooser::loadClickSound(const std::vector<std::string> &paths)
{
// Initialize audio only once before attempting to load sounds
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
std::cerr << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << '\n';
std::exit(2);
}
// Try loading the sound from the specified paths
for (const auto &path : paths)
{
Mix_Chunk *sound = Mix_LoadWAV(path.c_str());
if (sound != nullptr)
{
return sound; // Return the successfully loaded sound
}
// std::cerr << "Failed to load click sound from " << path << "! SDL_mixer Error: " << Mix_GetError() << '\n';
}
// If no sound file could be loaded, close the audio
Mix_CloseAudio(); // Close the audio system if no sound was loaded
return nullptr; // Return nullptr if no path succeeded
}
void FileChooser::getFileList(std::string directory, bool recursive)
{
auto matchFilters = [&](const std::filesystem::path &file)
{
// Convert file name to lowercase
std::string filename = file.filename().string();
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
if (filters.empty())
{
return true; // No filters means all files are allowed
}
for (const auto &filter : filters)
{
std::string lowerFilter = filter;
std::transform(lowerFilter.begin(), lowerFilter.end(), lowerFilter.begin(), ::tolower);
// Check if the filter is present in the file name
if (filename.find(lowerFilter) != std::string::npos)
{
return true;
}
}
return false;
};
if (recursive)
{
auto files{std::filesystem::recursive_directory_iterator{
directory,
std::filesystem::directory_options::skip_permission_denied}};
for (auto &file : files)
{
if (std::filesystem::is_regular_file(file) && matchFilters(file.path()))
{
fileList.push_back(file.path().string());
}
}
}
else
{
auto files{std::filesystem::directory_iterator{
directory,
std::filesystem::directory_options::skip_permission_denied}};
for (auto &file : files)
{
if (std::filesystem::is_regular_file(file) && matchFilters(file.path()))
{
fileList.push_back(file.path().string());
}
}
}
std::sort(fileList.begin(), fileList.end());
}
// Update constructor to handle filters and sound
FileChooser::FileChooser(std::string directory, std::string title, std::string backgroundImage, bool recursive, std::vector<std::string> filters)
: fileList(), filters(filters), window(nullptr), renderer(nullptr), font(nullptr), backgroundTexture(nullptr), clickSound(nullptr), chosenFileI(0), title(title)
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO);
TTF_Init();
// Load the "click" sound
std::vector<std::string> soundPaths = {
"/mnt/SDCARD/System/usr/trimui/res/sound/click.wav",
"click.wav",
"/usr/trimui/res/sound/click.wav"};
clickSound = loadClickSound(soundPaths);
if (clickSound == nullptr)
{
std::cerr << "No valid click sound file found.\n";
}
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 1000, SDL_WINDOW_ALLOW_HIGHDPI);
if (!window)
{
std::cerr << "Unable to create window" << '\n';
std::exit(2);
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer)
{
std::cerr << "Unable to create renderer" << '\n';
std::exit(2);
}
if (!backgroundImage.empty())
{
SDL_Surface *bgSurface = IMG_Load(backgroundImage.c_str());
if (bgSurface)
{
backgroundTexture = SDL_CreateTextureFromSurface(renderer, bgSurface);
SDL_FreeSurface(bgSurface);
}
else
{
std::cerr << "Failed to load background image: " << IMG_GetError() << '\n';
}
}
font = TTF_OpenFont("./Anonymous_Pro.ttf", 100);
if (!font)
{
std::cerr << "Unable to open font file." << '\n';
std::exit(2);
}
SDL_GameController *controller = NULL;
if (SDL_NumJoysticks() > 0)
{
controller = SDL_GameControllerOpen(0);
if (!controller)
{
std::cerr << "Failed to open controller: " << SDL_GetError() << '\n';
}
}
else
{
std::cerr << "No joystick found\n";
}
drawTitle("Loading...");
SDL_RenderPresent(renderer);
getFileList(directory, recursive); // Call with filters and recursive flag
bool isRunning{true};
auto lastDpadPressTime = std::chrono::steady_clock::now();
const int scrollIntervalMs = 220; // Adjust scrolling speed here
bool dpadDownPressed = false;
bool dpadUpPressed = false;
while (isRunning)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
chosenFileI = -1;
isRunning = false;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
chosenFileI = -1;
isRunning = false;
break;
case SDLK_DOWN:
case SDLK_s:
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
break;
case SDLK_UP:
case SDLK_w:
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
break;
case SDLK_RETURN:
isRunning = false;
break;
}
break;
case SDL_CONTROLLERBUTTONDOWN:
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
dpadDownPressed = true;
lastDpadPressTime = std::chrono::steady_clock::now();
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
dpadUpPressed = true;
lastDpadPressTime = std::chrono::steady_clock::now();
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_B)
{
isRunning = false;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A)
{
chosenFileI = -1;
isRunning = false;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER) // L1
{
if (chosenFileI > 0)
{
chosenFileI -= filesPerPage;
if (chosenFileI < 0)
chosenFileI = 0; // Prevent underflow
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER) // R1
{
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
chosenFileI += filesPerPage;
if (chosenFileI >= static_cast<int>(fileList.size()))
chosenFileI = static_cast<int>(fileList.size()) - 1; // Prevent overflow
Mix_PlayChannel(-1, clickSound, 0);
}
}
break;
case SDL_CONTROLLERBUTTONUP:
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
dpadDownPressed = false;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
dpadUpPressed = false;
}
break;
}
}
auto currentTime = std::chrono::steady_clock::now();
auto timeSinceLastPress = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - lastDpadPressTime).count();
if (dpadDownPressed && timeSinceLastPress >= scrollIntervalMs)
{
lastDpadPressTime = currentTime;
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (dpadUpPressed && timeSinceLastPress >= scrollIntervalMs)
{
lastDpadPressTime = currentTime;
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
drawBackground();
drawSelector();
drawTitle(title);
drawFileList();
SDL_RenderPresent(renderer);
SDL_Delay(20);
}
if (backgroundTexture)
{
SDL_DestroyTexture(backgroundTexture);
}
if (controller)
{
SDL_GameControllerClose(controller);
}
deinit();
}
void FileChooser::drawFileList()
{
for (int i = 0; i < static_cast<int>(fileList.size()); ++i)
{
int y = 500 - chosenFileI * 30 + i * 30;
if (y < 1000 && y > 0)
{
SDL_Surface *textSurface = TTF_RenderText_Blended(
font,
fileList[i].c_str(),
{255, 255, 255, static_cast<uint8_t>(255 - std::abs(500 - y) / 2)});
SDL_Rect sourceRect{0, 0, textSurface->w, textSurface->h};
SDL_Rect targetRect{0, y, textSurface->w / 5, textSurface->h / 5};
SDL_Texture *textTexture{SDL_CreateTextureFromSurface(renderer, textSurface)};
SDL_RenderCopy(renderer, textTexture, &sourceRect, &targetRect);
SDL_DestroyTexture(textTexture);
SDL_FreeSurface(textSurface);
// Call the method to display the counter in the bottom right corner
renderCounter(renderer, chosenFileI + 1, static_cast<int>(fileList.size()));
}
}
}
void FileChooser::drawTitle(const std::string &title)
{
int lineHeight = 40; // Height between lines (adjustable according to font size)
int yOffset = 10; // Vertical position of first line
// Divide title with line breaks
std::istringstream stream(title);
std::string line;
while (std::getline(stream, line, '\n'))
{
SDL_Surface *textSurface = TTF_RenderText_Solid(font, line.c_str(), {255, 255, 255, 255});
SDL_Rect sourceRect{0, 0, textSurface->w, textSurface->h};
SDL_Rect targetRect{10, yOffset, textSurface->w / 3, textSurface->h / 3}; // Adjust text size here
SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_RenderCopy(renderer, textTexture, &sourceRect, &targetRect);
SDL_DestroyTexture(textTexture);
SDL_FreeSurface(textSurface);
yOffset += lineHeight; // Adjust offset for next line
}
}
void FileChooser::drawSelector()
{
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 100);
SDL_Rect selectorRect{0, 500, 800, 25};
SDL_RenderFillRect(renderer, &selectorRect);
}
void FileChooser::drawBackground()
{
if (backgroundTexture)
{
SDL_RenderCopy(renderer, backgroundTexture, NULL, NULL); // Full-window image
}
}
// New builder for customized selections with D-Pad event management
FileChooser::FileChooser(std::vector<std::string> customChoices, std::string title, std::string backgroundImage)
: window(nullptr), renderer(nullptr), font(nullptr), backgroundTexture(nullptr), clickSound(nullptr), chosenFileI(0), title(title)
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO);
TTF_Init();
// Load the "click" sound
std::vector<std::string> soundPaths = {
"/mnt/SDCARD/System/usr/trimui/res/sound/click.wav",
"click.wav",
"/usr/trimui/res/sound/click.wav"};
clickSound = loadClickSound(soundPaths);
if (clickSound == nullptr)
{
std::cerr << "No valid click sound file found.\n";
}
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 1000, SDL_WINDOW_ALLOW_HIGHDPI);
if (!window)
{
std::cerr << "Unable to create window" << '\n';
std::exit(2);
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer)
{
std::cerr << "Unable to create renderer" << '\n';
std::exit(2);
}
// Load background image if supplied
if (!backgroundImage.empty())
{
SDL_Surface *bgSurface = IMG_Load(backgroundImage.c_str());
if (bgSurface)
{
backgroundTexture = SDL_CreateTextureFromSurface(renderer, bgSurface);
SDL_FreeSurface(bgSurface);
}
else
{
std::cerr << "Failed to load background image: " << IMG_GetError() << '\n';
}
}
font = TTF_OpenFont("./Anonymous_Pro.ttf", 100);
if (!font)
{
std::cerr << "Unable to open font file." << '\n';
std::exit(2);
}
fileList = customChoices; // Use the custom choices provided
// Controller opening if available
SDL_GameController *controller = NULL;
if (SDL_NumJoysticks() > 0)
{
controller = SDL_GameControllerOpen(0);
if (!controller)
{
std::cerr << "Failed to open controller: " << SDL_GetError() << '\n';
}
}
else
{
std::cerr << "No joystick found\n";
}
/* drawTitle("Loading...");
SDL_RenderPresent(renderer); */
bool isRunning{true};
auto lastDpadPressTime = std::chrono::steady_clock::now();
const int scrollIntervalMs = 220;
bool dpadDownPressed = false;
bool dpadUpPressed = false;
while (isRunning)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
chosenFileI = -1;
isRunning = false;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
chosenFileI = -1;
isRunning = false;
break;
case SDLK_DOWN:
case SDLK_s:
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
break;
case SDLK_UP:
case SDLK_w:
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
break;
case SDLK_RETURN:
isRunning = false;
deinit();
return;
}
break;
case SDL_CONTROLLERBUTTONDOWN:
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
dpadDownPressed = true;
lastDpadPressTime = std::chrono::steady_clock::now();
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
dpadUpPressed = true;
lastDpadPressTime = std::chrono::steady_clock::now();
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A)
{
chosenFileI = -1;
isRunning = false;
deinit();
return;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_B)
{
isRunning = false;
deinit();
return;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER) // L1
{
if (chosenFileI > 0)
{
chosenFileI -= filesPerPage;
if (chosenFileI < 0)
chosenFileI = 0; // Prevent underflow
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER) // R1
{
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
chosenFileI += filesPerPage;
if (chosenFileI >= static_cast<int>(fileList.size()))
chosenFileI = static_cast<int>(fileList.size()) - 1; // Prevent overflow
Mix_PlayChannel(-1, clickSound, 0);
}
}
break;
case SDL_CONTROLLERBUTTONUP:
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
dpadDownPressed = false;
}
else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
dpadUpPressed = false;
}
break;
case SDL_CONTROLLERAXISMOTION:
break; // Completely ignore analog stick input
}
}
auto currentTime = std::chrono::steady_clock::now();
auto timeSinceLastPress = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - lastDpadPressTime).count();
if (dpadDownPressed && timeSinceLastPress >= scrollIntervalMs)
{
lastDpadPressTime = currentTime;
if (chosenFileI < static_cast<int>(fileList.size()) - 1)
{
++chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
else if (dpadUpPressed && timeSinceLastPress >= scrollIntervalMs)
{
lastDpadPressTime = currentTime;
if (chosenFileI > 0)
{
--chosenFileI;
Mix_PlayChannel(-1, clickSound, 0);
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
drawBackground();
drawSelector();
drawTitle(title);
drawFileList();
SDL_RenderPresent(renderer);
SDL_Delay(20);
}
if (backgroundTexture)
{
SDL_DestroyTexture(backgroundTexture);
}
if (controller)
{
SDL_GameControllerClose(controller);
}
deinit();
}
std::string FileChooser::get()
{
if (chosenFileI < 0)
return "";
return fileList[chosenFileI];
}
void FileChooser::deinit()
{
if (clickSound)
{
Mix_FreeChunk(clickSound);
clickSound = nullptr;
}
if (font)
TTF_CloseFont(font);
if (renderer)
SDL_DestroyRenderer(renderer);
if (window)
SDL_DestroyWindow(window);
Mix_CloseAudio();
Mix_Quit(); // Exit SDL_mixer
TTF_Quit();
SDL_Quit();
}