-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.cpp
More file actions
594 lines (482 loc) · 21 KB
/
Copy pathdemo.cpp
File metadata and controls
594 lines (482 loc) · 21 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
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
/**
* TUIX Library Demo
* Comprehensive examples and usage demonstrations
*
* Compile with: g++ -std=c++17 -O2 demo.cpp -o demo
* Run with: ./demo
*/
#define TUIX_INCLUDE_DEMO
#include "tuix.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
using namespace tuix;
void basic_examples() {
utils::print_banner("Basic Examples", "Simple usage patterns");
// 1. Titles and headings
std::cout << color::bold("1. Titles and Headings:") << '\n';
print_title("Welcome to TUIX", 50, '=');
print_heading("Main Section", 1);
print_heading("Subsection", 2);
print_heading("Sub-subsection", 3);
std::cout << '\n';
// 2. Text alignment
std::cout << color::bold("2. Text Alignment:") << '\n';
std::cout << left("Left aligned", 30, '.') << "|\n";
std::cout << center("Centered", 30, '.') << "|\n";
std::cout << right("Right aligned", 30, '.') << "|\n";
std::cout << '\n';
// 3. Colors
std::cout << color::bold("3. Colors and Formatting:") << '\n';
std::cout << color::red("Red") << " | ";
std::cout << color::green("Green") << " | ";
std::cout << color::blue("Blue") << " | ";
std::cout << color::yellow("Yellow") << " | ";
std::cout << color::magenta("Magenta") << " | ";
std::cout << color::cyan("Cyan") << '\n';
std::cout << color::bold("Bold") << " | ";
std::cout << color::italic("Italic") << " | ";
std::cout << color::underline("Underlined") << '\n';
std::cout << '\n';
}
void advanced_formatting() {
utils::print_banner("Advanced Formatting", "Boxes, tables, and more");
// 1. Boxes with different styles
std::cout << color::bold("1. Box Styles:") << '\n';
print_boxed("Single border box\nwith multiple lines", box_style::single, "Single");
box double_box("Double border box with custom content");
double_box.set_style(box_style::double_).set_title("Double Border").set_alignment(align::center);
std::cout << double_box;
box rounded_box("Rounded corners look modern!\nGreat for notifications.");
rounded_box.set_style(box_style::rounded).set_title("Notification").set_padding(2);
std::cout << rounded_box;
// 2. Tables
std::cout << color::bold("2. Tables:") << '\n';
// Simple table
table simple_table;
simple_table.set_headers({"Product", "Price", "Stock"})
.add_row({"Laptop", "$999.99", "15"})
.add_row({"Mouse", "$24.99", "150"})
.add_row({"Keyboard", "$79.99", "45"})
.set_column_alignment(1, align::right)
.set_column_alignment(2, align::center);
std::cout << simple_table;
// Fancy table with different style
table fancy_table;
fancy_table.set_headers({"Name", "Department", "Salary", "Performance"})
.add_row({"Alice Johnson", "Engineering", "$85,000", "★★★★★"})
.add_row({"Bob Smith", "Marketing", "$65,000", "★★★★☆"})
.add_row({"Carol Williams", "Design", "$70,000", "★★★★★"})
.add_row({"David Brown", "Sales", "$60,000", "★★★☆☆"})
.set_style(box_style::double_)
.set_column_alignment(2, align::right)
.set_column_alignment(3, align::center);
std::cout << fancy_table << '\n';
}
void interactive_elements() {
utils::print_banner("Interactive Elements", "Progress bars, spinners, and prompts");
// 1. Progress bars
std::cout << color::bold("1. Progress Bars:") << '\n';
progress_bar basic_pb(40);
basic_pb.set_prefix("Download: ");
std::cout << "Basic progress bar:\n";
for (int i = 0; i <= 100; i += 10) {
basic_pb.print(i / 100.0);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
basic_pb.finish();
progress_bar custom_pb(30);
custom_pb.set_chars('#', '.').set_prefix("Install: ").set_suffix(" Complete");
std::cout << "Custom progress bar:\n";
for (int i = 0; i <= 100; i += 25) {
custom_pb.print(i / 100.0);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
custom_pb.finish();
// 2. Spinners
std::cout << color::bold("\n2. Spinners:") << '\n';
spinner basic_spinner("Loading data...");
basic_spinner.start();
std::this_thread::sleep_for(std::chrono::seconds(2));
basic_spinner.stop();
log_success("Data loaded successfully!");
spinner fancy_spinner("Processing...");
fancy_spinner.set_frames({"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"});
fancy_spinner.start();
std::this_thread::sleep_for(std::chrono::seconds(2));
fancy_spinner.stop();
log_success("Processing completed!");
std::cout << '\n';
}
void logging_demo() {
utils::print_banner("Logging System", "Different log levels and formatting");
// Configure logging
get_logger().set_timestamp(true);
std::cout << color::bold("Logging with timestamps:") << '\n';
log_debug("Debug message (usually hidden)");
log_info("Application started");
log_info("Loading configuration file");
log_warning("Configuration file not found, using defaults");
log_error("Failed to connect to external service");
log_success("Fallback connection established");
log_info("Application ready");
// Reset timestamp
get_logger().set_timestamp(false);
std::cout << '\n' << color::bold("Different log levels:") << '\n';
get_logger().set_level(log_level::debug);
log_debug("Now debug messages are visible");
log_info("Info level message");
log_warning("Warning level message");
log_error("Error level message");
log_success("Success level message");
get_logger().set_level(log_level::info); // Reset
std::cout << '\n';
}
void lists_and_structure() {
utils::print_banner("Lists and Structure", "Bullets, dividers, and organization");
// 1. Simple bullet lists
std::cout << color::bold("1. Simple Lists:") << '\n';
print_bullet_list({
"First item",
"Second item",
"Third item with longer text that might wrap"
});
print_bullet_list({
"Custom bullet item 1",
"Custom bullet item 2"
}, "→ ");
// 2. Nested lists
std::cout << color::bold("\n2. Nested Lists:") << '\n';
nested_list menu;
menu.add_item("Main Menu", 0)
.add_item("File Operations", 1)
.add_item("New File", 2)
.add_item("Open File", 2)
.add_item("Save File", 2)
.add_item("Edit Operations", 1)
.add_item("Cut", 2)
.add_item("Copy", 2)
.add_item("Paste", 2)
.add_item("Advanced", 2)
.add_item("Find & Replace", 3)
.add_item("Go to Line", 3)
.add_item("Help", 1)
.add_item("About", 2)
.add_item("Documentation", 2);
std::cout << menu;
// 3. Dividers and sections
std::cout << color::bold("3. Dividers and Sections:") << '\n';
print_divider(50, '=');
print_section("Configuration Settings", 50);
std::cout << "Database URL: localhost:5432\n";
std::cout << "Max Connections: 100\n";
std::cout << "Timeout: 30s\n";
print_section("Security Settings", 50);
std::cout << "SSL Enabled: Yes\n";
std::cout << "Auth Method: JWT\n";
print_divider(50, '=');
std::cout << '\n';
}
void markdown_and_themes() {
utils::print_banner("Markdown & Themes", "Rich text and theming");
// 1. Markdown rendering
std::cout << color::bold("1. Markdown Rendering:") << '\n';
print_markdown(R"(
# Welcome to TUIX
## Features
- **Bold text** support
- *Italic text* rendering
- __Underlined text__ formatting
- `Code highlighting` with colors
### Getting Started
1. Include the header: `#include "tuix.hpp"`
2. Use the **tuix** namespace
3. Start creating *beautiful* console apps!
**Note**: This is a __demonstration__ of markdown-like rendering.
)");
// 2. Theme switching
std::cout << color::bold("2. Theme Examples:") << '\n';
// Default theme
std::cout << "Default theme:\n";
print_boxed("This uses the default color scheme", box_style::single, "Default");
// Dark theme
themes::set_theme(themes::get_dark_theme());
std::cout << "Dark theme:\n";
print_boxed("This uses bright colors for dark terminals", box_style::rounded, "Dark");
// Minimal theme
themes::set_theme(themes::get_minimal_theme());
std::cout << "Minimal theme:\n";
print_boxed("This uses minimal colors and styling", box_style::single, "Minimal");
// Reset to default
themes::set_theme(themes::get_default_theme());
std::cout << '\n';
}
void real_world_examples() {
utils::print_banner("Real-World Examples", "Practical usage scenarios");
// 1. System status dashboard
std::cout << color::bold("1. System Status Dashboard:") << '\n';
table status_table;
status_table.set_headers({"Service", "Status", "Uptime", "Memory"})
.add_row({"Web Server", color::green("Running"), "15d 4h 23m", "245 MB"})
.add_row({"Database", color::green("Running"), "15d 4h 23m", "1.2 GB"})
.add_row({"Cache", color::yellow("Warning"), "2d 1h 15m", "512 MB"})
.add_row({"Queue", color::red("Stopped"), "0m", "0 MB"})
.set_style(box_style::double_);
std::cout << status_table;
// 2. Installation progress
std::cout << color::bold("2. Installation Simulation:") << '\n';
std::vector<std::string> steps = {
"Downloading packages...",
"Verifying checksums...",
"Extracting files...",
"Installing dependencies...",
"Configuring system...",
"Cleaning up..."
};
progress_bar install_pb(50);
install_pb.set_chars('#', '.').set_prefix("Installing: ");
for (size_t i = 0; i < steps.size(); ++i) {
log_info(steps[i]);
// Simulate work with progress
for (int j = 0; j <= 100; j += 20) {
double overall_progress = (i + j/100.0) / steps.size();
install_pb.print(overall_progress);
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
install_pb.finish();
log_success("Installation completed successfully!");
// 3. Configuration wizard
std::cout << color::bold("\n3. Configuration Menu:") << '\n';
box config_box(R"(Configuration Wizard
Select your preferred settings:
• Database: PostgreSQL
• Cache: Redis
• Auth: OAuth 2.0
• Logging: INFO level
All settings can be changed later.)");
config_box.set_style(box_style::rounded).set_title("Setup").set_alignment(align::left);
std::cout << config_box;
// 4. Error reporting
std::cout << color::bold("4. Error Report:") << '\n';
print_section("Error Summary", 60, '!');
log_error("Connection timeout to database server");
log_error("Failed to load user preferences");
log_warning("Using default configuration");
nested_list error_details;
error_details.add_item("Critical Errors: 2", 0)
.add_item("Database Connection Failed", 1)
.add_item("Host: db.example.com:5432", 2)
.add_item("Timeout: 30 seconds", 2)
.add_item("User Preferences Load Failed", 1)
.add_item("File: ~/.config/app/prefs.json", 2)
.add_item("Error: Permission denied", 2)
.add_item("Warnings: 1", 0)
.add_item("Using fallback configuration", 1);
std::cout << error_details;
print_divider(60, '!');
std::cout << '\n';
}
void performance_showcase() {
utils::print_banner("Performance Test", "Benchmarking library components");
auto start = std::chrono::high_resolution_clock::now();
// Large table test
std::cout << color::bold("Creating large table (1000 rows)...") << '\n';
table large_table;
large_table.set_headers({"ID", "Name", "Email", "Department", "Salary", "Status"});
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> salary_dist(30000, 150000);
std::vector<std::string> departments = {"Engineering", "Marketing", "Sales", "HR", "Finance"};
std::vector<std::string> statuses = {"Active", "Inactive", "On Leave", "Remote"};
for (int i = 1; i <= 1000; ++i) {
large_table.add_row({
std::to_string(i),
"User " + std::to_string(i),
"user" + std::to_string(i) + "@company.com",
departments[i % departments.size()],
"$" + std::to_string(salary_dist(gen)),
statuses[i % statuses.size()]
});
}
auto mid = std::chrono::high_resolution_clock::now();
// Measure rendering time (but don't output the huge table)
std::ostringstream dummy_stream;
dummy_stream << large_table;
std::string rendered = dummy_stream.str();
auto end = std::chrono::high_resolution_clock::now();
auto setup_time = std::chrono::duration_cast<std::chrono::microseconds>(mid - start);
auto render_time = std::chrono::duration_cast<std::chrono::microseconds>(end - mid);
// Results table
table perf_results;
perf_results.set_headers({"Metric", "Value", "Unit"})
.add_row({"Rows", "1,000", "entries"})
.add_row({"Columns", "6", "columns"})
.add_row({"Setup Time", std::to_string(setup_time.count()), "μs"})
.add_row({"Render Time", std::to_string(render_time.count()), "μs"})
.add_row({"Output Size", std::to_string(rendered.size()), "bytes"})
.add_row({"Throughput", std::to_string(1000000.0 / setup_time.count()), "rows/sec"})
.set_column_alignment(1, align::right)
.set_style(box_style::double_);
std::cout << perf_results;
if (render_time.count() < 10000) { // Less than 10ms
log_success("Performance: Excellent");
} else if (render_time.count() < 50000) { // Less than 50ms
log_info("Performance: Good");
} else {
log_warning("Performance: Could be improved");
}
std::cout << '\n';
}
void interactive_demo() {
utils::print_banner("Interactive Demo", "User input and prompts");
std::cout << color::bold("This section demonstrates interactive features:") << '\n';
std::cout << color::italic("(You can skip by pressing Enter for defaults)") << '\n';
std::cout << '\n';
// Basic input
std::string name = ask_input("What's your name?", "Anonymous");
log_info("Hello, " + color::bold(name) + "!");
// Confirmation
bool likes_demo = ask_yes_no("Are you enjoying this demo?", true);
if (likes_demo) {
log_success("Great! Thanks for trying TUIX!");
} else {
log_info("Thanks for the feedback. We'll keep improving!");
}
// Multiple choice
std::vector<std::string> favorite_features = {
"Colorful text formatting",
"Beautiful tables",
"Progress bars and spinners",
"Box layouts",
"All of the above!"
};
std::cout << '\n';
int choice = prompt::select("What's your favorite TUIX feature?", favorite_features);
log_info("You selected: " + color::cyan(favorite_features[choice]));
// Generate a personalized summary
box summary("Thank you, " + color::bold(name) + "!\n\n" +
"Your favorite feature: " + color::cyan(favorite_features[choice]) + "\n" +
"Demo enjoyment: " + (likes_demo ? color::green("Yes") : color::yellow("Neutral")) + "\n\n" +
"Thanks for trying the TUIX library!");
summary.set_style(box_style::rounded).set_title("Summary").set_alignment(align::center);
std::cout << summary;
std::cout << '\n';
}
void showcase_advanced_features() {
utils::print_banner("Advanced Features", "Terminal control and utilities");
// 1. Terminal utilities
std::cout << color::bold("1. Terminal Information:") << '\n';
auto [width, height] = terminal::get_size();
table term_info;
term_info.set_headers({"Property", "Value"})
.add_row({"Terminal Width", std::to_string(width) + " columns"})
.add_row({"Terminal Height", std::to_string(height) + " rows"})
.add_row({"Color Support", color::formatter::is_enabled() ? "Yes" : "No"})
.add_row({"Library Version", "1.0.0"})
.set_column_alignment(1, align::right);
std::cout << term_info;
// 2. Text wrapping
std::cout << color::bold("\n2. Text Wrapping:") << '\n';
std::string long_text = "This is a very long piece of text that demonstrates the text wrapping functionality. "
"It should automatically break into multiple lines when the specified width is exceeded. "
"This is useful for formatting long descriptions or content that needs to fit within "
"specific column widths or display constraints.";
box wrapped_box(utils::wrap_text(long_text, 50));
wrapped_box.set_title("Wrapped Text").set_style(box_style::single);
std::cout << wrapped_box;
// 3. Cursor positioning demo
std::cout << color::bold("3. Cursor Control:") << '\n';
std::cout << "Watch the cursor move...\n";
terminal::save_cursor();
for (int i = 0; i < 5; ++i) {
terminal::print_at(10 + i * 5, 2, "★");
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
terminal::restore_cursor();
std::cout << "Cursor returned to original position!\n";
std::cout << '\n';
}
void compile_time_features() {
utils::print_banner("Compile-Time Features", "Configuration and optimization");
std::cout << color::bold("Compile-time configuration:") << '\n';
table config_table;
config_table.set_headers({"Feature", "Status", "Description"});
#ifdef TUIX_COLOR_ENABLED
config_table.add_row({"Color Support", color::green("Enabled"), "ANSI colors available"});
#else
config_table.add_row({"Color Support", color::red("Disabled"), "No color output"});
#endif
#ifdef TUIX_INCLUDE_DEMO
config_table.add_row({"Demo Code", color::green("Included"), "Demo functions available"});
#else
config_table.add_row({"Demo Code", color::yellow("Excluded"), "Reduced binary size"});
#endif
config_table.add_row({"Default Width", std::to_string(TUIX_DEFAULT_WIDTH), "Fallback terminal width"})
.add_row({"Header Only", color::green("Yes"), "No compilation needed"})
.add_row({"C++ Standard", "C++17/20", "Modern C++ features"})
.add_row({"Cross Platform", color::green("Yes"), "Linux, Windows, macOS"});
std::cout << config_table;
std::cout << '\n';
}
int main() {
// Initialize the library
std::cout << color::formatter().fg_color(color::fg::bright_blue)
.add_style(color::style::bold)
.format("TUIX - Terminal User Interface eXtensions") << '\n';
std::cout << color::italic("A modern C++ library for beautiful console applications") << '\n';
std::cout << std::string(60, '=') << '\n';
std::cout << '\n';
try {
// Run all demonstrations
basic_examples();
utils::pause();
advanced_formatting();
utils::pause();
interactive_elements();
utils::pause();
logging_demo();
utils::pause();
lists_and_structure();
utils::pause();
markdown_and_themes();
utils::pause();
real_world_examples();
utils::pause();
performance_showcase();
utils::pause();
showcase_advanced_features();
utils::pause();
compile_time_features();
// Interactive section (optional)
std::cout << '\n';
bool run_interactive = ask_yes_no("Run interactive demo?", false);
if (run_interactive) {
interactive_demo();
}
// Final summary
utils::print_banner("Demo Complete!", "Thanks for exploring TUIX");
std::cout << color::bold("Key Features Demonstrated:") << '\n';
print_bullet_list({
"Cross-platform color support",
"Flexible table rendering",
"Beautiful text boxes",
"Progress bars and spinners",
"Structured logging system",
"Interactive prompts",
"Markdown-like formatting",
"Theme support",
"Performance optimization",
"Header-only design"
}, "✓ ");
std::cout << '\n';
std::cout << center(color::green("🎉 Thank you for trying TUIX! 🎉"), 60) << '\n';
std::cout << center(color::italic("Visit GitHub for more examples and documentation"), 60) << '\n';
std::cout << '\n';
} catch (const std::exception& e) {
log_error("Demo failed: " + std::string(e.what()));
return 1;
}
return 0;
}