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