forked from enkore/j4-dmenu-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cc
1550 lines (1392 loc) · 55.8 KB
/
main.cc
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// j4-dmenu-desktop is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with j4-dmenu-desktop. If not, see <http://www.gnu.org/licenses/>.
//
// See CONTRIBUTING.md for explanation of loglevels.
// v- This is set by the build system globally. -v
// #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <spdlog/common.h>
#include <spdlog/logger.h>
#include <spdlog/sinks/ansicolor_sink.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
#include <algorithm>
#include <cstring>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <map>
#include <memory>
#include <optional>
#include <poll.h>
#include <set>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <type_traits>
#include <unistd.h>
#include <unordered_set>
#include <utility>
#include <variant>
#include <vector>
#include "AppManager.hh"
#include "Application.hh"
#include "CMDLineAssembler.hh"
#include "CMDLineTerm.hh"
#include "Dmenu.hh"
#include "DynamicCompare.hh"
#include "FieldCodes.hh"
#include "FileFinder.hh"
#include "Formatters.hh"
#include "HistoryManager.hh"
#include "I3Exec.hh"
#include "LocaleSuffixes.hh"
#include "NotifyBase.hh"
#include "ParsingQuirks.hh"
#include "SearchPath.hh"
#include "Utilities.hh"
#include "version.hh"
#ifdef USE_KQUEUE
#include "NotifyKqueue.hh"
#else
#include "NotifyInotify.hh"
#endif
#ifdef FIX_COVERAGE
extern "C" void __gcov_dump();
static void sigabrt(int sig) {
__gcov_dump();
raise(sig);
}
#endif
static volatile int sigchld_fd;
// This handler is established only in --wait-on mode when executing desktop
// apps directly (not through i3 IPC).
static void sigchld(int) {
// Zombie reaping is implemented in do_wait_on()
auto saved_errno = errno;
if (write(sigchld_fd, "", 1) == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK)
abort();
}
errno = saved_errno;
}
static int setup_sigchld_signal() {
int pipefd[2];
if (pipe(pipefd) == -1)
PFATALE("pipe");
if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) == -1)
PFATALE("fcntl");
if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) == -1)
PFATALE("fcntl");
if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) == -1)
PFATALE("fcntl");
if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) == -1)
PFATALE("fcntl");
sigchld_fd = pipefd[1];
struct sigaction act;
memset(&act, 0, sizeof act);
act.sa_handler = sigchld;
if (sigaction(SIGCHLD, &act, NULL) == -1)
PFATALE("sigaction");
return pipefd[0];
}
static void print_usage(FILE *f) {
fmt::print(
f,
"j4-dmenu-desktop\n"
"A faster replacement for i3-dmenu-desktop\n"
"Copyright (c) 2013 Marian Beermann, GPLv3 license\n"
"\nUsage:\n"
" j4-dmenu-desktop [--dmenu=\"dmenu -i\"] "
"[--term=\"i3-sensible-terminal\"]\n"
" j4-dmenu-desktop --help\n"
"\nOptions:\n"
" -b, --display-binary\n"
" Display binary name after each entry (off by default)\n"
" -f, --display-binary-base\n"
" Display basename of binary name after each entry (off by "
"default)\n"
" -d, --dmenu=<command>\n"
" Determines the command used to invoke dmenu\n"
" --no-exec\n"
" Do not execute selected command, send to stdout instead\n"
" --no-generic\n"
" Do not include the generic name of desktop entries\n"
" -t, --term=<command>\n"
" Sets the terminal emulator used to start terminal apps\n"
" --term-mode=default | xterm | alacritty | kitty | terminator |\n"
" gnome-terminal | custom\n"
" Instruct j4-dmenu-desktop on how it should execute terminal\n"
" emulator; this also changes the default value of --term.\n"
" See the manpage for more info.\n"
" --usage-log=<file>\n"
" Use file as usage log (enables sorting by usage frequency)\n"
" --prune-bad-usage-log-entries\n"
" Remove names marked in usage log with no corresponding "
"desktop files\n"
" -x, --use-xdg-de\n"
" Enables reading $XDG_CURRENT_DESKTOP to determine the desktop "
"environment\n"
" --wait-on=<path>\n"
" Enable daemon mode\n"
" --wrapper=<wrapper>\n"
" A wrapper binary.\n"
" Usage of '--wrapper \"i3 exec\"' and '--wrapper \"sway "
"exec\"' is deprecated,\n"
" use '--i3-ipc' instead.\n"
" -I, --i3-ipc\n"
" Execute desktop entries through i3 IPC. Requires i3 to be "
"running.\n"
" --skip-i3-exec-check\n"
" Disable the check for '--wrapper \"i3 exec\"'.\n"
" j4-dmenu-desktop has direct support for i3 through the -I "
"flag which should be\n"
" used instead of the --wrapper option. j4-dmenu-desktop "
"detects this and exits.\n"
" This flag overrides this.\n"
" -v\n"
" Be more verbose\n"
" --log-level=ERROR | WARNING | INFO | DEBUG\n"
" Set log level\n"
" --log-file\n"
" Specify a log file\n"
" --log-file-level=ERROR | WARNING | INFO | DEBUG\n"
" Set file log level\n"
" --desktop-file-compatibility=wine,multispace\n"
" Enable nonconformant desktop file parsing quirks. Available "
"modes: wine, multispace.\n"
" --strict-parsing\n"
" Enable strict desktop file parsing. Mutaly exclusive with\n"
" --desktop-file-compatibility.\n"
" --version\n"
" Display program version\n"
" -h, --help\n"
" Display this help message\n\n"
"See the manpage for a more detailed description of the flags.\n"
"j4-dmenu-desktop is compiled with "
#ifdef USE_KQUEUE
"kqueue"
#else
"inotify"
#endif
" support.\n"
#ifdef DEBUG
"DEBUG enabled.\n"
#endif
);
}
/*
* Code here is divided into several phases designated by their namespace.
*/
namespace SetupPhase
{
// This returns absolute paths.
static Desktop_file_list collect_files(const stringlist_t &search_path) {
Desktop_file_list result;
result.reserve(search_path.size());
for (const string &base_path : search_path) {
std::vector<string> found_desktop_files;
FileFinder finder(base_path);
while (++finder) {
if (finder.isdir() || !endswith(finder.path(), ".desktop"))
continue;
found_desktop_files.push_back(finder.path());
}
result.emplace_back(base_path, std::move(found_desktop_files));
}
return result;
}
// This helper function is most likely useless, but I, meator, ran into
// a situation where a directory was specified twice in $XDG_DATA_DIRS.
static void validate_search_path(stringlist_t &search_path) {
std::unordered_set<std::string> is_unique;
auto iter = search_path.begin();
while (iter != search_path.end()) {
const std::string &path = *iter;
if (path.empty())
SPDLOG_WARN("Empty path in $XDG_DATA_DIRS!");
else {
if (path.front() != '/') {
SPDLOG_WARN(
"Relative path '{}' found in $XDG_DATA_DIRS, ignoring...",
path);
iter = search_path.erase(iter);
continue;
}
if (!is_unique.emplace(path).second)
SPDLOG_WARN("$XDG_DATA_DIRS contains duplicate element '{}'!",
path);
}
++iter;
}
}
static unsigned int
count_collected_desktop_files(const Desktop_file_list &files) {
unsigned int result = 0;
for (const Desktop_file_rank &rank : files)
result += rank.files.size();
return result;
}
// This class manager nape -> app mapping used for resolving user response
// received by Dmenu.
class NameToAppMapping
{
public:
using formatted_name_map =
std::map<std::string, const Resolved_application, DynamicCompare>;
using raw_name_map = AppManager::name_app_mapping_type;
NameToAppMapping(application_formatter app_format, bool case_insensitive,
bool exclude_generic)
: app_format(app_format), mapping(DynamicCompare(case_insensitive)),
exclude_generic(exclude_generic) {}
void load(const AppManager &appm) {
SPDLOG_INFO("Received request to load NameToAppMapping, formatting all "
"names...");
this->raw_mapping = appm.view_name_app_mapping();
this->mapping.clear();
for (const auto &[key, resolved] : this->raw_mapping) {
const auto &[ptr, is_generic] = resolved;
if (this->exclude_generic && is_generic)
continue;
std::string formatted = this->app_format(key, *ptr);
SPDLOG_DEBUG("Formatted '{}' -> '{}'", key, formatted);
auto safety_check = this->mapping.try_emplace(std::move(formatted),
ptr, is_generic);
if (!safety_check.second) {
SPDLOG_ERROR("Formatter has created a collision!");
abort();
}
}
}
const formatted_name_map &get_formatted_map() const {
return this->mapping;
}
const raw_name_map &get_unordered_raw_map() const {
return this->raw_mapping;
}
application_formatter view_formatter() const {
return this->app_format;
}
private:
application_formatter app_format;
formatted_name_map mapping;
raw_name_map raw_mapping;
bool exclude_generic;
};
static_assert(std::is_move_constructible_v<NameToAppMapping>);
// HistoryManager can't save formatted names. This class handles conversion of
// raw names to formatted ones.
class FormattedHistoryManager
{
public:
void reload(const NameToAppMapping &mapping) {
const auto &raw_name_lookup = mapping.get_unordered_raw_map();
this->formatted_history.clear();
const auto &hist_view = this->hist.view();
this->formatted_history.reserve(hist_view.size());
const auto &format = mapping.view_formatter();
for (auto iter = hist_view.begin(); iter != hist_view.end(); ++iter) {
const std::string &raw_name = iter->second;
auto lookup_result = raw_name_lookup.find(raw_name);
if (lookup_result == raw_name_lookup.end()) {
if (this->remove_obsolete_entries) {
SPDLOG_WARN(
"Removing history entry '{}', which doesn't correspond "
"to any known desktop app name.",
raw_name);
iter = this->hist.remove_obsolete_entry(iter);
if (iter == hist_view.end())
break;
} else {
SPDLOG_WARN(
"Couldn't find history entry '{}'. Has the program "
"been uninstalled? Has j4-dmenu-desktop been executed "
"with different $XDG_DATA_HOME or $XDG_DATA_DIRS? Use "
"--prune-bad-usage-log-entries "
"to remove these entries.",
raw_name);
}
continue;
}
if (this->exclude_generic && lookup_result->second.is_generic)
continue;
this->formatted_history.push_back(
format(raw_name, *lookup_result->second.app));
}
}
FormattedHistoryManager(HistoryManager hist,
const NameToAppMapping &mapping,
bool remove_obsolete_entries, bool exclude_generic)
: hist(std::move(hist)),
remove_obsolete_entries(remove_obsolete_entries),
exclude_generic(exclude_generic) {
reload(mapping);
}
const stringlist_t &view() const {
#ifdef DEBUG
std::unordered_set<string_view> ensure_uniqueness;
for (const std::string &hist_entry : this->formatted_history) {
if (!ensure_uniqueness.emplace(hist_entry).second) {
SPDLOG_ERROR(
"Error while processing history file '{}': History doesn't "
"contain unique entries! Duplicate entry '{}' is present!",
this->hist.get_filename(), hist_entry);
exit(EXIT_FAILURE);
}
}
#endif
return this->formatted_history;
}
void increment(const string &name) {
this->hist.increment(name);
}
void remove_obsolete_entry(
HistoryManager::history_mmap_type::const_iterator iter) {
this->hist.remove_obsolete_entry(iter);
}
private:
HistoryManager hist;
stringlist_t formatted_history;
bool remove_obsolete_entries;
bool exclude_generic;
};
}; // namespace SetupPhase
// Functions and classes used in the "main" phase of j4dd after setup.
// Most of the functions defined here are used in CommandRetrievalLoop.
namespace RunPhase
{
using name_map = SetupPhase::NameToAppMapping::formatted_name_map;
// This is wrapped in a class to unregister the handler in dtor.
class SIGPIPEHandler
{
private:
struct sigaction oldact, act;
static void sigpipe_handler(int) {
SPDLOG_ERROR(
"A SIGPIPE occurred while communicating with dmenu. Is dmenu "
"installed?");
exit(EXIT_FAILURE);
}
public:
SIGPIPEHandler() {
memset(&this->act, 0, sizeof(struct sigaction));
this->act.sa_handler = sigpipe_handler;
if (sigaction(SIGPIPE, &this->act, &this->oldact) < 0)
PFATALE("sigaction");
}
~SIGPIPEHandler() {
if (sigaction(SIGPIPE, &this->oldact, NULL) < 0)
PFATALE("sigaction");
}
};
static std::optional<std::string>
do_dmenu(Dmenu &dmenu, const name_map &mapping, const stringlist_t &history) {
// Check for dmenu errors via SIGPIPE.
SIGPIPEHandler sig;
// Transfer the names to dmenu
if (!history.empty()) {
std::set<std::string_view, DynamicCompare> desktop_file_names(
mapping.key_comp());
for (const auto &[name, ignored] : mapping)
desktop_file_names.emplace_hint(desktop_file_names.end(), name);
for (const auto &name : history) {
// We don't want to display a single element twice. We can't
// print history and then desktop name list because names in
// history will also be in desktop name list. Also, if there is
// a name in history which isn't in desktop name list, it could
// mean that the desktop file corresponding to the history name
// has been removed, making the history entry obsolete. The
// history entry shouldn't be shown if that is the case.
if (desktop_file_names.erase(name))
dmenu.write(name);
else {
// This shouldn't happen thanks to FormattedHistoryManager
SPDLOG_ERROR(
"A name in history isn't in name list when it should "
"be there!");
abort();
}
}
for (const auto &name : desktop_file_names)
dmenu.write(name);
} else {
for (const auto &[name, ignored] : mapping)
dmenu.write(name);
}
dmenu.display();
string choice = dmenu.read_choice(); // This blocks
if (choice.empty())
return {};
fmt::print(stderr, "User input is: {}\n", choice);
SPDLOG_INFO("User input is: {}", choice);
return choice;
}
namespace Lookup
{
struct ApplicationLookup
{
const Application *app;
bool is_generic;
std::string args;
ApplicationLookup(const Application *a, bool i) : app(a), is_generic(i) {}
ApplicationLookup(const Application *a, bool i, std::string arg)
: app(a), is_generic(i), args(std::move(arg)) {}
};
struct CommandLookup
{
std::string command;
CommandLookup(std::string command) : command(std::move(command)) {}
};
using lookup_res_type = std::variant<ApplicationLookup, CommandLookup>;
// This function takes a query and returns Application*. If the optional is
// empty, there is no desktop file with matching name. J4dd supports executing
// raw commands through dmenu. This is the fallback behavior when there's no
// match.
static lookup_res_type lookup_name(const std::string &query,
const name_map &map) {
auto find = map.find(query);
if (find != map.end())
return ApplicationLookup(find->second.app, find->second.is_generic);
else {
for (const auto &[name, resolved] : map) {
if (startswith(query, name))
return ApplicationLookup(resolved.app, resolved.is_generic,
query.substr(name.size()));
}
return CommandLookup(query);
}
}
}; // namespace Lookup
class CommandRetrievalLoop
{
public:
CommandRetrievalLoop(
Dmenu dmenu, SetupPhase::NameToAppMapping mapping,
std::optional<SetupPhase::FormattedHistoryManager> hist_manager,
bool no_exec)
: dmenu(std::move(dmenu)), mapping(std::move(mapping)),
hist_manager(std::move(hist_manager)), no_exec(no_exec) {}
// This class could be copied or moved, but it wouldn't make much sense in
// current implementation. This prevents accidental copy/move.
CommandRetrievalLoop(const CommandRetrievalLoop &) = delete;
CommandRetrievalLoop(CommandRetrievalLoop &&) = delete;
void operator=(const CommandRetrievalLoop &) = delete;
void operator=(CommandRetrievalLoop &&) = delete;
struct DesktopCommandInfo
{
const Application *app;
std::string args; // Arguments provided to %f, %F, %u and %U field codes
// in desktop files. This will be empty in most cases.
DesktopCommandInfo(const Application *app, std::string args)
: app(app), args(std::move(args)) {}
};
struct CustomCommandInfo
{
std::string raw_command;
CustomCommandInfo(std::string raw_command)
: raw_command(std::move(raw_command)) {}
};
using CommandInfoVariant =
std::variant<DesktopCommandInfo, CustomCommandInfo>;
// This function is separate from prompt_user_for_choice() because it needs
// to be executed at different times when j4dd is executed normally and when
// it is executed in wait-on mode. When executed normally, dmenu.run()
// should be executed as soon as possible. It is executed in main() as part
// of setup. In wait-on mode, it must be executed after each pipe
// invocation. run_dmenu() is used only in wait-on mode in do_wait_on().
void run_dmenu() {
this->dmenu.run();
}
std::optional<CommandInfoVariant> prompt_user_for_choice() {
std::optional<std::string> query =
RunPhase::do_dmenu(this->dmenu, this->mapping.get_formatted_map(),
(this->hist_manager ? this->hist_manager->view()
: stringlist_t{})); // blocks
if (!query) {
SPDLOG_INFO("No application has been selected, exiting...");
return {};
}
using namespace Lookup;
lookup_res_type lookup =
lookup_name(*query, this->mapping.get_formatted_map());
bool is_custom = std::holds_alternative<CommandLookup>(lookup);
if (is_custom)
SPDLOG_DEBUG("Selected entry is: custom command");
else
SPDLOG_DEBUG("Selected entry is: desktop app");
if (is_custom)
return CommandInfoVariant(std::in_place_type_t<CustomCommandInfo>{},
std::get<CommandLookup>(lookup).command);
else {
const ApplicationLookup &appl = std::get<ApplicationLookup>(lookup);
if (!this->no_exec && this->hist_manager) {
const std::string &name =
(appl.is_generic ? appl.app->generic_name : appl.app->name);
this->hist_manager->increment(name);
}
return CommandInfoVariant(
std::in_place_type_t<DesktopCommandInfo>{}, appl.app,
appl.args);
}
}
void update_mapping(const AppManager &appm) {
this->mapping.load(appm);
if (this->hist_manager)
this->hist_manager->reload(this->mapping);
}
private:
Dmenu dmenu;
SetupPhase::NameToAppMapping mapping;
std::optional<SetupPhase::FormattedHistoryManager> hist_manager;
bool no_exec;
};
}; // namespace RunPhase
namespace ExecutePhase
{
[[noreturn]] void execute_app(const stringlist_t &args) {
std::string cmdline_string = CMDLineAssembly::convert_argv_to_string(args);
SPDLOG_INFO("Executing command: {}", cmdline_string);
auto argv = CMDLineAssembly::create_argv(args);
#ifdef FIX_COVERAGE
__gcov_dump();
#endif
execvp(argv.front(), (char *const *)argv.data());
SPDLOG_ERROR("Couldn't execute command: {}", cmdline_string);
// this function can be called either directly, or in a fork used in
// do_wait_on(). Theoretically exit() should be called instead of _exit() in
// the first case, but it isn't that important.
_exit(EXIT_FAILURE);
}
class BaseExecutable
{
public:
virtual void
execute(const RunPhase::CommandRetrievalLoop::CommandInfoVariant &) = 0;
virtual ~BaseExecutable() {}
};
class NormalExecutable final : public BaseExecutable
{
public:
NormalExecutable(std::string terminal, std::string wrapper,
CMDLineTerm::term_assembler term_assembler,
ParsingQuirks quirks)
: terminal(std::move(terminal)), wrapper(std::move(wrapper)),
term_assembler(term_assembler), quirks(quirks) {}
// This class could be copied or moved, but it wouldn't make much sense in
// current implementation. This prevents accidental copy/move.
NormalExecutable(const NormalExecutable &) = delete;
NormalExecutable(NormalExecutable &&) = delete;
void operator=(const NormalExecutable &) = delete;
void operator=(NormalExecutable &&) = delete;
// This is used in both NormalExecutable and in FakeExecutable
static stringlist_t prepare_processed_argv(
const RunPhase::CommandRetrievalLoop::CommandInfoVariant &command_info,
const std::string &wrapper, const std::string &terminal,
CMDLineTerm::term_assembler term_assembler, ParsingQuirks quirks) {
using CMDLineAssembly::invalid_Exec;
std::vector<std::string> command_array;
using CustomCommandInfo =
RunPhase::CommandRetrievalLoop::CustomCommandInfo;
using DesktopCommandInfo =
RunPhase::CommandRetrievalLoop::DesktopCommandInfo;
if (std::holds_alternative<CustomCommandInfo>(command_info)) {
const auto &info = std::get<CustomCommandInfo>(command_info);
command_array =
CMDLineAssembly::wrap_cmdstring_in_shell(info.raw_command);
} else {
const auto &info = std::get<DesktopCommandInfo>(command_info);
try {
command_array = CMDLineAssembly::convert_exec_to_command(
info.app->exec, quirks);
} catch (const invalid_Exec &e) {
throw invalid_Exec(
(std::string) "Error while processing selected desktop "
"file '" +
info.app->location + "': " + e.what());
}
expand_field_codes(command_array, *info.app, info.args);
if (info.app->terminal)
command_array =
term_assembler(command_array, terminal, info.app->name);
}
if (!wrapper.empty())
command_array = CMDLineAssembly::wrap_command_in_wrapper(
command_array, wrapper);
return command_array;
}
void execute(const RunPhase::CommandRetrievalLoop::CommandInfoVariant
&command_info) override {
if (std::holds_alternative<
RunPhase::CommandRetrievalLoop::DesktopCommandInfo>(
command_info)) {
const std::string &path =
std::get<RunPhase::CommandRetrievalLoop::DesktopCommandInfo>(
command_info)
.app->path;
if (!path.empty()) {
if (chdir(path.c_str()) == -1) {
SPDLOG_ERROR("Couldn't chdir() to '{}' set in Path key: {}",
path, strerror(errno));
exit(EXIT_FAILURE);
}
}
}
execute_app(prepare_processed_argv(command_info, this->wrapper,
this->terminal, this->term_assembler,
this->quirks));
abort();
}
private:
std::string terminal;
std::string wrapper; // empty when no wrapper is in use
CMDLineTerm::term_assembler term_assembler;
ParsingQuirks quirks;
};
// This "executable" is used to handle --no-exec
class FakeExecutable final : public BaseExecutable
{
public:
FakeExecutable(std::string terminal, std::string wrapper,
CMDLineTerm::term_assembler term_assembler,
ParsingQuirks quirks)
: terminal(std::move(terminal)), wrapper(std::move(wrapper)),
term_assembler(term_assembler), quirks(quirks) {}
// This class could be copied or moved, but it wouldn't make much sense in
// current implementation. This prevents accidental copy/move.
FakeExecutable(const FakeExecutable &) = delete;
FakeExecutable(FakeExecutable &&) = delete;
void operator=(const FakeExecutable &) = delete;
void operator=(FakeExecutable &&) = delete;
void execute(const RunPhase::CommandRetrievalLoop::CommandInfoVariant
&command_info) override {
auto argv = NormalExecutable::prepare_processed_argv(
command_info, this->wrapper, this->terminal, this->term_assembler,
this->quirks);
std::string command_string =
CMDLineAssembly::convert_argv_to_string(argv);
fmt::print("{}\n", command_string);
}
private:
std::string terminal;
std::string wrapper; // empty when no wrapper is in use
CMDLineTerm::term_assembler term_assembler;
ParsingQuirks quirks;
};
class I3Executable final : public BaseExecutable
{
public:
I3Executable(std::string terminal, std::string i3_ipc_path,
CMDLineTerm::term_assembler term_assembler,
ParsingQuirks quirks)
: terminal(std::move(terminal)), i3_ipc_path(std::move(i3_ipc_path)),
term_assembler(term_assembler), quirks(quirks) {}
// This class could be copied or moved, but it wouldn't make much sense in
// current implementation. This prevents accidental copy/move.
I3Executable(const I3Executable &) = delete;
I3Executable(I3Executable &&) = delete;
void operator=(const I3Executable &) = delete;
void operator=(I3Executable &&) = delete;
void execute(const RunPhase::CommandRetrievalLoop::CommandInfoVariant
&command_info) override {
std::string result;
using CustomCommandInfo =
RunPhase::CommandRetrievalLoop::CustomCommandInfo;
using DesktopCommandInfo =
RunPhase::CommandRetrievalLoop::DesktopCommandInfo;
using CMDLineAssembly::invalid_Exec;
if (std::holds_alternative<CustomCommandInfo>(command_info)) {
const auto &info = std::get<CustomCommandInfo>(command_info);
// command is already wrapped in i3's shell.
result = info.raw_command;
} else {
const auto &info = std::get<DesktopCommandInfo>(command_info);
std::vector<std::string> command_array;
try {
command_array = CMDLineAssembly::convert_exec_to_command(
info.app->exec, this->quirks);
} catch (const invalid_Exec &e) {
throw invalid_Exec(
(std::string) "Error while processing selected desktop "
"file '" +
info.app->location + "': " + e.what());
}
expand_field_codes(command_array, *info.app, info.args);
if (!info.app->path.empty()) {
result = "cd " + CMDLineAssembly::sq_quote(info.app->path) +
" && " +
CMDLineAssembly::convert_argv_to_string(command_array);
if (info.app->terminal) {
std::vector<std::string> new_command_array =
CMDLineAssembly::wrap_cmdstring_in_shell(result);
new_command_array = this->term_assembler(
new_command_array, this->terminal, info.app->name);
result = CMDLineAssembly::convert_argv_to_string(
new_command_array);
}
} else {
if (info.app->terminal) {
std::vector<std::string> new_command_array =
this->term_assembler(command_array, this->terminal,
info.app->name);
result = CMDLineAssembly::convert_argv_to_string(
new_command_array);
} else
result =
CMDLineAssembly::convert_argv_to_string(command_array);
}
}
// wrapper and i3 mode are mutally exclusive, no need to handle it here.
/*
if (!this->wrapper.empty())
...
*/
I3Interface::exec(result, this->i3_ipc_path);
}
private:
std::string terminal;
std::string i3_ipc_path;
CMDLineTerm::term_assembler term_assembler;
ParsingQuirks quirks;
};
}; // namespace ExecutePhase
[[noreturn]] static void
do_wait_on(NotifyBase ¬ify, const char *wait_on, AppManager &appm,
const stringlist_t &search_path,
RunPhase::CommandRetrievalLoop &command_retrieve,
ExecutePhase::BaseExecutable *executor) {
// We need to determine if we're i3 to know if we need to fork before
// executing a program.
bool is_i3 =
dynamic_cast<ExecutePhase::NormalExecutable *>(executor) == nullptr;
int local_sigchld_fd = -1;
// Avoid zombie processes.
if (!is_i3)
local_sigchld_fd = setup_sigchld_signal();
std::vector<pid_t> processes_to_wait_for;
int fd;
if (mkfifo(wait_on, 0600) && errno != EEXIST)
PFATALE("mkfifo");
fd = open(wait_on, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd == -1)
PFATALE("open");
pollfd watch[] = {
{fd, POLLIN, 0},
{notify.getfd(), POLLIN, 0},
{local_sigchld_fd, POLLIN, 0}
};
// Do not process the third entry when in i3 mode
// i3 mode doesn't exec nor fork, so the entire SIGCHLD handling mechanism
// is turned off for it. The signal handler is not established and poll
// disregards it because of nfds (local_sigchld_fd is also set to -1, so
// poll() would have ignored it anyway).
int nfds = is_i3 ? 2 : 3;
while (1) {
watch[0].revents = watch[1].revents = watch[2].revents = 0;
int ret;
while ((ret = poll(watch, nfds, -1)) == -1 && errno == EINTR)
;
if (ret == -1)
PFATALE("poll");
if (watch[1].revents & POLLIN) {
for (const auto &i : notify.getchanges()) {
if (!endswith(i.name, ".desktop"))
continue;
switch (i.status) {
case NotifyBase::changetype::modified:
appm.add(search_path[i.rank] + i.name, search_path[i.rank],
i.rank);
break;
case NotifyBase::changetype::deleted:
appm.remove(search_path[i.rank] + i.name,
search_path[i.rank]);
break;
default:
// Shouldn't be reachable.
abort();
}
command_retrieve.update_mapping(appm);
#ifdef DEBUG
appm.check_inner_state();
#endif
}
}
if (watch[0].revents & POLLIN) {
// It can happen that the user tries to execute j4dd several times
// but has forgot to start j4dd. They then run it in wait on mode
// and then j4dd would be invoked several times because the FIFO has
// a bunch of events piled up. This nonblocking read() loop prevents
// this.
char data;
ssize_t err = read(fd, &data, sizeof(data));
bool nothing_received = false;
if (err > 0) {
while ((err = read(fd, &data, sizeof(data))) == 1)
continue;
} else if (err == 0)
nothing_received = true;
if (err == -1 && errno != EAGAIN)
PFATALE("read");
if (err == 0) {
// EOF was reached, fd is useless now.
close(fd);
fd = open(wait_on, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd == -1)
PFATALE("open");
watch[0].fd = fd;
watch[0].revents = 0;
if (nothing_received)
continue;
}
// Only the last event is taken into account (there is usually only
// a single event).
if (data == 'q')
exit(EXIT_SUCCESS);
command_retrieve.run_dmenu();
auto user_response = command_retrieve.prompt_user_for_choice();
if (user_response) {
if (is_i3)
executor->execute(*user_response);
else {
pid_t pid = fork();
switch (pid) {
case -1:
perror("fork");
exit(EXIT_FAILURE);
case 0:
close(fd);
setsid();
// This function can throw. It means that the child
// process can jump out to main.
executor->execute(*user_response);
abort();
}
processes_to_wait_for.push_back(pid);
}
}
}
if (watch[0].revents & POLLHUP) {
// The writing client has closed. We won't be able to poll()
// properly until POLLHUP is cleared. This happens when a) someone