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