]> git.sur5r.net Git - i3/i3/blob - i3-dmenu-desktop
Merge branch 'fix-assign-and-move'
[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.2 © 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         $choices{basename($command)} = $app;
254     }
255 }
256
257 # %choices now looks like this:
258 #
259 # %choices = {
260 #     'Dokumentenbetrachter' => 'evince.desktop',
261 #     'gedit' => 'gedit.desktop'
262 #   };
263
264 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
265 # ┃ Run dmenu to ask the user for her choice                                  ┃
266 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
267
268 # open2 will just make dmenu’s STDERR go to our own STDERR.
269 my ($dmenu_out, $dmenu_in);
270 my $pid = open2($dmenu_out, $dmenu_in, $dmenu_cmd);
271 binmode $dmenu_in, ':utf8';
272 binmode $dmenu_out, ':utf8';
273
274 # Feed dmenu the possible choices.
275 say $dmenu_in $_ for sort keys %choices;
276 close($dmenu_in);
277
278 waitpid($pid, 0);
279 my $status = ($? >> 8);
280
281 # Pass on dmenu’s exit status if there was an error.
282 exit $status unless $status == 0;
283
284 my $choice = <$dmenu_out>;
285 my $app;
286 # Exact match: the user chose “Avidemux (GTK+)”
287 if (exists($choices{$choice})) {
288     $app = $apps{$choices{$choice}};
289     $choice = '';
290 } else {
291     # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
292     for my $possibility (keys %choices) {
293         next unless substr($choice, 0, length($possibility)) eq $possibility;
294         $app = $apps{$choices{$possibility}};
295         substr($choice, 0, length($possibility)) = '';
296         # Remove whitespace separating the entry and arguments.
297         $choice =~ s/^\s//g;
298         last;
299     }
300     if (!defined($app)) {
301         die "Invalid input: “$choice” does not match any application.";
302     }
303 }
304
305 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
306 # ┃ Make i3 start the chosen application.                                     ┃
307 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
308
309 my $name = $app->{Name};
310 my $exec = $app->{Exec};
311 my $location = $app->{_Location};
312
313 # Quote as described by “The Exec key”:
314 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
315 sub quote {
316     my ($str) = @_;
317     $str =~ s/("|`|\$|\\)/\\$1/g;
318     $str = qq|"$str"| if $str ne "";
319     return $str;
320 }
321
322 $choice = quote($choice);
323 $location = quote($location);
324
325 # Remove deprecated field codes, as the spec dictates.
326 $exec =~ s/%[dDnNvm]//g;
327
328 # Replace filename field codes with the rest of the command line.
329 # Note that we assume the user uses precisely one file name,
330 # not multiple file names.
331 $exec =~ s/%[fF]/$choice/g;
332
333 # If the program works with URLs,
334 # we assume the user provided a URL instead of a filename.
335 # As per the spec, there must be at most one of %f, %u, %F or %U present.
336 $exec =~ s/%[uU]/$choice/g;
337
338 # The translated name of the application.
339 $exec =~ s/%c/$name/g;
340
341 # XXX: Icons are not implemented. Is the complexity (looking up the path if
342 # only a name is given) actually worth it?
343 #$exec =~ s/%i/--icon $icon/g;
344
345 # location of .desktop file
346 $exec =~ s/%k/$location/g;
347
348 # Literal % characters are represented as %%.
349 $exec =~ s/%%/%/g;
350
351 my $nosn = '';
352 my $cmd;
353 if (exists($app->{Terminal}) && $app->{Terminal}) {
354     # For applications which specify “Terminal=true” (e.g. htop.desktop),
355     # we need to create a temporary script that contains the full command line
356     # as the syntax for starting commands with arguments varies from terminal
357     # emulator to terminal emulator.
358     # Then, we launch that script with i3-sensible-terminal.
359     my ($fh, $filename) = tempfile();
360     binmode($fh, ':utf8');
361     say $fh <<EOT;
362 #!/bin/sh
363 rm $filename
364 exec $exec
365 EOT
366     close($fh);
367     chmod 0755, $filename;
368
369     $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
370 } else {
371     # i3 executes applications by passing the argument to i3’s “exec” command
372     # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
373     # starts with a double quote ("), everything is parsed as-is until the next
374     # double quote which is NOT preceded by a backslash (\).
375     #
376     # Therefore, we escape all double quotes (") by replacing them with \"
377     $exec =~ s/"/\\"/g;
378
379     if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
380         $nosn = '--no-startup-id';
381     }
382     $cmd = qq|exec $nosn "$exec"|;
383 }
384
385 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
386
387 =encoding utf-8
388
389 =head1 NAME
390
391     i3-dmenu-desktop - run .desktop files with dmenu
392
393 =head1 SYNOPSIS
394
395     i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=both]
396
397 =head1 DESCRIPTION
398
399 i3-dmenu-desktop is a script which extracts the (localized) name from
400 application .desktop files, offers the user a choice via dmenu(1) and then
401 starts the chosen application via i3 (for startup notification support).
402 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
403 offers B<all> binaries in your $PATH, including non-interactive utilities like
404 "sed". Also, .desktop files contain a proper name, information about whether
405 the application runs in a terminal and whether it supports startup
406 notifications.
407
408 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
409 $HOME/.local/share/applications) and in the "applications" subdirectory of each
410 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
411
412 Files with the same name in $XDG_DATA_HOME/applications take precedence over
413 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
414 .desktop files by copying them to your local directory and making changes.
415
416 i3-dmenu-desktop displays the "Name" value in the localized version depending
417 on LC_MESSAGES as specified in the Desktop Entry Specification.
418
419 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
420 file respectively) by appending it to the name of the application. E.g., if you
421 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
422 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
423
424 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
425
426 .desktop files with NoDisplay=true or Hidden=true are skipped.
427
428 UTF-8 is supported, of course, but dmenu does not support displaying all
429 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
430 fine, but not its Name[ru]=Терминал.
431
432 =head1 OPTIONS
433
434 =over
435
436 =item B<--dmenu=command>
437
438 Execute command instead of 'dmenu -i'. This option can be used to pass custom
439 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
440 version of dmenu.
441
442 =item B<--entry-type=type>
443
444 Display the (localized) "Name" (type = name) or the command (type = command) or
445 both (type = both) in dmenu.
446
447 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
448 command) and both (type = both).
449
450 =back
451
452 =head1 VERSION
453
454 Version 1.2
455
456 =head1 AUTHOR
457
458 Michael Stapelberg, C<< <michael at i3wm.org> >>
459
460 =head1 LICENSE AND COPYRIGHT
461
462 Copyright 2012 Michael Stapelberg.
463
464 This program is free software; you can redistribute it and/or modify it
465 under the terms of the BSD license.
466
467 =cut