.i3/i3-dmenu-desktop

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

mercurial