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