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>;
291 # Exact match: the user chose “Avidemux (GTK+)”
292 if (exists($choices{$choice})) {
293 $app = $apps{$choices{$choice}};
296 # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
297 for my $possibility (keys %choices) {
298 next unless substr($choice, 0, length($possibility)) eq $possibility;
299 $app = $apps{$choices{$possibility}};
300 substr($choice, 0, length($possibility)) = '';
301 # Remove whitespace separating the entry and arguments.
305 if (!defined($app)) {
306 die "Invalid input: “$choice” does not match any application.";
310 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
311 # ┃ Make i3 start the chosen application. ┃
312 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
314 my $name = $app->{Name};
315 my $exec = $app->{Exec};
316 my $location = $app->{_Location};
318 # Quote as described by “The Exec key”:
319 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
322 $str =~ s/("|`|\$|\\)/\\$1/g;
323 $str = qq|"$str"| if $str ne "";
327 $choice = quote($choice);
328 $location = quote($location);
330 # Remove deprecated field codes, as the spec dictates.
331 $exec =~ s/%[dDnNvm]//g;
333 # Replace filename field codes with the rest of the command line.
334 # Note that we assume the user uses precisely one file name,
335 # not multiple file names.
336 $exec =~ s/%[fF]/$choice/g;
338 # If the program works with URLs,
339 # we assume the user provided a URL instead of a filename.
340 # As per the spec, there must be at most one of %f, %u, %F or %U present.
341 $exec =~ s/%[uU]/$choice/g;
343 # The translated name of the application.
344 $exec =~ s/%c/$name/g;
346 # XXX: Icons are not implemented. Is the complexity (looking up the path if
347 # only a name is given) actually worth it?
348 #$exec =~ s/%i/--icon $icon/g;
350 # location of .desktop file
351 $exec =~ s/%k/$location/g;
353 # Literal % characters are represented as %%.
358 if (exists($app->{Terminal}) && $app->{Terminal}) {
359 # For applications which specify “Terminal=true” (e.g. htop.desktop),
360 # we need to create a temporary script that contains the full command line
361 # as the syntax for starting commands with arguments varies from terminal
362 # emulator to terminal emulator.
363 # Then, we launch that script with i3-sensible-terminal.
364 my ($fh, $filename) = tempfile();
365 binmode($fh, ':utf8');
372 chmod 0755, $filename;
374 $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
376 # i3 executes applications by passing the argument to i3’s “exec” command
377 # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
378 # starts with a double quote ("), everything is parsed as-is until the next
379 # double quote which is NOT preceded by a backslash (\).
381 # Therefore, we escape all double quotes (") by replacing them with \"
384 if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
385 $nosn = '--no-startup-id';
387 $cmd = qq|exec $nosn "$exec"|;
390 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
396 i3-dmenu-desktop - run .desktop files with dmenu
400 i3-dmenu-desktop [--dmenu='dmenu -i'] [--entry-type=both]
404 i3-dmenu-desktop is a script which extracts the (localized) name from
405 application .desktop files, offers the user a choice via dmenu(1) and then
406 starts the chosen application via i3 (for startup notification support).
407 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
408 offers B<all> binaries in your $PATH, including non-interactive utilities like
409 "sed". Also, .desktop files contain a proper name, information about whether
410 the application runs in a terminal and whether it supports startup
413 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
414 $HOME/.local/share/applications) and in the "applications" subdirectory of each
415 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
417 Files with the same name in $XDG_DATA_HOME/applications take precedence over
418 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
419 .desktop files by copying them to your local directory and making changes.
421 i3-dmenu-desktop displays the "Name" value in the localized version depending
422 on LC_MESSAGES as specified in the Desktop Entry Specification.
424 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
425 file respectively) by appending it to the name of the application. E.g., if you
426 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
427 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
429 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
431 .desktop files with NoDisplay=true or Hidden=true are skipped.
433 UTF-8 is supported, of course, but dmenu does not support displaying all
434 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
435 fine, but not its Name[ru]=Терминал.
441 =item B<--dmenu=command>
443 Execute command instead of 'dmenu -i'. This option can be used to pass custom
444 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
447 =item B<--entry-type=type>
449 Display the (localized) "Name" (type = name) or the command (type = command) or
450 both (type = both) in dmenu.
452 Examples are "GNU Image Manipulation Program" (type = name), "gimp" (type =
453 command) and both (type = both).
463 Michael Stapelberg, C<< <michael at i3wm.org> >>
465 =head1 LICENSE AND COPYRIGHT
467 Copyright 2012 Michael Stapelberg.
469 This program is free software; you can redistribute it and/or modify it
470 under the terms of the BSD license.