1 /* GTK-based dmenu
2  * Copyright (c) 2021 Piotr Miller
3  * e-mail: nwg.piotr@gmail.com
4  * Website: http://nwg.pl
5  * Project: https://github.com/nwg-piotr/nwg-launchers
6  * License: GPL3
7  * */
8 
9 #include <algorithm>
10 #include <iostream>
11 #include <fstream>
12 
13 #include "filesystem-compat.h"
14 #include "nwg_tools.h"
15 #include "dmenu.h"
16 
17 /*
18  * Returns settings cache file path
19  * */
get_settings_path()20 fs::path get_settings_path() {
21     auto full_path = get_cache_home();
22     full_path /= "nwg-dmenu-case";
23     return full_path;
24 }
25 
26 /*
27  * Returns all commands paths
28  * */
list_commands()29 static std::vector<Glib::ustring> list_commands() {
30     std::vector<Glib::ustring> commands;
31     if (auto command_dirs_ = getenv("PATH")) {
32         std::string command_dirs{ command_dirs_ };
33         auto paths = split_string(command_dirs, ":");
34         std::error_code ec;
35         for (auto && dir: paths) {
36             if (fs::is_directory(dir, ec) && !ec) {
37                 for (auto && entry: fs::directory_iterator(dir)) {
38                     auto cmd = take_last_by(entry.path().native(), "/");
39                     if (cmd.size() > 1 && cmd[0] != '.') {
40                         commands.emplace_back(cmd.data(), cmd.size());
41                     }
42                 }
43             }
44         }
45     }
46     return commands;
47 }
48 
49 /*
50  * Returns list of commands loaded according to config
51  * */
get_commands_list(const DmenuConfig & config)52 std::vector<Glib::ustring> get_commands_list(const DmenuConfig& config) {
53     std::vector<Glib::ustring> all_commands;
54     if (config.dmenu_run) {
55         /* get a list of paths to all commands from all application dirs */
56         all_commands = list_commands();
57         Log::info(all_commands.size(), " commands found");
58 
59         /* Sort case insensitive */
60         std::sort(all_commands.begin(), all_commands.end(), [](auto& a, auto& b) {
61             return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](auto a, auto b) {
62                 return std::tolower(a) < std::tolower(b);
63             });
64         });
65     } else {
66         for (std::string line; std::getline(std::cin, line);) {
67             all_commands.emplace_back(std::move(line));
68         }
69     }
70     return all_commands;
71 }
72