.i3/i3-dmenu-desktop

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

mercurial