Files
libstorm-nvgt/file_viewer.nvgt
2026-02-16 19:49:29 -05:00

86 lines
1.9 KiB
Plaintext

#include "form.nvgt"
// Reusable text/file viewer based on NVGT audio_form.
// Returns edited text in edit mode when user confirms.
string file_viewer(string content, string title = "Text Reader", bool readOnly = true) {
audio_form f;
f.create_window(title, false, true);
int textControl = f.create_input_box(
(readOnly ? "Document (read only)" : "Document (editable)"),
content,
"",
0,
readOnly,
true,
true
);
int okButton = -1;
int closeButton = -1;
if (readOnly) {
closeButton = f.create_button("&Close", true, true);
} else {
okButton = f.create_button("&OK", true);
closeButton = f.create_button("&Cancel", false, true);
}
f.focus(textControl);
while (true) {
f.monitor();
wait(5);
if (!readOnly && okButton != -1 && f.is_pressed(okButton)) {
return f.get_text(textControl);
}
if (closeButton != -1 && f.is_pressed(closeButton)) {
return "";
}
if (key_pressed(KEY_ESCAPE)) {
return "";
}
}
return "";
}
string file_viewer_lines(string[] lines, string title = "Text Reader", bool readOnly = true) {
string content = join(lines, "\n");
return file_viewer(content, title, readOnly);
}
// Opens a file in the viewer. In edit mode, saves on confirm.
// Returns edited text when saved or empty string when canceled/failure.
string file_viewer_file(string filePath, string title = "", bool readOnly = true) {
file f;
if (!f.open(filePath, "rb")) {
screen_reader_speak("Failed to open file: " + filePath, true);
return "";
}
string content = f.read();
f.close();
if (title == "") {
title = filePath;
}
string result = file_viewer(content, title, readOnly);
if (!readOnly && result != "") {
if (f.open(filePath, "wb")) {
f.write(result);
f.close();
screen_reader_speak("File saved successfully", true);
return result;
}
screen_reader_speak("Failed to save file", true);
}
return result;
}