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