Debian Codegraph @

i3-dmenu-desktop

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env perl
2 # vim:ts=4:sw=4:expandtab
3 #
4 # © 2012 Michael Stapelberg
5 #
6 # No dependencies except for perl ≥ v5.10
7
8 use strict;
9 use warnings qw(FATAL utf8);
10 use Data::Dumper;
11 use IPC::Open2;
12 use POSIX qw(locale_h);
13 use File::Find;
14 use File::Basename qw(basename);
15 use File::Temp qw(tempfile);
16 use List::Util 'first';
17 use Getopt::Long;
18 use Pod::Usage;
19 use v5.10;
20 use utf8;
21 use open ':encoding(UTF-8)';
22
23 binmode STDOUT, ':utf8';
24 binmode STDERR, ':utf8';
25
26 # reads in a whole file
27 sub slurp {
28 my ($filename) = @_;
29 my $fh;
30 if (!open($fh, '<', $filename)) {
31 warn "Could not open $filename: $!";
32 return undef;
33 }
34 local $/;
35 my $result;
36 eval {
37 $result = <$fh>;
38 };
39 if ($@) {
40 warn "Could not read $filename: $@";
41 return undef;
42 } else {
43 return $result;
44 }
45 }
46
47 my @entry_types;
48 my $dmenu_cmd = 'dmenu -i';
49 my $show_duplicates;
50 my $result = GetOptions(
51 'dmenu=s' => \$dmenu_cmd,
52 'entry-type=s' => \@entry_types,
53 'show-duplicates' => \$show_duplicates,
54 'version' => sub {
55 say "dmenu-desktop 1.5 © 2012 Michael Stapelberg";
56 exit 0;
57 },
58 'help' => sub {
59 pod2usage(-exitval => 0);
60 });
61
62 die "Could not parse command line options" unless $result;
63
64 # Filter entry types and set default type(s) if none selected
65 my $valid_types = {
66 name => 1,
67 command => 1,
68 filename => 1,
69 };
70 @entry_types = grep { exists($valid_types->{$_}) } @entry_types;
71 @entry_types = ('name', 'command') unless @entry_types;
72
73 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
74 # ┃ Convert LC_MESSAGES into an ordered list of suffixes to search for in the ┃
75 # ┃ .desktop files (e.g. “Name[de_DE@euro]” for LC_MESSAGES=de_DE.UTF-8@euro ┃
76 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
77
78 # For details on how the transformation of LC_MESSAGES to a list of keys that
79 # should be looked up works, refer to “Localized values for keys” of the
80 # “Desktop Entry Specification”:
81 # https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s04.html
82 my $lc_messages = setlocale(LC_MESSAGES);
83
84 # Ignore the encoding (e.g. .UTF-8)
85 $lc_messages =~ s/\.[^@]+//g;
86
87 my @suffixes = ($lc_messages);
88
89 # _COUNTRY and @MODIFIER are present
90 if ($lc_messages =~ /_[^@]+@/) {
91 my $no_modifier = $lc_messages;
92 $no_modifier =~ s/@.*//g;
93 push @suffixes, $no_modifier;
94
95 my $no_country = $lc_messages;
96 $no_country =~ s/_[^@]+//g;
97 push @suffixes, $no_country;
98 }
99
100 # Strip _COUNTRY and @MODIFIER if present
101 $lc_messages =~ s/[_@].*//g;
102 push @suffixes, $lc_messages;
103
104 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
105 # ┃ Read all .desktop files and store the values in which we are interested. ┃
106 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
107
108 my %desktops;
109 # See https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
110 my $xdg_data_home = $ENV{XDG_DATA_HOME};
111 $xdg_data_home = $ENV{HOME} . '/.local/share' if
112 !defined($xdg_data_home) ||
113 $xdg_data_home eq '' ||
114 ! -d $xdg_data_home;
115
116 my $xdg_data_dirs = $ENV{XDG_DATA_DIRS};
117 $xdg_data_dirs = '/usr/local/share/:/usr/share/' if
118 !defined($xdg_data_dirs) ||
119 $xdg_data_dirs eq '';
120
121 my @searchdirs = ("$xdg_data_home/applications/");
122 for my $dir (split(':', $xdg_data_dirs)) {
123 push @searchdirs, "$dir/applications/";
124 }
125
126 # Cleanup the paths, maybe some application does not cope with double slashes
127 # (the field code %k is replaced with the .desktop file location).
128 @searchdirs = map { s,//,/,g; $_ } @searchdirs;
129 # Also remove any trailing slashes.
130 @searchdirs = map { s,/*$,,g; $_ } @searchdirs;
131
132 # To avoid errors by File::Find’s find(), only pass existing directories.
133 @searchdirs = grep { -d $_ } @searchdirs;
134
135 find(
136 {
137 wanted => sub {
138 return unless substr($_, -1 * length('.desktop')) eq '.desktop';
139 my $relative = $File::Find::name;
140
141 # Find and then replace the directory in @searchdirs in which the
142 # current file is located. We used to do this with
143 # $File::Find::topdir but it is not supported when using the
144 # 'follow' or 'follow_fast' options.
145 # See #3973, #4031.
146 my $topdir = first { substr($relative, 0, length($_)) eq $_ } @searchdirs;
147
148 # + 1 for the trailing /, which is missing in $topdir.
149 substr($relative, 0, length($topdir) + 1) = '';
150
151 # Don’t overwrite files with the same relative path, we search in
152 # descending order of importance.
153 return if exists($desktops{$relative});
154
155 $desktops{$relative} = $File::Find::name;
156 },
157 no_chdir => 1,
158 follow_fast => 1,
159 # Ignore any duplicate files and directories and proceed normally:
160 follow_skip => 2,
161 },
162 @searchdirs
163 );
164
165 my %apps;
166
167 for my $file (values %desktops) {
168 my $base = basename($file);
169
170 # _ is an invalid character for a key, so we can use it for our own keys.
171 $apps{$base}->{_Location} = $file;
172
173 # Extract all “Name” and “Exec” keys from the [Desktop Entry] group
174 # and store them in $apps{$base}.
175 my %names;
176 my $content = slurp($file);
177 next unless defined($content);
178 my @lines = split("\n", $content);
179 for my $line (@lines) {
180 my $first = substr($line, 0, 1);
181 next if $line eq '' || $first eq '#';
182 next unless ($line eq '[Desktop Entry]' ..
183 ($first eq '[' &&
184 substr($line, -1) eq ']' &&
185 $line ne '[Desktop Entry]'));
186 next if $first eq '[';
187
188 my ($key, $value) = ($line =~ /^
189 (
190 [A-Za-z0-9-]+ # the spec specifies these as valid key characters
191 (?:\[[^]]+\])? # possibly, there as a locale suffix
192 )
193 \s* = \s* # whitespace around = should be ignored
194 (.*) # no restrictions on the values
195 $/x);
196
197 if ($key =~ /^Name/) {
198 $names{$key} = $value;
199 } elsif ($key eq 'Exec' ||
200 $key eq 'TryExec' ||
201 $key eq 'Path' ||
202 $key eq 'Type') {
203 $apps{$base}->{$key} = $value;
204 } elsif ($key eq 'NoDisplay' ||
205 $key eq 'Hidden' ||
206 $key eq 'StartupNotify' ||
207 $key eq 'Terminal') {
208 # Values of type boolean must either be string true or false,
209 # see “Possible value types”:
210 # https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s03.html
211 $apps{$base}->{$key} = ($value eq 'true');
212 }
213 }
214
215 for my $suffix (@suffixes) {
216 next unless exists($names{"Name[$suffix]"});
217 $apps{$base}->{Name} = $names{"Name[$suffix]"};
218 last;
219 }
220
221 # Fallback to unlocalized “Name”.
222 $apps{$base}->{Name} = $names{Name} unless exists($apps{$base}->{Name});
223 }
224
225 # %apps now looks like this:
226 #
227 # %apps = {
228 # 'evince.desktop' => {
229 # 'Exec' => 'evince %U',
230 # 'Name' => 'Dokumentenbetrachter',
231 # '_Location' => '/usr/share/applications/evince.desktop'
232 # },
233 # 'gedit.desktop' => {
234 # 'Exec' => 'gedit %U',
235 # 'Name' => 'gedit',
236 # '_Location' => '/usr/share/applications/gedit.desktop'
237 # }
238 # };
239
240 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
241 # ┃ Turn %apps inside out to provide Name → filename lookup. ┃
242 # ┃ The Name is what we display in dmenu later. ┃
243 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
244
245 my %choices;
246 for my $app (keys %apps) {
247 my $name = $apps{$app}->{Name};
248
249 # Don’t try to use .desktop files which don’t have Type=application
250 next if (!exists($apps{$app}->{Type}) ||
251 $apps{$app}->{Type} ne 'Application');
252
253 # Skip broken files (Type=application, but no Exec key).
254 if (!exists($apps{$app}->{Exec}) ||
255 $apps{$app}->{Exec} eq '') {
256 warn 'File ' . $apps{$app}->{_Location} . ' is broken: it contains Type=Application, but no Exec key/value pair.';
257 next;
258 }
259
260 # Don’t offer apps which have NoDisplay == true or Hidden == true.
261 # See https://wiki.xfce.org/howto/customize-menu#hide_menu_entries
262 # for the difference between NoDisplay and Hidden.
263 next if (exists($apps{$app}->{NoDisplay}) && $apps{$app}->{NoDisplay}) ||
264 (exists($apps{$app}->{Hidden}) && $apps{$app}->{Hidden});
265
266 if (exists($apps{$app}->{TryExec})) {
267 my $tryexec = $apps{$app}->{TryExec};
268 if (substr($tryexec, 0, 1) eq '/') {
269 # Skip if absolute path is not executable.
270 next unless -x $tryexec;
271 } else {
272 # Search in $PATH for the executable.
273 my $found = 0;
274 for my $path (split(':', $ENV{PATH})) {
275 next unless -x "$path/$tryexec";
276 $found = 1;
277 last;
278 }
279 next unless $found;
280 }
281 }
282
283 if ((scalar grep { $_ eq 'name' } @entry_types) > 0) {
284 if (exists($choices{$name})) {
285 # There are two .desktop files which contain the same “Name” value.
286 # I’m not sure if that is allowed to happen, but we disambiguate the
287 # situation by appending “ (2)”, “ (3)”, etc. to the name.
288 #
289 # An example of this happening is exo-file-manager.desktop and
290 # thunar-settings.desktop, both of which contain “Name=File Manager”.
291 my $inc = 2;
292 $inc++ while exists($choices{"$name ($inc)"});
293 $name = "$name ($inc)";
294 }
295
296 $choices{$name} = $app;
297 next unless $show_duplicates;
298 }
299
300 if ((scalar grep { $_ eq 'command' } @entry_types) > 0) {
301 my $command = $apps{$app}->{Exec};
302
303 # Handle escape sequences (should be done for all string values, but does
304 # matter here).
305 my %escapes = (
306 '\\s' => ' ',
307 '\\n' => '\n',
308 '\\t' => '\t',
309 '\\r' => '\r',
310 '\\\\' => '\\',
311 );
312 $command =~ s/(\\[sntr\\])/$escapes{$1}/go;
313
314 # Extract executable
315 if ($command =~ m/^\s*([^\s\"]+)(?:\s|$)/) {
316 # No quotes
317 $command = $1;
318 } elsif ($command =~ m/^\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"(?:\s|$)/) {
319 # Quoted, remove quotes and fix escaped characters
320 $command = $1;
321 $command =~ s/\\([\"\`\$\\])/$1/g;
322 } else {
323 # Invalid quotes, fallback to whitespace
324 ($command) = split(' ', $command);
325 }
326
327 # Don’t add “geany” if “Geany” is already present.
328 my @keys = map { lc } keys %choices;
329 if (!(scalar grep { $_ eq lc(basename($command)) } @keys) > 0) {
330 $choices{basename($command)} = $app;
331 }
332 next unless $show_duplicates;
333 }
334
335 if ((scalar grep { $_ eq 'filename' } @entry_types) > 0) {
336 my $filename = basename($app, '.desktop');
337
338 # Don’t add “geany” if “Geany” is already present.
339 my @keys = map { lc } keys %choices;
340 next if (scalar grep { $_ eq lc($filename) } @keys) > 0;
341
342 $choices{$filename} = $app;
343 }
344 }
345
346 # %choices now looks like this:
347 #
348 # %choices = {
349 # 'Dokumentenbetrachter' => 'evince.desktop',
350 # 'gedit' => 'gedit.desktop'
351 # };
352
353 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
354 # ┃ Run dmenu to ask the user for their choice ┃
355 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
356
357 # open2 will just make dmenu’s STDERR go to our own STDERR.
358 my ($dmenu_out, $dmenu_in);
359 my $pid = eval {
360 open2($dmenu_out, $dmenu_in, $dmenu_cmd);
361 } or do {
362 print STDERR "$@";
363 say STDERR "Running dmenu failed. Is dmenu installed at all? Try running dmenu -v";
364 exit 1;
365 };
366
367 binmode $dmenu_in, ':utf8';
368 binmode $dmenu_out, ':utf8';
369
370 # Feed dmenu the possible choices.
371 # Since the process might have already exited, we ignore SIGPIPE.
372 $SIG{PIPE} = 'IGNORE';
373
374 say $dmenu_in $_ for sort keys %choices;
375 close($dmenu_in);
376
377 $SIG{PIPE} = 'DEFAULT';
378
379 waitpid($pid, 0);
380 my $status = ($? >> 8);
381
382 # Pass on dmenu’s exit status if there was an error.
383 exit $status unless $status == 0;
384
385 my $choice = <$dmenu_out>;
386 # dmenu ≥ 4.4 adds a newline after the choice
387 chomp($choice);
388 my $app;
389 # Exact match: the user chose “Avidemux (GTK+)”
390 if (exists($choices{$choice})) {
391 $app = $apps{$choices{$choice}};
392 $choice = '';
393 } else {
394 # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
395 for my $possibility (keys %choices) {
396 next unless substr($choice, 0, length($possibility)) eq $possibility;
397 $app = $apps{$choices{$possibility}};
398 substr($choice, 0, length($possibility)) = '';
399 # Remove whitespace separating the entry and arguments.
400 $choice =~ s/^\s//g;
401 last;
402 }
403 if (!defined($app)) {
404 warn "Invalid input: “$choice” does not match any application. Trying to execute nevertheless.";
405 $app->{Name} = '';
406 $app->{Exec} = $choice;
407 # We assume that the app is old and does not support startup
408 # notifications because it doesn’t ship a desktop file.
409 $app->{StartupNotify} = 0;
410 $app->{_Location} = '';
411 }
412 }
413
414 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
415 # ┃ Make i3 start the chosen application. ┃
416 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
417
418 my $name = $app->{Name};
419 my $exec = $app->{Exec};
420 my $location = $app->{_Location};
421
422 # Quote as described by “The Exec key”:
423 # https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s07.html
424 sub quote {
425 my ($str) = @_;
426 $str =~ s/("|`|\$|\\)/\\$1/g;
427 $str = qq|"$str"| if $str ne "";
428 return $str;
429 }
430
431 $choice = quote($choice);
432 $location = quote($location);
433 $name = quote($name);
434
435 # https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s07.html:
436 #
437 # Note that the general escape rule for values of type string states that the
438 # backslash character can be escaped as ("\\") as well and that this escape rule
439 # is applied before the quoting rule. As such, to unambiguously represent a
440 # literal backslash character in a quoted argument in a desktop entry file
441 # requires the use of four successive backslash characters ("\\\\"). Likewise, a
442 # literal dollar sign in a quoted argument in a desktop entry file is
443 # unambiguously represented with ("\\$").
444 $exec =~ s/\\\\/\\/g;
445
446 # Remove deprecated field codes, as the spec dictates.
447 $exec =~ s/%[dDnNvm]//g;
448
449 # Replace filename field codes with the rest of the command line.
450 # Note that we assume the user uses precisely one file name,
451 # not multiple file names.
452 $exec =~ s/%[fF]/$choice/g;
453
454 # If the program works with URLs,
455 # we assume the user provided a URL instead of a filename.
456 # As per the spec, there must be at most one of %f, %u, %F or %U present.
457 $exec =~ s/%[uU]/$choice/g;
458
459 # The translated name of the application.
460 $exec =~ s/%c/$name/g;
461
462 # XXX: Icons are not implemented. Is the complexity (looking up the path if
463 # only a name is given) actually worth it?
464 #$exec =~ s/%i/--icon $icon/g;
465 $exec =~ s/%i//g;
466
467 # location of .desktop file
468 $exec =~ s/%k/$location/g;
469
470 # Literal % characters are represented as %%.
471 $exec =~ s/%%/%/g;
472
473 if (exists($app->{Path}) && $app->{Path} ne '') {
474 $exec = 'cd ' . quote($app->{Path}) . ' && ' . $exec;
475 }
476
477 my $nosn = '';
478 my $cmd;
479 if (exists($app->{Terminal}) && $app->{Terminal}) {
480 # For applications which specify “Terminal=true” (e.g. htop.desktop),
481 # we need to create a temporary script that contains the full command line
482 # as the syntax for starting commands with arguments varies from terminal
483 # emulator to terminal emulator.
484 # Then, we launch that script with i3-sensible-terminal.
485 my ($fh, $filename) = tempfile();
486 binmode($fh, ':utf8');
487 say $fh <<EOT;
488 #!/bin/sh
489 rm $filename
490 exec $exec
491 EOT
492 close($fh);
493 chmod 0755, $filename;
494
495 $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
496 } else {
497 # i3 executes applications by passing the argument to i3’s “exec” command
498 # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
499 # starts with a double quote ("), everything is parsed as-is until the next
500 # double quote which is NOT preceded by a backslash (\).
501 #
502 # Therefore, we escape all double quotes (") by replacing them with \".
503 # To not change the meaning of any double quote, backslashes need to be
504 # escaped as well.
505 $exec =~ s/(["\\])/\\$1/g;
506
507 if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
508 $nosn = '--no-startup-id';
509 }
510 $cmd = qq|exec $nosn "$exec"|;
511 }
512
513 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
514
515 =encoding utf-8
516
517 =head1 NAME
518
519 i3-dmenu-desktop - run .desktop files with dmenu
520
521 =head1 SYNOPSIS
522
523 i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=name] [--show-duplicates]
524
525 =head1 DESCRIPTION
526
527 i3-dmenu-desktop is a script which extracts the (localized) name from
528 application .desktop files, offers the user a choice via dmenu(1) and then
529 starts the chosen application via i3 (for startup notification support).
530 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
531 offers B<all> binaries in your $PATH, including non-interactive utilities like
532 "sed". Also, .desktop files contain a proper name, information about whether
533 the application runs in a terminal and whether it supports startup
534 notifications.
535
536 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
537 $HOME/.local/share/applications) and in the "applications" subdirectory of each
538 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
539
540 Files with the same name in $XDG_DATA_HOME/applications take precedence over
541 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
542 .desktop files by copying them to your local directory and making changes.
543
544 i3-dmenu-desktop displays the "Name" value in the localized version depending
545 on LC_MESSAGES as specified in the Desktop Entry Specification.
546
547 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
548 file respectively) by appending it to the name of the application. E.g., if you
549 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
550 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
551
552 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
553
554 .desktop files with NoDisplay=true or Hidden=true are skipped.
555
556 UTF-8 is supported, of course, but dmenu does not support displaying all
557 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
558 fine, but not its Name[ru]=Терминал.
559
560 =head1 OPTIONS
561
562 =over
563
564 =item B<--dmenu=command>
565
566 Execute command instead of 'dmenu -i'. This option can be used to pass custom
567 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
568 version of dmenu.
569
570 =item B<--entry-type=type>
571
572 Display the (localized) "Name" (type = name), the command (type = command) or
573 the (*.desktop) filename (type = filename) in dmenu. This option can be
574 specified multiple times. Duplicates will be removed, see '--show-duplicates'.
575
576 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
577 command), and "libreoffice-writer" (type = filename).
578
579 =item B<--show-duplicates>
580
581 Show duplicates if '--entry-type' is specified multiple times.
582
583 =back
584
585 =head1 VERSION
586
587 Version 1.5
588
589 =head1 AUTHOR
590
591 Michael Stapelberg, C<< <michael at i3wm.org> >>
592
593 =head1 LICENSE AND COPYRIGHT
594
595 Copyright 2012 Michael Stapelberg.
596
597 This program is free software; you can redistribute it and/or modify it
598 under the terms of the BSD license.
599
600 =cut