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