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