2 # vim:ts=4:sw=4:expandtab
4 # © 2012 Michael Stapelberg
6 # No dependencies except for perl ≥ v5.10
9 use warnings qw(FATAL utf8);
12 use POSIX qw(locale_h);
14 use File::Basename qw(basename);
15 use File::Temp qw(tempfile);
20 use open ':encoding(UTF-8)';
22 binmode STDOUT, ':utf8';
23 binmode STDERR, ':utf8';
25 # reads in a whole file
28 open(my $fh, '<', $filename) or die "$!";
35 warn "Could not read $filename: $@";
42 my $entry_type = 'both';
43 my $dmenu_cmd = 'dmenu -i';
44 my $result = GetOptions(
45 'dmenu=s' => \$dmenu_cmd,
46 'entry-type=s' => \$entry_type,
48 say "dmenu-desktop 1.3 © 2012 Michael Stapelberg";
52 pod2usage(-exitval => 0);
55 die "Could not parse command line options" unless $result;
57 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
58 # ┃ Convert LC_MESSAGES into an ordered list of suffixes to search for in the ┃
59 # ┃ .desktop files (e.g. “Name[de_DE@euro]” for LC_MESSAGES=de_DE.UTF-8@euro ┃
60 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
62 # For details on how the transformation of LC_MESSAGES to a list of keys that
63 # should be looked up works, refer to “Localized values for keys” of the
64 # “Desktop Entry Specification”:
65 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s04.html
66 my $lc_messages = setlocale(LC_MESSAGES);
68 # Ignore the encoding (e.g. .UTF-8)
69 $lc_messages =~ s/\.[^@]+//g;
71 my @suffixes = ($lc_messages);
73 # _COUNTRY and @MODIFIER are present
74 if ($lc_messages =~ /_[^@]+@/) {
75 my $no_modifier = $lc_messages;
76 $no_modifier =~ s/@.*//g;
77 push @suffixes, $no_modifier;
79 my $no_country = $lc_messages;
80 $no_country =~ s/_[^@]+//g;
81 push @suffixes, $no_country;
84 # Strip _COUNTRY and @MODIFIER if present
85 $lc_messages =~ s/[_@].*//g;
86 push @suffixes, $lc_messages;
88 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
89 # ┃ Read all .desktop files and store the values in which we are interested. ┃
90 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
93 # See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
94 my $xdg_data_home = $ENV{XDG_DATA_HOME};
95 $xdg_data_home = $ENV{HOME} . '/.local/share' if
96 !defined($xdg_data_home) ||
97 $xdg_data_home eq '' ||
100 my $xdg_data_dirs = $ENV{XDG_DATA_DIRS};
101 $xdg_data_dirs = '/usr/local/share/:/usr/share/' if
102 !defined($xdg_data_dirs) ||
103 $xdg_data_dirs eq '';
105 my @searchdirs = ("$xdg_data_home/applications/");
106 for my $dir (split(':', $xdg_data_dirs)) {
107 push @searchdirs, "$dir/applications/";
110 # Cleanup the paths, maybe some application does not cope with double slashes
111 # (the field code %k is replaced with the .desktop file location).
112 @searchdirs = map { s,//,/,g; $_ } @searchdirs;
114 # To avoid errors by File::Find’s find(), only pass existing directories.
115 @searchdirs = grep { -d $_ } @searchdirs;
120 return unless substr($_, -1 * length('.desktop')) eq '.desktop';
121 my $relative = $File::Find::name;
123 # + 1 for the trailing /, which is missing in ::topdir.
124 substr($relative, 0, length($File::Find::topdir) + 1) = '';
126 # Don’t overwrite files with the same relative path, we search in
127 # descending order of importance.
128 return if exists($desktops{$relative});
130 $desktops{$relative} = $File::Find::name;
139 for my $file (values %desktops) {
140 my $base = basename($file);
142 # _ is an invalid character for a key, so we can use it for our own keys.
143 $apps{$base}->{_Location} = $file;
145 # Extract all “Name” and “Exec” keys from the [Desktop Entry] group
146 # and store them in $apps{$base}.
148 my $content = slurp($file);
149 next unless defined($content);
150 my @lines = split("\n", $content);
151 for my $line (@lines) {
152 my $first = substr($line, 0, 1);
153 next if $line eq '' || $first eq '#';
154 next unless ($line eq '[Desktop Entry]' ..
156 substr($line, -1) eq ']' &&
157 $line ne '[Desktop Entry]'));
158 next if $first eq '[';
160 my ($key, $value) = ($line =~ /^
162 [A-Za-z0-9-]+ # the spec specifies these as valid key characters
163 (?:\[[^]]+\])? # possibly, there as a locale suffix
165 \s* = \s* # whitespace around = should be ignored
166 (.*) # no restrictions on the values
169 if ($key =~ /^Name/) {
170 $names{$key} = $value;
171 } elsif ($key eq 'Exec' ||
174 $apps{$base}->{$key} = $value;
175 } elsif ($key eq 'NoDisplay' ||
177 $key eq 'StartupNotify' ||
178 $key eq 'Terminal') {
179 # Values of type boolean must either be string true or false,
180 # see “Possible value types”:
181 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s03.html
182 $apps{$base}->{$key} = ($value eq 'true');
186 for my $suffix (@suffixes) {
187 next unless exists($names{"Name[$suffix]"});
188 $apps{$base}->{Name} = $names{"Name[$suffix]"};
192 # Fallback to unlocalized “Name”.
193 $apps{$base}->{Name} = $names{Name} unless exists($apps{$base}->{Name});
196 # %apps now looks like this:
199 # 'evince.desktop' => {
200 # 'Exec' => 'evince %U',
201 # 'Name' => 'Dokumentenbetrachter',
202 # '_Location' => '/usr/share/applications/evince.desktop'
204 # 'gedit.desktop' => {
205 # 'Exec' => 'gedit %U',
207 # '_Location' => '/usr/share/applications/gedit.desktop'
211 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
212 # ┃ Turn %apps inside out to provide Name → filename lookup. ┃
213 # ┃ The Name is what we display in dmenu later. ┃
214 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
217 for my $app (keys %apps) {
218 my $name = $apps{$app}->{Name};
220 # Don’t try to use .desktop files which don’t have Type=application
221 next if (!exists($apps{$app}->{Type}) ||
222 $apps{$app}->{Type} ne 'Application');
224 # Don’t offer apps which have NoDisplay == true or Hidden == true.
225 # See http://wiki.xfce.org/howto/customize-menu#hide_menu_entries
226 # for the difference between NoDisplay and Hidden.
227 next if (exists($apps{$app}->{NoDisplay}) && $apps{$app}->{NoDisplay}) ||
228 (exists($apps{$app}->{Hidden}) && $apps{$app}->{Hidden});
230 if (exists($apps{$app}->{TryExec})) {
231 my $tryexec = $apps{$app}->{TryExec};
232 if (substr($tryexec, 0, 1) eq '/') {
233 # Skip if absolute path is not executable.
234 next unless -x $tryexec;
236 # Search in $PATH for the executable.
238 for my $path (split(':', $ENV{PATH})) {
239 next unless -x "$path/$tryexec";
247 if ($entry_type eq 'name' || $entry_type eq 'both') {
248 if (exists($choices{$name})) {
249 # There are two .desktop files which contain the same “Name” value.
250 # I’m not sure if that is allowed to happen, but we disambiguate the
251 # situation by appending “ (2)”, “ (3)”, etc. to the name.
253 # An example of this happening is exo-file-manager.desktop and
254 # thunar-settings.desktop, both of which contain “Name=File Manager”.
256 $inc++ while exists($choices{"$name ($inc)"});
257 $name = "$name ($inc)";
260 $choices{$name} = $app;
263 if ($entry_type eq 'command' || $entry_type eq 'both') {
264 my ($command) = split(' ', $apps{$app}->{Exec});
266 # Don’t add “geany” if “Geany” is already present.
267 my @keys = map { lc } keys %choices;
268 next if lc(basename($command)) ~~ @keys;
270 $choices{basename($command)} = $app;
274 # %choices now looks like this:
277 # 'Dokumentenbetrachter' => 'evince.desktop',
278 # 'gedit' => 'gedit.desktop'
281 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
282 # ┃ Run dmenu to ask the user for her choice ┃
283 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
285 # open2 will just make dmenu’s STDERR go to our own STDERR.
286 my ($dmenu_out, $dmenu_in);
287 my $pid = open2($dmenu_out, $dmenu_in, $dmenu_cmd);
288 binmode $dmenu_in, ':utf8';
289 binmode $dmenu_out, ':utf8';
291 # Feed dmenu the possible choices.
292 say $dmenu_in $_ for sort keys %choices;
296 my $status = ($? >> 8);
298 # Pass on dmenu’s exit status if there was an error.
299 exit $status unless $status == 0;
301 my $choice = <$dmenu_out>;
302 # dmenu ≥ 4.4 adds a newline after the choice
305 # Exact match: the user chose “Avidemux (GTK+)”
306 if (exists($choices{$choice})) {
307 $app = $apps{$choices{$choice}};
310 # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
311 for my $possibility (keys %choices) {
312 next unless substr($choice, 0, length($possibility)) eq $possibility;
313 $app = $apps{$choices{$possibility}};
314 substr($choice, 0, length($possibility)) = '';
315 # Remove whitespace separating the entry and arguments.
319 if (!defined($app)) {
320 die "Invalid input: “$choice” does not match any application.";
324 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
325 # ┃ Make i3 start the chosen application. ┃
326 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
328 my $name = $app->{Name};
329 my $exec = $app->{Exec};
330 my $location = $app->{_Location};
332 # Quote as described by “The Exec key”:
333 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
336 $str =~ s/("|`|\$|\\)/\\$1/g;
337 $str = qq|"$str"| if $str ne "";
341 $choice = quote($choice);
342 $location = quote($location);
344 # Remove deprecated field codes, as the spec dictates.
345 $exec =~ s/%[dDnNvm]//g;
347 # Replace filename field codes with the rest of the command line.
348 # Note that we assume the user uses precisely one file name,
349 # not multiple file names.
350 $exec =~ s/%[fF]/$choice/g;
352 # If the program works with URLs,
353 # we assume the user provided a URL instead of a filename.
354 # As per the spec, there must be at most one of %f, %u, %F or %U present.
355 $exec =~ s/%[uU]/$choice/g;
357 # The translated name of the application.
358 $exec =~ s/%c/$name/g;
360 # XXX: Icons are not implemented. Is the complexity (looking up the path if
361 # only a name is given) actually worth it?
362 #$exec =~ s/%i/--icon $icon/g;
364 # location of .desktop file
365 $exec =~ s/%k/$location/g;
367 # Literal % characters are represented as %%.
372 if (exists($app->{Terminal}) && $app->{Terminal}) {
373 # For applications which specify “Terminal=true” (e.g. htop.desktop),
374 # we need to create a temporary script that contains the full command line
375 # as the syntax for starting commands with arguments varies from terminal
376 # emulator to terminal emulator.
377 # Then, we launch that script with i3-sensible-terminal.
378 my ($fh, $filename) = tempfile();
379 binmode($fh, ':utf8');
386 chmod 0755, $filename;
388 $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
390 # i3 executes applications by passing the argument to i3’s “exec” command
391 # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
392 # starts with a double quote ("), everything is parsed as-is until the next
393 # double quote which is NOT preceded by a backslash (\).
395 # Therefore, we escape all double quotes (") by replacing them with \"
398 if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
399 $nosn = '--no-startup-id';
401 $cmd = qq|exec $nosn "$exec"|;
404 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
410 i3-dmenu-desktop - run .desktop files with dmenu
414 i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=both]
418 i3-dmenu-desktop is a script which extracts the (localized) name from
419 application .desktop files, offers the user a choice via dmenu(1) and then
420 starts the chosen application via i3 (for startup notification support).
421 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
422 offers B<all> binaries in your $PATH, including non-interactive utilities like
423 "sed". Also, .desktop files contain a proper name, information about whether
424 the application runs in a terminal and whether it supports startup
427 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
428 $HOME/.local/share/applications) and in the "applications" subdirectory of each
429 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
431 Files with the same name in $XDG_DATA_HOME/applications take precedence over
432 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
433 .desktop files by copying them to your local directory and making changes.
435 i3-dmenu-desktop displays the "Name" value in the localized version depending
436 on LC_MESSAGES as specified in the Desktop Entry Specification.
438 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
439 file respectively) by appending it to the name of the application. E.g., if you
440 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
441 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
443 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
445 .desktop files with NoDisplay=true or Hidden=true are skipped.
447 UTF-8 is supported, of course, but dmenu does not support displaying all
448 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
449 fine, but not its Name[ru]=Терминал.
455 =item B<--dmenu=command>
457 Execute command instead of 'dmenu -i'. This option can be used to pass custom
458 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
461 =item B<--entry-type=type>
463 Display the (localized) "Name" (type = name) or the command (type = command) or
464 both (type = both) in dmenu.
466 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
467 command) and both (type = both).
477 Michael Stapelberg, C<< <michael at i3wm.org> >>
479 =head1 LICENSE AND COPYRIGHT
481 Copyright 2012 Michael Stapelberg.
483 This program is free software; you can redistribute it and/or modify it
484 under the terms of the BSD license.