forked from crosspoint-reader/crosspoint-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileBrowserActivity.cpp
More file actions
528 lines (466 loc) · 19.2 KB
/
Copy pathFileBrowserActivity.cpp
File metadata and controls
528 lines (466 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#include "FileBrowserActivity.h"
#include <FsHelpers.h>
#include <GfxRenderer.h>
#include <HalStorage.h>
#include <I18n.h>
#include <Memory.h>
#include <algorithm>
#include "CrossPointSettings.h"
#include "MappedInputManager.h"
#include "activities/util/ConfirmationActivity.h"
#include "components/UITheme.h"
#include "components/UiAppHelpers.h"
#include "fontIds.h"
#include "util/BookCacheUtils.h"
namespace fui = freeink::ui;
namespace {
constexpr unsigned long GO_HOME_MS = 1000;
constexpr size_t NAME_BUFFER_SIZE = 500;
} // namespace
std::string getFileName(std::string filename);
std::string getFileExtension(const std::string& filename);
FileBrowserActivity::FileBrowserActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
std::string initialPath, const Mode mode)
: UiListActivity("FileBrowser", renderer, mappedInput, /*wantsTouchLongPress=*/true),
mode(mode),
basepath(initialPath.empty() ? "/" : std::move(initialPath)) {}
void FileBrowserActivity::loadFiles() {
files.clear();
auto root = Storage.open(basepath.c_str());
if (!root || !root.isDirectory()) {
rebuildRowItems(); // files is empty; also drops any now-stale cached rows
return;
}
root.rewindDirectory();
if (!fileNameBuffer) {
LOG_ERR("FileBrowser", "fileNameBuffer not allocated");
root.close();
rebuildRowItems();
return;
}
for (auto file = root.openNextFile(); file; file = root.openNextFile()) {
file.getName(fileNameBuffer.get(), NAME_BUFFER_SIZE);
const bool isDirectory = file.isDirectory();
if ((!SETTINGS.showHiddenFiles && fileNameBuffer[0] == '.') ||
strcmp(fileNameBuffer.get(), "System Volume Information") == 0) {
continue;
}
if (isDirectory) {
files.emplace_back(std::string(fileNameBuffer.get()) + "/");
} else {
std::string_view filename{fileNameBuffer.get()};
if (mode == Mode::PickFirmware) {
// Firmware picker: only show .bin files.
if (FsHelpers::checkFileExtension(filename, ".bin")) {
files.emplace_back(filename);
}
} else if (FsHelpers::hasEpubExtension(filename) || FsHelpers::hasXtcExtension(filename) ||
FsHelpers::hasTxtExtension(filename) || FsHelpers::hasMarkdownExtension(filename) ||
FsHelpers::hasBmpExtension(filename) || FsHelpers::hasPngExtension(filename)) {
files.emplace_back(filename);
}
}
}
root.close();
FsHelpers::sortFileList(files);
rebuildRowItems();
}
// Derives rowNames/rowExtensions/rowItems from `files`. Called whenever
// `files` changes (end of loadFiles()) so buildScreen() can reuse the cached
// rows on every repaint instead of re-deriving a name/extension string (and a
// ListItem) per file each time it's called.
void FileBrowserActivity::rebuildRowItems() {
rowsUseFileIcons = UITheme::getInstance().getTheme().showsFileIcons();
rowNames.resize(files.size());
rowExtensions.resize(files.size());
rowItems.clear();
rowItems.reserve(files.size());
for (size_t i = 0; i < files.size(); i++) {
rowNames[i] = getFileName(files[i]);
rowExtensions[i] = getFileExtension(files[i]);
fui::ListItem item;
item.label = rowNames[i].c_str();
if (!rowExtensions[i].empty()) item.value = rowExtensions[i].c_str();
item.icon = listIconFor(UITheme::getFileIcon(files[i]));
item.actionValue = static_cast<int16_t>(i);
rowItems.push_back(item);
}
// One SD pass for every CJK filename in the folder; repaints then hit the
// resident tables instead of re-reading per-string. Getter form: no
// concatenated copy (a bare-new string append aborts under heap pressure).
// The last index covers the bottom path band: basepath (possibly a CJK
// folder name) draws in the same small font, so it must live in the same
// batch or it would evict the rows' glyphs when the heap gate disables
// union merging. (prewarmFallbackText appends the truncation ellipsis.)
struct PrewarmCtx {
const std::vector<std::string>* names;
const std::string* path;
} prewarmCtx{&rowNames, &basepath};
renderer.prewarmFallbackText(
uiScaleSpec().smallFontId,
[](const void* ctx, uint32_t i) -> const char* {
const auto* c = static_cast<const PrewarmCtx*>(ctx);
return i < c->names->size() ? (*c->names)[i].c_str() : c->path->c_str();
},
&prewarmCtx, static_cast<uint32_t>(rowNames.size()) + 1);
}
void FileBrowserActivity::onEnter() {
UiListActivity::onEnter();
fileNameBuffer = makeUniqueNoThrow<char[]>(NAME_BUFFER_SIZE);
if (!fileNameBuffer) {
LOG_ERR("FileBrowser", "malloc failed for name buffer");
return;
}
auto root = Storage.open(basepath.c_str());
if (!root) {
basepath = "/";
loadFiles();
} else if (!root.isDirectory()) {
const std::string oldPath = basepath;
basepath = FsHelpers::extractFolderPath(basepath);
loadFiles();
const auto pos = oldPath.find_last_of('/');
const std::string fileName = oldPath.substr(pos + 1);
// The first screen build pulls the viewport to it (ListNav follow-on-build).
nav.selected = static_cast<int>(findEntry(fileName));
} else {
loadFiles();
}
}
void FileBrowserActivity::onExit() {
Activity::onExit();
files.clear();
rowNames.clear();
rowExtensions.clear();
rowItems.clear();
fileNameBuffer.reset();
}
// To avoid traversing directories twice (once for cache clearing, once for deletion),
// we do both in one pass here, instead of using Storage.removeDir
bool FileBrowserActivity::removeDirFile(const std::string& fullPath) {
auto file = Storage.open(fullPath.c_str());
if (!file) {
LOG_ERR("FileBrowser", "Failed to open for metadata clearing: %s", fullPath.c_str());
return false;
}
if (!file.isDirectory()) {
file.close();
clearBookCache(fullPath);
return Storage.remove(fullPath.c_str());
}
file.close();
if (!fileNameBuffer) {
LOG_ERR("FileBrowser", "fileNameBuffer not allocated");
return false;
}
// Stack of (dirPath, postOrder): postOrder=true means rmdir this path after children are processed.
std::vector<std::pair<std::string, bool>> stack;
stack.reserve(16);
stack.push_back({fullPath, false});
while (!stack.empty()) {
auto [currentPath, postOrder] = std::move(stack.back());
stack.pop_back();
if (postOrder) {
if (!Storage.rmdir(currentPath.c_str())) {
LOG_ERR("FileBrowser", "Failed to rmdir: %s", currentPath.c_str());
return false;
}
continue;
}
auto dir = Storage.open(currentPath.c_str());
if (!dir) {
LOG_ERR("FileBrowser", "Failed to open dir: %s", currentPath.c_str());
return false;
}
if (!dir.isDirectory()) {
LOG_ERR("FileBrowser", "Not a directory: %s", currentPath.c_str());
return false;
}
// Push this dir for post-order rmdir (after all children are processed).
stack.push_back({currentPath, true});
dir.rewindDirectory();
for (auto entry = dir.openNextFile(); entry; entry = dir.openNextFile()) {
entry.getName(fileNameBuffer.get(), NAME_BUFFER_SIZE);
if (strcmp(fileNameBuffer.get(), ".") == 0 || strcmp(fileNameBuffer.get(), "..") == 0) {
continue;
}
std::string entryPath = currentPath;
if (entryPath.back() != '/') {
entryPath += "/";
}
entryPath += fileNameBuffer.get();
const bool isDir = entry.isDirectory();
entry.close();
if (isDir) {
stack.push_back({std::move(entryPath), false});
} else {
clearBookCache(entryPath);
if (!Storage.remove(entryPath.c_str())) {
LOG_ERR("FileBrowser", "Failed to remove file: %s", entryPath.c_str());
return false;
}
}
}
}
return true;
}
void FileBrowserActivity::activateIndex(const int index) {
(void)index; // base already synced nav.selected to the tapped row
// Activation navigates or opens; a lingering flash would gray an unrelated
// row on the next list.
app.clearTapFlash();
activateSelected();
}
void FileBrowserActivity::onRowLongPress(const int index) {
(void)index; // base already synced nav.selected to the pressed row
// Activation navigates or opens; a lingering flash would gray an unrelated
// row on the next list.
app.clearTapFlash();
activateSelected(/*forceDelete=*/true);
}
void FileBrowserActivity::activateSelected(const bool forceDelete) {
if (files.empty()) return;
// A touch activation can carry a row index captured before a delete/reload
// shrank the list; the next render re-registers the rows.
if (nav.selected < 0 || nav.selected >= listCount()) return;
const std::string& entry = files[nav.selected];
bool isDirectory = (entry.back() == '/');
// Firmware picker: select file -> return path; navigate into directories normally.
if (mode == Mode::PickFirmware && !isDirectory) {
std::string cleanBasePath = basepath;
if (cleanBasePath.back() != '/') cleanBasePath += "/";
ActivityResult res{FilePathResult{cleanBasePath + entry}};
res.isCancelled = false;
setResult(std::move(res));
finish();
return;
}
if (mode == Mode::Books && (forceDelete || mappedInput.getHeldTime() >= GO_HOME_MS)) {
// --- LONG PRESS ACTION: DELETE FILE OR DIRECTORY ---
std::string cleanBasePath = basepath;
if (cleanBasePath.back() != '/') cleanBasePath += "/";
const std::string fullPath = cleanBasePath + entry;
auto handler = [this, fullPath](const ActivityResult& res) {
if (!res.isCancelled) {
LOG_DBG("FileBrowser", "Attempting to delete: %s", fullPath.c_str());
if (removeDirFile(fullPath)) {
LOG_DBG("FileBrowser", "Deleted successfully");
{
// buildScreen() reads the row caches on the render task; see loop().
RenderLock lock(*this);
loadFiles();
if (files.empty()) {
nav.selected = 0;
} else if (nav.selected >= listCount()) {
// Move selection to the new "last" item
nav.selected = listCount() - 1;
}
nav.follow(listCount());
}
requestUpdate(true);
} else {
LOG_ERR("FileBrowser", "Failed to delete: %s", fullPath.c_str());
}
} else {
LOG_DBG("FileBrowser", "Delete cancelled by user");
}
};
std::string heading = tr(STR_DELETE) + std::string("? ");
startActivityForResult(std::make_unique<ConfirmationActivity>(renderer, mappedInput, heading, entry), handler);
return;
} else {
// --- SHORT PRESS ACTION: OPEN/NAVIGATE ---
// buildScreen() runs on the render task and reads basepath plus the
// ListItem label/value pointers into rowNames/rowExtensions that
// rebuildRowItems() frees; mutate only under the render lock.
RenderLock lock(*this);
if (basepath.back() != '/') basepath += "/";
if (isDirectory) {
basepath += entry.substr(0, entry.length() - 1);
loadFiles();
nav.selected = 0;
nav.top = 0;
lock.unlock();
requestUpdate();
} else {
const std::string fullPath = basepath + entry;
lock.unlock(); // onSelectBook launches an activity; don't hold the lock across it
onSelectBook(fullPath);
}
}
return;
}
bool FileBrowserActivity::handleCustomInput() {
// Long press BACK (1s+) goes to root folder (Books mode only).
// In firmware-pick mode we keep navigation simple: short Back = up dir / cancel.
if (mode == Mode::Books && mappedInput.wasReleased(MappedInputManager::Button::Back) &&
mappedInput.getHeldTime() >= GO_HOME_MS && basepath != "/") {
{
// buildScreen() runs on the render task and reads basepath plus the
// row caches rebuildRowItems() frees; mutate only under the render lock.
RenderLock lock(*this);
basepath = "/";
loadFiles();
nav.selected = 0;
nav.top = 0;
}
requestUpdate();
return true;
}
return false;
}
bool FileBrowserActivity::handleButtons() {
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
activateSelected();
return true;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
// Short press: go up one directory, or go home if at root
if (mappedInput.getHeldTime() < GO_HOME_MS) {
if (basepath != "/") {
const std::string oldPath = basepath;
{
// buildScreen() runs on the render task and reads basepath plus the
// row caches rebuildRowItems() frees; mutate only under the render lock.
RenderLock lock(*this);
basepath.replace(basepath.find_last_of('/'), std::string::npos, "");
if (basepath.empty()) basepath = "/";
loadFiles();
const auto pos = oldPath.find_last_of('/');
const std::string dirName = oldPath.substr(pos + 1) + "/";
nav.selected = static_cast<int>(findEntry(dirName));
nav.top = 0;
nav.follow(listCount());
}
requestUpdate();
} else if (mode == Mode::PickFirmware) {
// Firmware picker at root: cancel back to caller instead of going home.
ActivityResult res;
res.isCancelled = true;
setResult(std::move(res));
finish();
} else {
onGoHome();
}
}
return true;
}
return false;
}
std::string getFileName(std::string filename) {
if (filename.back() == '/') {
filename.pop_back();
if (!UITheme::getInstance().getTheme().showsFileIcons()) {
return "[" + filename + "]";
}
return filename;
}
const auto pos = filename.rfind('.');
return filename.substr(0, pos);
}
std::string getFileExtension(const std::string& filename) {
if (filename.back() == '/') {
return "";
}
const auto pos = filename.rfind('.');
return filename.substr(pos);
}
void FileBrowserActivity::buildScreen(UiScreen& screen) {
const auto& metrics = UITheme::getInstance().getMetrics();
// Content below the GUI.drawHeader band, above the button hints.
screen.setContentMargin(fui::Insets{static_cast<int16_t>(metrics.topPadding + metrics.headerHeight), 0,
static_cast<int16_t>(metrics.buttonHintsHeight), 0});
screen.spacer(static_cast<int16_t>(metrics.verticalSpacing));
// Full path band at the bottom: separator on top, left-truncated so the
// deepest directory stays visible.
{
const int pathLineHeight = renderer.getLineHeight(SMALL_FONT_ID);
const fui::Rect band = screen.takeBottom(static_cast<int16_t>(pathLineHeight + metrics.verticalSpacing));
screen.target().fill(fui::Rect{band.x, band.y, band.width, 3}, fui::Paint::solid(fui::Color::Black));
const int pathY =
band.y + metrics.verticalSpacing / 2 + (band.height - metrics.verticalSpacing / 2 - pathLineHeight) / 2;
const int pathMaxWidth = band.width - metrics.contentSidePadding * 2;
const char* pathStr = basepath.c_str();
const char* pathDisplay = pathStr;
char leftTruncBuf[256];
if (renderer.getTextWidth(SMALL_FONT_ID, pathStr) > pathMaxWidth) {
const char ellipsis[] = "\xe2\x80\xa6"; // UTF-8 ellipsis (…)
const int ellipsisWidth = renderer.getTextWidth(SMALL_FONT_ID, ellipsis);
const int available = pathMaxWidth - ellipsisWidth;
// Walk forward from the start until the suffix fits, skipping UTF-8 continuation bytes
const char* p = pathStr;
while (*p) {
if (renderer.getTextWidth(SMALL_FONT_ID, p) <= available) break;
++p;
while (*p && (static_cast<unsigned char>(*p) & 0xC0) == 0x80) ++p;
}
snprintf(leftTruncBuf, sizeof(leftTruncBuf), "%s%s", ellipsis, p);
pathDisplay = leftTruncBuf;
}
renderer.drawText(SMALL_FONT_ID, band.x + metrics.contentSidePadding, pathY, pathDisplay);
}
if (files.empty()) {
screen.centeredText(mode == Mode::PickFirmware ? tr(STR_NO_BIN_FILES) : tr(STR_NO_FILES_FOUND),
screen.theme().bodyText);
return;
}
// rowNames/rowExtensions/rowItems are built once per loadFiles() call (see
// rebuildRowItems()) and reused here. getFileName()'s folder-bracket format
// depends on the theme, so a theme change picked up while this activity was
// paused underneath another screen invalidates the cache before it's read.
if (rowsUseFileIcons != UITheme::getInstance().getTheme().showsFileIcons()) {
rebuildRowItems();
}
fui::ListProps props;
props.items = rowItems.data();
props.count = static_cast<uint16_t>(rowItems.size());
props.action = ACTION_ROW;
// Tap opens/navigates; long-press prompts delete (physical buttons stay in loop()).
props.inputMask = fui::InputTouch | fui::InputLongPress;
props.valueInset = 8; // air between the extension and the row edge
// File names in the small font, wrapping onto a second line inside the same
// row height (rowHeight is derived from the small font itself: two of its
// lines plus 8, so two small lines always fit), so long names show more
// text. maxLines=2 doubles as the caller-owned marker: an all-default
// smallText fails textStyleUnset and Screen::list() would substitute
// bodyText back (FONT_SLOT_SMALL is 0).
fui::TextStyle label = screen.theme().smallText;
label.maxLines = 2;
props.labelText = label;
// The trailing value here is just the short extension: skip the balanced
// 60%-band wrap cap and let both name lines run the full width before it.
props.balanceWrappedLabelWithValue = false;
// Wrapped two-line names shrink how many rows fit a page, so the last row
// of a page can end up in leftover space: draw it as a partial preview so
// files past the fold are visibly present, not silently absent.
props.partialTrailingRow = true;
syncListViewport(screen, props);
screen.list(props);
}
void FileBrowserActivity::drawChrome() {
const auto pageWidth = renderer.getScreenWidth();
const auto& metrics = UITheme::getInstance().getMetrics();
std::string folderName =
(mode == Mode::PickFirmware)
? std::string(tr(STR_SELECT_FIRMWARE_FILE))
: ((basepath == "/") ? std::string(tr(STR_SD_CARD)) : basepath.substr(basepath.rfind('/') + 1));
// Header via GUI.drawHeader (already FreeInkUI-themed) for the battery
// indicator; the rest of the screen renders through the app.
GUI.drawHeader(renderer, Rect{0, metrics.topPadding, pageWidth, metrics.headerHeight}, folderName.c_str());
}
void FileBrowserActivity::drawFooter() {
const char* backLabel = (basepath == "/") ? (mode == Mode::PickFirmware ? tr(STR_BACK) : tr(STR_HOME)) : tr(STR_BACK);
// In PickFirmware mode, Confirm on a .bin returns the path to the caller (not "open"); show
// STR_SELECT instead. Directories in the same picker still descend, so keep STR_OPEN there.
const bool selectingFirmwareFile = mode == Mode::PickFirmware && !files.empty() && nav.selected >= 0 &&
nav.selected < listCount() && files[nav.selected].back() != '/';
const char* confirmLabel = files.empty() ? "" : (selectingFirmwareFile ? tr(STR_SELECT) : tr(STR_OPEN));
const auto labels = mappedInput.mapLabels(backLabel, confirmLabel, files.empty() ? "" : tr(STR_DIR_UP),
files.empty() ? "" : tr(STR_DIR_DOWN));
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
}
size_t FileBrowserActivity::findEntry(const std::string& name) const {
for (size_t i = 0; i < files.size(); i++)
if (files[i] == name) return i;
return 0;
}