2 # vim:ts=4:sw=4:expandtab
4 # © 2012 Michael Stapelberg
6 # No dependencies except for perl ≥ v5.10
12 use POSIX qw(locale_h);
14 use File::Basename qw(basename);
15 use File::Temp qw(tempfile);
20 use open ':encoding(utf8)';
22 binmode STDOUT, ':utf8';
23 binmode STDERR, ':utf8';
25 # reads in a whole file
27 open(my $fh, '<', shift) or die "$!";
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,
38 say "dmenu-desktop 1.3 © 2012 Michael Stapelberg";
42 pod2usage(-exitval => 0);
45 die "Could not parse command line options" unless $result;
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 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
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);
58 # Ignore the encoding (e.g. .UTF-8)
59 $lc_messages =~ s/\.[^@]+//g;
61 my @suffixes = ($lc_messages);
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;
69 my $no_country = $lc_messages;
70 $no_country =~ s/_[^@]+//g;
71 push @suffixes, $no_country;
74 # Strip _COUNTRY and @MODIFIER if present
75 $lc_messages =~ s/[_@].*//g;
76 push @suffixes, $lc_messages;
78 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
79 # ┃ Read all .desktop files and store the values in which we are interested. ┃
80 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
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 '' ||
90 my $xdg_data_dirs = $ENV{XDG_DATA_DIRS};
91 $xdg_data_dirs = '/usr/local/share/:/usr/share/' if
92 !defined($xdg_data_dirs) ||
95 my @searchdirs = ("$xdg_data_home/applications/");
96 for my $dir (split(':', $xdg_data_dirs)) {
97 push @searchdirs, "$dir/applications/";
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;
104 # To avoid errors by File::Find’s find(), only pass existing directories.
105 @searchdirs = grep { -d $_ } @searchdirs;
110 return unless substr($_, -1 * length('.desktop')) eq '.desktop';
111 my $relative = $File::Find::name;
113 # + 1 for the trailing /, which is missing in ::topdir.
114 substr($relative, 0, length($File::Find::topdir) + 1) = '';
116 # Don’t overwrite files with the same relative path, we search in
117 # descending order of importance.
118 return if exists($desktops{$relative});
120 $desktops{$relative} = $File::Find::name;
129 for my $file (values %desktops) {
130 my $base = basename($file);
132 # _ is an invalid character for a key, so we can use it for our own keys.
133 $apps{$base}->{_Location} = $file;
135 # Extract all “Name” and “Exec” keys from the [Desktop Entry] group
136 # and store them in $apps{$base}.
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]' ..
144 substr($line, -1) eq ']' &&
145 $line ne '[Desktop Entry]'));
146 next if $first eq '[';
148 my ($key, $value) = ($line =~ /^
150 [A-Za-z0-9-]+ # the spec specifies these as valid key characters
151 (?:\[[^]]+\])? # possibly, there as a locale suffix
153 \s* = \s* # whitespace around = should be ignored
154 (.*) # no restrictions on the values
157 if ($key =~ /^Name/) {
158 $names{$key} = $value;
159 } elsif ($key eq 'Exec' ||
162 $apps{$base}->{$key} = $value;
163 } elsif ($key eq 'NoDisplay' ||
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');
174 for my $suffix (@suffixes) {
175 next unless exists($names{"Name[$suffix]"});
176 $apps{$base}->{Name} = $names{"Name[$suffix]"};
180 # Fallback to unlocalized “Name”.
181 $apps{$base}->{Name} = $names{Name} unless exists($apps{$base}->{Name});
184 # %apps now looks like this:
187 # 'evince.desktop' => {
188 # 'Exec' => 'evince %U',
189 # 'Name' => 'Dokumentenbetrachter',
190 # '_Location' => '/usr/share/applications/evince.desktop'
192 # 'gedit.desktop' => {
193 # 'Exec' => 'gedit %U',
195 # '_Location' => '/usr/share/applications/gedit.desktop'
199 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
200 # ┃ Turn %apps inside out to provide Name → filename lookup. ┃
201 # ┃ The Name is what we display in dmenu later. ┃
202 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
205 for my $app (keys %apps) {
206 my $name = $apps{$app}->{Name};
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');
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});
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;
224 # Search in $PATH for the executable.
226 for my $path (split(':', $ENV{PATH})) {
227 next unless -x "$path/$tryexec";
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.
241 # An example of this happening is exo-file-manager.desktop and
242 # thunar-settings.desktop, both of which contain “Name=File Manager”.
244 $inc++ while exists($choices{"$name ($inc)"});
245 $name = "$name ($inc)";
248 $choices{$name} = $app;
251 if ($entry_type eq 'command' || $entry_type eq 'both') {
252 my ($command) = split(' ', $apps{$app}->{Exec});
254 # Don’t add “geany” if “Geany” is already present.
255 my @keys = map { lc } keys %choices;
256 next if lc(basename($command)) ~~ @keys;
258 $choices{basename($command)} = $app;
262 # %choices now looks like this:
265 # 'Dokumentenbetrachter' => 'evince.desktop',
266 # 'gedit' => 'gedit.desktop'
269 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
270 # ┃ Run dmenu to ask the user for her choice ┃
271 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
273 # open2 will just make dmenu’s STDERR go to our own STDERR.
274 my ($dmenu_out, $dmenu_in);
275 my $pid = open2($dmenu_out, $dmenu_in, $dmenu_cmd);
276 binmode $dmenu_in, ':utf8';
277 binmode $dmenu_out, ':utf8';
279 # Feed dmenu the possible choices.
280 say $dmenu_in $_ for sort keys %choices;
284 my $status = ($? >> 8);
286 # Pass on dmenu’s exit status if there was an error.
287 exit $status unless $status == 0;
289 my $choice = <$dmenu_out>;
290 # dmenu ≥ 4.4 adds a newline after the choice
293 # Exact match: the user chose “Avidemux (GTK+)”
294 if (exists($choices{$choice})) {
295 $app = $apps{$choices{$choice}};
298 # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
299 for my $possibility (keys %choices) {
300 next unless substr($choice, 0, length($possibility)) eq $possibility;
301 $app = $apps{$choices{$possibility}};
302 substr($choice, 0, length($possibility)) = '';
303 # Remove whitespace separating the entry and arguments.
307 if (!defined($app)) {
308 die "Invalid input: “$choice” does not match any application.";
312 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
313 # ┃ Make i3 start the chosen application. ┃
314 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
316 my $name = $app->{Name};
317 my $exec = $app->{Exec};
318 my $location = $app->{_Location};
320 # Quote as described by “The Exec key”:
321 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
324 $str =~ s/("|`|\$|\\)/\\$1/g;
325 $str = qq|"$str"| if $str ne "";
329 $choice = quote($choice);
330 $location = quote($location);
332 # Remove deprecated field codes, as the spec dictates.
333 $exec =~ s/%[dDnNvm]//g;
335 # Replace filename field codes with the rest of the command line.
336 # Note that we assume the user uses precisely one file name,
337 # not multiple file names.
338 $exec =~ s/%[fF]/$choice/g;
340 # If the program works with URLs,
341 # we assume the user provided a URL instead of a filename.
342 # As per the spec, there must be at most one of %f, %u, %F or %U present.
343 $exec =~ s/%[uU]/$choice/g;
345 # The translated name of the application.
346 $exec =~ s/%c/$name/g;
348 # XXX: Icons are not implemented. Is the complexity (looking up the path if
349 # only a name is given) actually worth it?
350 #$exec =~ s/%i/--icon $icon/g;
352 # location of .desktop file
353 $exec =~ s/%k/$location/g;
355 # Literal % characters are represented as %%.
360 if (exists($app->{Terminal}) && $app->{Terminal}) {
361 # For applications which specify “Terminal=true” (e.g. htop.desktop),
362 # we need to create a temporary script that contains the full command line
363 # as the syntax for starting commands with arguments varies from terminal
364 # emulator to terminal emulator.
365 # Then, we launch that script with i3-sensible-terminal.
366 my ($fh, $filename) = tempfile();
367 binmode($fh, ':utf8');
374 chmod 0755, $filename;
376 $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
378 # i3 executes applications by passing the argument to i3’s “exec” command
379 # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
380 # starts with a double quote ("), everything is parsed as-is until the next
381 # double quote which is NOT preceded by a backslash (\).
383 # Therefore, we escape all double quotes (") by replacing them with \"
386 if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
387 $nosn = '--no-startup-id';
389 $cmd = qq|exec $nosn "$exec"|;
392 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
398 i3-dmenu-desktop - run .desktop files with dmenu
402 i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=both]
406 i3-dmenu-desktop is a script which extracts the (localized) name from
407 application .desktop files, offers the user a choice via dmenu(1) and then
408 starts the chosen application via i3 (for startup notification support).
409 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
410 offers B<all> binaries in your $PATH, including non-interactive utilities like
411 "sed". Also, .desktop files contain a proper name, information about whether
412 the application runs in a terminal and whether it supports startup
415 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
416 $HOME/.local/share/applications) and in the "applications" subdirectory of each
417 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
419 Files with the same name in $XDG_DATA_HOME/applications take precedence over
420 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
421 .desktop files by copying them to your local directory and making changes.
423 i3-dmenu-desktop displays the "Name" value in the localized version depending
424 on LC_MESSAGES as specified in the Desktop Entry Specification.
426 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
427 file respectively) by appending it to the name of the application. E.g., if you
428 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
429 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
431 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
433 .desktop files with NoDisplay=true or Hidden=true are skipped.
435 UTF-8 is supported, of course, but dmenu does not support displaying all
436 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
437 fine, but not its Name[ru]=Терминал.
443 =item B<--dmenu=command>
445 Execute command instead of 'dmenu -i'. This option can be used to pass custom
446 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
449 =item B<--entry-type=type>
451 Display the (localized) "Name" (type = name) or the command (type = command) or
452 both (type = both) in dmenu.
454 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
455 command) and both (type = both).
465 Michael Stapelberg, C<< <michael at i3wm.org> >>
467 =head1 LICENSE AND COPYRIGHT
469 Copyright 2012 Michael Stapelberg.
471 This program is free software; you can redistribute it and/or modify it
472 under the terms of the BSD license.