-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
620 lines (529 loc) · 20.7 KB
/
Copy pathmain.cpp
File metadata and controls
620 lines (529 loc) · 20.7 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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
* Copyright 2025 Toni500git
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <dlfcn.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <string>
#include <thread>
#include <vector>
#include "core-modules.hh"
#include "display.hpp"
#include "fmt/base.h"
#include "fmt/ranges.h"
#include "getopt_port/getopt.h"
#include "gui.hpp"
#include "libcufetch/fmt/compile.h"
#include "platform.hpp"
#include "switch_fnv1a.hpp"
#include "texts.hpp"
#include "util.hpp"
#if (!__has_include("version.h"))
#error "version.h not found, please generate it with ./scripts/generateVersion.sh"
#else
#include "version.h"
#endif
// clang-format off
// https://cfengine.com/blog/2021/optional-arguments-with-getopt-long/
// because "--opt-arg arg" won't work
// but "--opt-arg=arg" will
#define OPTIONAL_ARGUMENT_IS_PRESENT \
((optarg == NULL && optind < argc && argv[optind][0] != '-') \
? (bool) (optarg = argv[optind++]) \
: (optarg != NULL))
// clang-format on
using namespace std::string_view_literals;
bool display_modules = false;
bool display_list_logos = false;
struct termios orig_termios;
static void disable_raw_mode()
{
tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios);
}
static void enable_raw_mode()
{
tcgetattr(STDIN_FILENO, &orig_termios);
atexit(disable_raw_mode);
struct termios raw = orig_termios;
raw.c_lflag &= ~(ECHO | ICANON); // Disable echo and canonical mode
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
}
static int kbhit()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
return select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0;
}
// Print the version and some other infos, then exit successfully
static void version()
{
std::string version{ fmt::format(
"customfetch {} built from branch '{}' at {} commit '{}' ({}).\n"
"Date: {}\n"
"Tag: {}",
VERSION, GIT_BRANCH, GIT_DIRTY, GIT_COMMIT_HASH, GIT_COMMIT_MESSAGE, GIT_COMMIT_DATE, GIT_TAG) };
#if !(USE_DCONF)
version += "\n\nNO flags were set\n";
#else
version += "\n\nset flags:\n";
#if USE_DCONF
version += "USE_DCONF\n";
#endif
#endif
fmt::print("{}", version);
fmt::print("\n");
// if only everyone would not return error when querying the program version :(
std::exit(EXIT_SUCCESS);
}
// Print the args help menu, then exit with code depending if it's from invalid or -h arg
static void help(bool invalid_opt = false)
{
fmt::print(FMT_COMPILE("{}"), customfetch_help);
fmt::print("\n");
std::exit(invalid_opt);
}
// Print how customfetch works, then exit successfully
static void explain_how_this_works()
{
fmt::print(FMT_COMPILE("{}"), explain_customfetch);
fmt::print("\n");
std::exit(EXIT_SUCCESS);
}
// Print a modules list of ascii logos you can use at a "data-dir"
// @param data_dir The data directory
static void list_logos(const std::string& data_dir)
{
debug("data-dir = {}", data_dir);
if (access(data_dir.c_str(), F_OK) != 0)
die("failed to access data directory '{}'", data_dir);
std::vector<std::string> list;
for (const auto& logo : std::filesystem::directory_iterator{ data_dir })
{
if (logo.is_regular_file())
list.push_back(logo.path().stem());
}
std::sort(list.begin(), list.end());
fmt::print("{}", fmt::join(list, "\n"));
fmt::print("\n");
}
// Print all info modules you can put in $<>, then exit successfully
static void modules_list()
{
fmt::print("{}", R"(===============================================================================================
| Syntax: |
| when "[NO QUERY]" is present, it means you should call only the children modules (if any) |
| |
| module - Root module description [NO QUERY] |
| foo - Submodule with no children description |
| subfoo - Submodule with children description |
| subbar - Submodule children of "subfoo" |
===============================================================================================
)");
for (const module_t& module : cfGetModules())
{
std::vector<std::string> parts;
// Split name into parts (e.g., "os.name.pretty" -> ["os", "name", "pretty"])
size_t start = 0, end = module.name.find('.');
bool new_module = true;
while (end != std::string::npos)
{
new_module = false;
parts.push_back(module.name.substr(start, end - start));
start = end + 1;
end = module.name.find('.', start);
}
parts.push_back(module.name.substr(start));
if (new_module)
fmt::print("\n");
// Generate indentation
for (size_t depth = 0; depth < parts.size(); ++depth)
{
if (depth == parts.size() - 1)
{
if (new_module)
fmt::print("{} - {}", parts[depth], module.description);
else
fmt::print("{:<6} \t- {}", parts[depth], module.description);
if (!module.handler)
fmt::print(" [NO QUERY]");
}
else
{
fmt::print(" ");
}
}
fmt::print("\n");
}
}
// clang-format off
// Return true if optarg says something true
static bool str_to_bool(const std::string_view str)
{
return (str == "true" || str == "1" || str == "enable");
}
// parseargs() but only for parsing the user config path trough args
// and so we can directly construct Config
static std::filesystem::path parse_config_path(int argc, char* argv[], const std::filesystem::path &configDir)
{
int opt = 0;
int option_index = 0;
opterr = 0;
const char *optstring = "-C:";
static const struct option opts[] = {
{"config", required_argument, 0, 'C'},
{0,0,0,0}
};
while ((opt = getopt_long(argc, argv, optstring, opts, &option_index)) != -1)
{
switch (opt)
{
// skip errors or anything else
case 0:
case '?':
break;
case 'C':
if (!std::filesystem::exists(optarg))
die(_("config file '{}' doesn't exist"), optarg);
return optarg;
}
}
return configDir / "config.toml";
}
static bool parseargs(int argc, char* argv[], Config& config, const std::filesystem::path& configFile)
{
int opt = 0;
int option_index = 0;
opterr = 1; // re-enable since before we disabled for "invalid option" error
const char *optstring = "-VhwnLlNa:f:o:C:O:i:d:D:p:s:m:";
static const struct option opts[] = {
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"list-modules", no_argument, 0, 'l'},
{"how-it-works", no_argument, 0, 'w'},
{"logo-only", no_argument, 0, 'L'},
{"no-logo", no_argument, 0, 'n'},
{"no-color", no_argument, 0, 'N'},
{"ascii-logo-type", required_argument, 0, 'a'},
{"offset", required_argument, 0, 'o'},
{"override", required_argument, 0, 'O'},
{"font", required_argument, 0, 'f'},
{"config", required_argument, 0, 'C'},
{"layout-line", required_argument, 0, 'm'},
{"logo-position", required_argument, 0, 'p'},
{"data-dir", required_argument, 0, 'D'},
{"distro", required_argument, 0, 'd'},
{"source-path", required_argument, 0, 's'},
{"image-backend", required_argument, 0, 'i'},
{"list-logos", no_argument, 0, "list-logos"_fnv1a16},
{"disallow-command-tag", no_argument, 0, "disallow-command-tag"_fnv1a16},
{"sep-reset-after", optional_argument, 0, "sep-reset-after"_fnv1a16},
{"debug", optional_argument, 0, "debug"_fnv1a16},
{"wrap-lines", optional_argument, 0, "wrap-lines"_fnv1a16},
{"gen-config", optional_argument, 0, "gen-config"_fnv1a16},
{"sep-reset", required_argument, 0, "sep-reset"_fnv1a16},
{"title-sep", required_argument, 0, "title-sep"_fnv1a16},
{"logo-padding-top", required_argument, 0, "logo-padding-top"_fnv1a16},
{"logo-padding-left", required_argument, 0, "logo-padding-left"_fnv1a16},
{"layout-padding-top", required_argument, 0, "layout-padding-top"_fnv1a16},
{"gtk-css", required_argument, 0, "gtk-css"_fnv1a16},
{"loop-ms", required_argument, 0, "loop-ms"_fnv1a16},
{"bg-image", required_argument, 0, "bg-image"_fnv1a16},
{"color", required_argument, 0, "color"_fnv1a16},
{0,0,0,0}
};
/* parse operation */
optind = 1;
while ((opt = getopt_long(argc, argv, optstring, opts, &option_index)) != -1)
{
switch (opt)
{
case 0:
break;
case '?':
help(EXIT_FAILURE); break;
case 'V':
version(); break;
case 'h':
help(); break;
case 'l':
display_modules = true; break;
case 'w':
explain_how_this_works(); break;
case "list-logos"_fnv1a16:
display_list_logos = true; break;
case 'f':
config.overrideOption("gui.font", optarg); break;
case 'o':
config.overrideOption("config.offset", optarg); break;
case 'C': // we have already did it in parse_config_path()
break;
case 'D':
config.overrideOption("config.data-dir", optarg); break;
case 'd':
config.args_custom_distro = str_tolower(optarg); break;
case 'm':
config.args_layout.push_back(optarg); break;
case 'p':
config.overrideOption("config.logo-position", optarg); break;
case 's':
config.overrideOption("config.source-path", optarg); break;
case 'i':
config.args_image_backend = optarg; break;
case 'O':
config.overrideOption(optarg); break;
case 'N':
config.args_disable_colors = true; break;
case 'a':
config.overrideOption("config.ascii-logo-type", optarg); break;
case 'n':
config.args_disable_source = true; break;
case 'L':
config.args_print_logo_only = true; break;
case "disallow-command-tag"_fnv1a16:
config.args_disallow_commands = true; break;
case "logo-padding-top"_fnv1a16:
config.overrideOption("config.logo-padding-top", std::stoi(optarg)); break;
case "logo-padding-left"_fnv1a16:
config.overrideOption("config.logo-padding-left", std::stoi(optarg)); break;
case "layout-padding-top"_fnv1a16:
config.overrideOption("config.layout-padding-top", std::stoi(optarg)); break;
case "loop-ms"_fnv1a16:
config.loop_ms = std::stoul(optarg); break;
case "color"_fnv1a16:
config.addAliasColors(optarg); break;
case "sep-reset"_fnv1a16:
config.overrideOption("config.sep-reset", optarg); break;
case "title-sep"_fnv1a16:
config.overrideOption("config.title-sep", optarg); break;
case "bg-image"_fnv1a16:
config.overrideOption("gui.bg-image", optarg); break;
case "gtk-css"_fnv1a16:
config.overrideOption("gui.gtk-css", optarg); break;
case "wrap-lines"_fnv1a16:
if (OPTIONAL_ARGUMENT_IS_PRESENT)
config.overrideOption("config.wrap-lines", str_to_bool(optarg));
else
config.overrideOption("config.wrap-lines", true);
break;
case "debug"_fnv1a16:
if (OPTIONAL_ARGUMENT_IS_PRESENT)
debug_print = str_to_bool(optarg);
else
debug_print = true;
break;
case "gen-config"_fnv1a16:
if (OPTIONAL_ARGUMENT_IS_PRESENT)
config.generateConfig(optarg);
else
config.generateConfig(configFile);
exit(EXIT_SUCCESS);
case "sep-reset-after"_fnv1a16:
if (OPTIONAL_ARGUMENT_IS_PRESENT)
config.overrideOption("config.sep-reset-after", str_to_bool(optarg));
else
config.overrideOption("config.sep-reset-after", true);
break;
default:
return false;
}
}
config.overrideOption("intern.args.print-logo-only", config.args_print_logo_only);
config.overrideOption("intern.args.disable-logo", config.args_disable_source);
config.overrideOption("intern.args.disallow-commands", config.args_disallow_commands);
config.overrideOption("intern.args.custom-distro", config.args_custom_distro);
config.overrideOption("intern.args.image-backend", config.args_image_backend);
config.overrideOption("intern.args.disable-colors", config.args_disable_colors);
return true;
}
static void enable_cursor()
{
fmt::print("\x1B[?25h\x1B[?7h");
}
/** Sets up gettext localization. Safe to call multiple times.
*/
/* Inspired by the monotone function localize_monotone. */
// taken from pacman
static void localize(void)
{
#if ENABLE_NLS && !CF_MACOS
static bool init = false;
if (!init)
{
setlocale(LC_ALL, "");
bindtextdomain("customfetch", LOCALEDIR);
textdomain("customfetch");
init = true;
}
#endif
}
// clang-format on
int main(int argc, char* argv[])
{
const std::filesystem::path& configDir = getConfigDir();
const std::filesystem::path& configFile = parse_config_path(argc, argv, configDir);
localize();
Config config(configFile, configDir);
if (!parseargs(argc, argv, config, configFile))
return 1;
config.loadConfigFile(configFile);
std::vector<void*> plugins_handle;
const std::filesystem::path pluginDir = configDir / "plugins";
std::filesystem::create_directories(pluginDir);
for (const auto& entry : std::filesystem::recursive_directory_iterator{ pluginDir })
{
if (entry.is_regular_file() && entry.path().has_extension() && entry.path().extension() == LIBRARY_EXTENSION){}
else {continue;}
debug("loading plugin at {}!", entry.path().string());
void* handle = LOAD_LIBRARY(std::filesystem::absolute(entry.path()).c_str());
if (!handle)
{
// dlerror() is pretty formatted
warn("Failed to load plugin at '{}': {}", entry.path().string(), dlerror());
dlerror();
continue;
}
LOAD_LIB_SYMBOL(handle, void, start, void*, const ConfigBase&);
if (dlerror())
{
warn("Failed to load plugin at '{}': Missing function 'start'", entry.path().string());
dlclose(handle);
continue;
}
start(handle, config);
plugins_handle.push_back(handle);
}
// The "conflicting" modules won't be overwritten by the main ones.
// First the external modules, then the core ones.
core_plugins_start(config);
if (display_modules)
{
modules_list();
return 0;
}
else if (display_list_logos)
{
list_logos(config.data_dir + "/ascii");
return 0;
}
const std::vector<module_t>& modules = cfGetModules();
moduleMap_t moduleMap;
debug("modules count: {}", modules.size());
for (const module_t& module : modules)
{
debug("adding module {} (has handler: {})", module.name, module.handler != NULL);
if (!module.handler)
continue;
moduleMap.emplace(module.name, module);
}
is_live_mode = (config.loop_ms >= 200);
if (config.source_path.empty() || config.source_path == "off")
config.args_disable_source = true;
config.m_display_distro = (config.source_path == "os");
std::string path = config.m_display_distro ? Display::detect_distro(config) : config.source_path;
if (!config.ascii_logo_type.empty() && config.m_display_distro)
{
std::string logo_type_path{ path };
const size_t pos = path.rfind('.');
if (pos != std::string::npos)
logo_type_path.insert(pos, "_" + config.ascii_logo_type);
else
logo_type_path += "_" + config.ascii_logo_type;
if (std::filesystem::exists(logo_type_path))
path = logo_type_path;
}
debug("{} path = {}", __PRETTY_FUNCTION__, path);
if (!std::filesystem::exists(path) && !config.args_disable_source)
{
path = std::filesystem::temp_directory_path() / "customfetch_ascii_logo-XXXXXX";
Display::ascii_logo_fd = mkstemp(path.data());
if (Display::ascii_logo_fd < 0)
die("Failed to create temp path at {}: {}", path, strerror(errno));
write(Display::ascii_logo_fd, ascii_logo.data(), ascii_logo.size());
}
#if GUI_APP
const auto& app = Gtk::Application::create("org.toni.customfetch");
GUI::Window window(config, path, moduleMap);
return app->run(window);
#endif // GUI_APP
if (!config.wrap_lines)
{
// https://en.cppreference.com/w/c/program/exit
std::atexit(enable_cursor);
// hide cursor and disable line wrapping
fmt::print("\x1B[?25l\x1B[?7l");
}
if (is_live_mode)
{
enable_raw_mode();
const std::chrono::milliseconds sleep_ms{ config.loop_ms };
while (true)
{
if (kbhit())
{
char c;
read(STDIN_FILENO, &c, 1);
if (c == 'q' || c == 'Q')
{
info("exiting...\n");
disable_raw_mode();
break;
}
}
// clear screen and go to position 0, 0
write(STDOUT_FILENO, "\33[H\33[2J", 7);
fmt::print("\033[0;0H");
Display::display(Display::render(config, false, path, moduleMap));
std::this_thread::sleep_for(sleep_ms);
}
}
else
{
Display::display(Display::render(config, false, path, moduleMap));
}
// enable both of them again
if (!config.wrap_lines)
enable_cursor();
core_plugins_finish();
for (void* handle : plugins_handle)
{
LOAD_LIB_SYMBOL(handle, void, finish, void*);
if (dlerror())
{
dlclose(handle);
continue;
}
finish(handle);
UNLOAD_LIBRARY(handle);
}
plugins_handle.clear();
return 0;
}