]> git.sur5r.net Git - i3/i3/blob - i3-dmenu-desktop
80d33c23559469f489286e28167341a434781728
[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;
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.3 © 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                  $key eq 'Type') {
162             $apps{$base}->{$key} = $value;
163         } elsif ($key eq 'NoDisplay' ||
164                  $key eq 'Hidden' ||
165                  $key eq 'StartupNotify' ||
166                  $key eq 'Terminal') {
167             # Values of type boolean must either be string true or false,
168             # see “Possible value types”:
169             # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s03.html
170             $apps{$base}->{$key} = ($value eq 'true');
171         }
172     }
173
174     for my $suffix (@suffixes) {
175         next unless exists($names{"Name[$suffix]"});
176         $apps{$base}->{Name} = $names{"Name[$suffix]"};
177         last;
178     }
179
180     # Fallback to unlocalized “Name”.
181     $apps{$base}->{Name} = $names{Name} unless exists($apps{$base}->{Name});
182 }
183
184 # %apps now looks like this:
185 #
186 # %apps = {
187 #     'evince.desktop' => {
188 #         'Exec' => 'evince %U',
189 #         'Name' => 'Dokumentenbetrachter',
190 #         '_Location' => '/usr/share/applications/evince.desktop'
191 #       },
192 #     'gedit.desktop' => {
193 #         'Exec' => 'gedit %U',
194 #         'Name' => 'gedit',
195 #         '_Location' => '/usr/share/applications/gedit.desktop'
196 #       }
197 #   };
198
199 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
200 # ┃ Turn %apps inside out to provide Name → filename lookup.                  ┃
201 # ┃ The Name is what we display in dmenu later.                               ┃
202 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
203
204 my %choices;
205 for my $app (keys %apps) {
206     my $name = $apps{$app}->{Name};
207
208     # Don’t try to use .desktop files which don’t have Type=application
209     next if (!exists($apps{$app}->{Type}) ||
210              $apps{$app}->{Type} ne 'Application');
211
212     # Don’t offer apps which have NoDisplay == true or Hidden == true.
213     # See http://wiki.xfce.org/howto/customize-menu#hide_menu_entries
214     # for the difference between NoDisplay and Hidden.
215     next if (exists($apps{$app}->{NoDisplay}) && $apps{$app}->{NoDisplay}) ||
216             (exists($apps{$app}->{Hidden}) && $apps{$app}->{Hidden});
217
218     if (exists($apps{$app}->{TryExec})) {
219         my $tryexec = $apps{$app}->{TryExec};
220         if (substr($tryexec, 0, 1) eq '/') {
221             # Skip if absolute path is not executable.
222             next unless -x $tryexec;
223         } else {
224             # Search in $PATH for the executable.
225             my $found = 0;
226             for my $path (split(':', $ENV{PATH})) {
227                 next unless -x "$path/$tryexec";
228                 $found = 1;
229                 last;
230             }
231             next unless $found;
232         }
233     }
234
235     if ($entry_type eq 'name' || $entry_type eq 'both') {
236         if (exists($choices{$name})) {
237             # There are two .desktop files which contain the same “Name” value.
238             # I’m not sure if that is allowed to happen, but we disambiguate the
239             # situation by appending “ (2)”, “ (3)”, etc. to the name.
240             #
241             # An example of this happening is exo-file-manager.desktop and
242             # thunar-settings.desktop, both of which contain “Name=File Manager”.
243             my $inc = 2;
244             $inc++ while exists($choices{"$name ($inc)"});
245             $name = "$name ($inc)";
246         }
247
248         $choices{$name} = $app;
249     }
250
251     if ($entry_type eq 'command' || $entry_type eq 'both') {
252         my ($command) = split(' ', $apps{$app}->{Exec});
253
254         # Don’t add “geany” if “Geany” is already present.
255         my @keys = map { lc } keys %choices;
256         next if lc(basename($command)) ~~ @keys;
257
258         $choices{basename($command)} = $app;
259     }
260 }
261
262 # %choices now looks like this:
263 #
264 # %choices = {
265 #     'Dokumentenbetrachter' => 'evince.desktop',
266 #     'gedit' => 'gedit.desktop'
267 #   };
268
269 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
270 # ┃ Run dmenu to ask the user for her choice                                  ┃
271 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
272
273 # open2 will just make dmenu’s STDERR go to our own STDERR.
274 my ($dmenu_out, $dmenu_in);
275 my $pid = open2($dmenu_out, $dmenu_in, $dmenu_cmd);
276 binmode $dmenu_in, ':utf8';
277 binmode $dmenu_out, ':utf8';
278
279 # Feed dmenu the possible choices.
280 say $dmenu_in $_ for sort keys %choices;
281 close($dmenu_in);
282
283 waitpid($pid, 0);
284 my $status = ($? >> 8);
285
286 # Pass on dmenu’s exit status if there was an error.
287 exit $status unless $status == 0;
288
289 my $choice = <$dmenu_out>;
290 # dmenu ≥ 4.4 adds a newline after the choice
291 chomp($choice);
292 my $app;
293 # Exact match: the user chose “Avidemux (GTK+)”
294 if (exists($choices{$choice})) {
295     $app = $apps{$choices{$choice}};
296     $choice = '';
297 } else {
298     # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
299     for my $possibility (keys %choices) {
300         next unless substr($choice, 0, length($possibility)) eq $possibility;
301         $app = $apps{$choices{$possibility}};
302         substr($choice, 0, length($possibility)) = '';
303         # Remove whitespace separating the entry and arguments.
304         $choice =~ s/^\s//g;
305         last;
306     }
307     if (!defined($app)) {
308         die "Invalid input: “$choice” does not match any application.";
309     }
310 }
311
312 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
313 # ┃ Make i3 start the chosen application.                                     ┃
314 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
315
316 my $name = $app->{Name};
317 my $exec = $app->{Exec};
318 my $location = $app->{_Location};
319
320 # Quote as described by “The Exec key”:
321 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
322 sub quote {
323     my ($str) = @_;
324     $str =~ s/("|`|\$|\\)/\\$1/g;
325     $str = qq|"$str"| if $str ne "";
326     return $str;
327 }
328
329 $choice = quote($choice);
330 $location = quote($location);
331
332 # Remove deprecated field codes, as the spec dictates.
333 $exec =~ s/%[dDnNvm]//g;
334
335 # Replace filename field codes with the rest of the command line.
336 # Note that we assume the user uses precisely one file name,
337 # not multiple file names.
338 $exec =~ s/%[fF]/$choice/g;
339
340 # If the program works with URLs,
341 # we assume the user provided a URL instead of a filename.
342 # As per the spec, there must be at most one of %f, %u, %F or %U present.
343 $exec =~ s/%[uU]/$choice/g;
344
345 # The translated name of the application.
346 $exec =~ s/%c/$name/g;
347
348 # XXX: Icons are not implemented. Is the complexity (looking up the path if
349 # only a name is given) actually worth it?
350 #$exec =~ s/%i/--icon $icon/g;
351
352 # location of .desktop file
353 $exec =~ s/%k/$location/g;
354
355 # Literal % characters are represented as %%.
356 $exec =~ s/%%/%/g;
357
358 my $nosn = '';
359 my $cmd;
360 if (exists($app->{Terminal}) && $app->{Terminal}) {
361     # For applications which specify “Terminal=true” (e.g. htop.desktop),
362     # we need to create a temporary script that contains the full command line
363     # as the syntax for starting commands with arguments varies from terminal
364     # emulator to terminal emulator.
365     # Then, we launch that script with i3-sensible-terminal.
366     my ($fh, $filename) = tempfile();
367     binmode($fh, ':utf8');
368     say $fh <<EOT;
369 #!/bin/sh
370 rm $filename
371 exec $exec
372 EOT
373     close($fh);
374     chmod 0755, $filename;
375
376     $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
377 } else {
378     # i3 executes applications by passing the argument to i3’s “exec” command
379     # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
380     # starts with a double quote ("), everything is parsed as-is until the next
381     # double quote which is NOT preceded by a backslash (\).
382     #
383     # Therefore, we escape all double quotes (") by replacing them with \"
384     $exec =~ s/"/\\"/g;
385
386     if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
387         $nosn = '--no-startup-id';
388     }
389     $cmd = qq|exec $nosn "$exec"|;
390 }
391
392 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
393
394 =encoding utf-8
395
396 =head1 NAME
397
398     i3-dmenu-desktop - run .desktop files with dmenu
399
400 =head1 SYNOPSIS
401
402     i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=both]
403
404 =head1 DESCRIPTION
405
406 i3-dmenu-desktop is a script which extracts the (localized) name from
407 application .desktop files, offers the user a choice via dmenu(1) and then
408 starts the chosen application via i3 (for startup notification support).
409 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
410 offers B<all> binaries in your $PATH, including non-interactive utilities like
411 "sed". Also, .desktop files contain a proper name, information about whether
412 the application runs in a terminal and whether it supports startup
413 notifications.
414
415 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
416 $HOME/.local/share/applications) and in the "applications" subdirectory of each
417 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
418
419 Files with the same name in $XDG_DATA_HOME/applications take precedence over
420 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
421 .desktop files by copying them to your local directory and making changes.
422
423 i3-dmenu-desktop displays the "Name" value in the localized version depending
424 on LC_MESSAGES as specified in the Desktop Entry Specification.
425
426 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
427 file respectively) by appending it to the name of the application. E.g., if you
428 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
429 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
430
431 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
432
433 .desktop files with NoDisplay=true or Hidden=true are skipped.
434
435 UTF-8 is supported, of course, but dmenu does not support displaying all
436 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
437 fine, but not its Name[ru]=Терминал.
438
439 =head1 OPTIONS
440
441 =over
442
443 =item B<--dmenu=command>
444
445 Execute command instead of 'dmenu -i'. This option can be used to pass custom
446 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
447 version of dmenu.
448
449 =item B<--entry-type=type>
450
451 Display the (localized) "Name" (type = name) or the command (type = command) or
452 both (type = both) in dmenu.
453
454 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
455 command) and both (type = both).
456
457 =back
458
459 =head1 VERSION
460
461 Version 1.3
462
463 =head1 AUTHOR
464
465 Michael Stapelberg, C<< <michael at i3wm.org> >>
466
467 =head1 LICENSE AND COPYRIGHT
468
469 Copyright 2012 Michael Stapelberg.
470
471 This program is free software; you can redistribute it and/or modify it
472 under the terms of the BSD license.
473
474 =cut