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