book/reader.cpp

90 lines
2.9 KiB
C++
Raw Normal View History

2023-10-26 14:10:13 -04:00
#include <ncurses.h>
#include <filesystem>
#include <vector>
#include <fstream>
namespace fs = std::filesystem;
int main() {
initscr();
keypad(stdscr, TRUE);
noecho();
cbreak();
int maxY, maxX;
getmaxyx(stdscr, maxY, maxX); // Get the dimensions of the screen
// Create a separate window at the bottom for the static message
WINDOW *messageWin = newwin(2, maxX, maxY-2, 0);
mvwprintw(messageWin, 0, 0, "Press the right arrow to go to the next page or the left arrow to go back.");
mvwprintw(messageWin, 1, 0, "Press 'q' to exit.");
wrefresh(messageWin);
// Rest of the screen will be used for content
int contentHeight = maxY - 2;
WINDOW *contentPad = newpad(1000, maxX); // Create a pad (assuming max 1000 lines)
keypad(contentPad, TRUE);
std::string chaptersDir = "chapters";
if (!fs::exists(chaptersDir) || !fs::is_directory(chaptersDir)) {
printw("The 'chapters' directory does not exist!");
getch();
endwin();
return 1;
}
std::vector<fs::path> chapterDirs;
for (const auto &entry : fs::directory_iterator(chaptersDir)) {
if (fs::is_directory(entry)) {
chapterDirs.push_back(entry.path());
printw("%d. %s\n", chapterDirs.size(), entry.path().filename().string().c_str());
}
}
int choice;
echo();
printw("Which chapter would you like to read? Enter the number: ");
scanw("%d", &choice);
noecho();
int currentPage = 1;
int offsetY = 0; // For scrolling
while (true) {
wclear(contentPad);
fs::path pagePath = chapterDirs[choice-1] / ("page_" + std::to_string(currentPage) + ".txt");
if (fs::exists(pagePath) && fs::is_regular_file(pagePath)) {
std::ifstream pageFile(pagePath);
std::string line;
int lineNum = 0;
while (getline(pageFile, line)) {
mvwprintw(contentPad, lineNum++, 0, "%s", line.c_str());
}
pageFile.close();
}
prefresh(contentPad, offsetY, 0, 0, 0, contentHeight-1, maxX-1);
int ch = wgetch(contentPad);
fs::path nextPagePath = chapterDirs[choice-1] / ("page_" + std::to_string(currentPage + 1) + ".txt");
fs::path prevPagePath = chapterDirs[choice-1] / ("page_" + std::to_string(currentPage - 1) + ".txt");
if (ch == KEY_RIGHT && fs::exists(nextPagePath)) {
currentPage++;
offsetY = 0;
} else if (ch == KEY_LEFT && currentPage > 1 && fs::exists(prevPagePath)) {
currentPage--;
offsetY = 0;
} else if (ch == 'q') {
break;
} else if (ch == KEY_UP && offsetY > 0) {
offsetY--; // Scroll up
} else if (ch == KEY_DOWN) {
offsetY++; // Scroll down
}
}
delwin(contentPad);
delwin(messageWin);
endwin();
return 0;
}