stamenStatic Menu Generator |
git clone git://git.dimitrijedobrota.com/stamen.git |
Log | Files | Refs | README | LICENSE | HACKING | CONTRIBUTING | CODE_OF_CONDUCT | BUILDING |
dynamic.cpp (2441B)
0 #include <cmath> 1 #include <cstddef> 2 #include <format> 3 #include <fstream> 4 #include <iostream> 5 #include <limits> 6 #include <span> 7 8 #include "stamen/stamen.hpp" 9 10 namespace { 11 int display(const stamen::Menu& menu) 12 { 13 const int sizei = static_cast<int>(menu.items().size()); 14 const size_t dgts = static_cast<size_t>(std::log10(sizei)) + 1; 15 int choice = 0; 16 17 while (true) 18 { 19 std::cout << std::format("{}:\n", menu.title()); 20 for (auto i = 0UL; i < menu.items().size(); i++) 21 { 22 std::cout << std::format(" {:{}}. {}\n", i, dgts, menu.item(i).prompt); 23 } 24 25 while (true) 26 { 27 std::cout << "Choose an option: "; 28 if (std::cin >> choice && choice >= -1 && choice < sizei) 29 { 30 if (choice == -1) 31 { 32 std::cout << "Choice: back\n"; 33 return 1; 34 } 35 36 const auto uchoice = static_cast<size_t>(choice); 37 std::cout << "Choice: " << menu.item(uchoice).prompt << "\n\n"; 38 const int res = menu.item(uchoice).callback(uchoice); 39 40 if (res < 2) break; 41 return res - 1; 42 } 43 44 if (std::cin.eof()) 45 { 46 std::cerr << "encountered end of input!\n"; 47 return std::numeric_limits<int>::max(); 48 } 49 50 std::cin.clear(); 51 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 52 std::cout << "Invalid option, please choose again!\n"; 53 } 54 55 std::cout << '\n' << std::flush; 56 } 57 58 return 1; 59 } 60 61 int finish(std::size_t /* unused */) 62 { 63 // return from everything so that memory can be freed 64 return 1000; 65 } 66 67 int operation1(std::size_t /* unused */) 68 { 69 std::cout << "1\n"; 70 std::cout << std::flush; 71 return 1; 72 } 73 74 int operation2(std::size_t /* unused */) 75 { 76 std::cout << "2\n"; 77 std::cout << std::flush; 78 return 1; 79 } 80 81 int operation3(std::size_t /* unused */) 82 { 83 std::cout << "3\n"; 84 std::cout << std::flush; 85 return 1; 86 } 87 88 } // namespace 89 90 int main(int argc, char* argv[]) 91 { 92 const std::span args(argv, argv + argc); 93 94 if (argc != 2) 95 { 96 std::cout << std::format("Usage: {} filename\n", args[0]); 97 return 1; 98 } 99 100 std::ifstream ifs(args[1]); 101 102 // read the configuration 103 stamen::Stamen inst(ifs); 104 105 // register free functions 106 inst.insert("finish", finish); 107 inst.insert("operation1", operation1); 108 inst.insert("operation2", operation2); 109 inst.insert("operation3", operation3); 110 111 // start the menu on specific panel 112 inst.dynamic("menu_main", display); 113 114 return 0; 115 }