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 $dmenu_cmd = 'dmenu -i';
33 my $result = GetOptions(
34 'dmenu=s' => \$dmenu_cmd,
36 say "dmenu-desktop 1.0 © 2012 Michael Stapelberg";
40 pod2usage(-exitval => 0);
43 die "Could not parse command line options" unless $result;
45 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
46 # ┃ Convert LC_MESSAGES into an ordered list of suffixes to search for in the ┃
47 # ┃ .desktop files (e.g. “Name[de_DE@euro]” for LC_MESSAGES=de_DE.UTF-8@euro ┃
48 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
50 # For details on how the transformation of LC_MESSAGES to a list of keys that
51 # should be looked up works, refer to “Localized values for keys” of the
52 # “Desktop Entry Specification”:
53 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s04.html
54 my $lc_messages = setlocale(LC_MESSAGES);
56 # Ignore the encoding (e.g. .UTF-8)
57 $lc_messages =~ s/\.[^@]+//g;
59 my @suffixes = ($lc_messages);
61 # _COUNTRY and @MODIFIER are present
62 if ($lc_messages =~ /_[^@]+@/) {
63 my $no_modifier = $lc_messages;
64 $no_modifier =~ s/@.*//g;
65 push @suffixes, $no_modifier;
67 my $no_country = $lc_messages;
68 $no_country =~ s/_[^@]+//g;
69 push @suffixes, $no_country;
72 # Strip _COUNTRY and @MODIFIER if present
73 $lc_messages =~ s/[_@].*//g;
74 push @suffixes, $lc_messages;
76 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
77 # ┃ Read all .desktop files and store the values in which we are interested. ┃
78 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
81 # See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
82 my $xdg_data_home = $ENV{XDG_DATA_HOME};
83 $xdg_data_home = $ENV{HOME} . '/.local/share' if
84 !defined($xdg_data_home) ||
85 $xdg_data_home eq '' ||
88 my $xdg_data_dirs = $ENV{XDG_DATA_DIRS};
89 $xdg_data_dirs = '/usr/local/share/:/usr/share/' if
90 !defined($xdg_data_dirs) ||
93 my @searchdirs = ("$xdg_data_home/applications/");
94 for my $dir (split(':', $xdg_data_dirs)) {
95 push @searchdirs, "$dir/applications/";
98 # Cleanup the paths, maybe some application does not cope with double slashes
99 # (the field code %k is replaced with the .desktop file location).
100 @searchdirs = map { s,//,/,g; $_ } @searchdirs;
102 # To avoid errors by File::Find’s find(), only pass existing directories.
103 @searchdirs = grep { -d $_ } @searchdirs;
108 return unless substr($_, -1 * length('.desktop')) eq '.desktop';
109 my $relative = $File::Find::name;
111 # + 1 for the trailing /, which is missing in ::topdir.
112 substr($relative, 0, length($File::Find::topdir) + 1) = '';
114 # Don’t overwrite files with the same relative path, we search in
115 # descending order of importance.
116 return if exists($desktops{$relative});
118 $desktops{$relative} = $File::Find::name;
127 for my $file (values %desktops) {
128 my $base = basename($file);
130 # _ is an invalid character for a key, so we can use it for our own keys.
131 $apps{$base}->{_Location} = $file;
133 # Extract all “Name” and “Exec” keys from the [Desktop Entry] group
134 # and store them in $apps{$base}.
136 my @lines = split("\n", slurp($file));
137 for my $line (@lines) {
138 my $first = substr($line, 0, 1);
139 next if $line eq '' || $first eq '#';
140 next unless ($line eq '[Desktop Entry]' ..
142 substr($line, -1) eq ']' &&
143 $line ne '[Desktop Entry]'));
144 next if $first eq '[';
146 my ($key, $value) = ($line =~ /^
148 [A-Za-z0-9-]+ # the spec specifies these as valid key characters
149 (?:\[[^]]+\])? # possibly, there as a locale suffix
151 \s* = \s* # whitespace around = should be ignored
152 (.*) # no restrictions on the values
155 if ($key =~ /^Name/) {
156 $names{$key} = $value;
157 } elsif ($key eq 'Exec' ||
159 $apps{$base}->{$key} = $value;
160 } elsif ($key eq 'NoDisplay' ||
162 $key eq 'StartupNotify' ||
163 $key eq 'Terminal') {
164 # Values of type boolean must either be string true or false,
165 # see “Possible value types”:
166 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s03.html
167 $apps{$base}->{$key} = ($value eq 'true');
171 for my $suffix (@suffixes) {
172 next unless exists($names{"Name[$suffix]"});
173 $apps{$base}->{Name} = $names{"Name[$suffix]"};
177 # Fallback to unlocalized “Name”.
178 $apps{$base}->{Name} = $names{Name} unless exists($apps{$base}->{Name});
181 # %apps now looks like this:
184 # 'evince.desktop' => {
185 # 'Exec' => 'evince %U',
186 # 'Name' => 'Dokumentenbetrachter',
187 # '_Location' => '/usr/share/applications/evince.desktop'
189 # 'gedit.desktop' => {
190 # 'Exec' => 'gedit %U',
192 # '_Location' => '/usr/share/applications/gedit.desktop'
196 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
197 # ┃ Turn %apps inside out to provide Name → filename lookup. ┃
198 # ┃ The Name is what we display in dmenu later. ┃
199 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
202 for my $app (keys %apps) {
203 my $name = $apps{$app}->{Name};
205 # Don’t offer apps which have NoDisplay == true or Hidden == true.
206 # See http://wiki.xfce.org/howto/customize-menu#hide_menu_entries
207 # for the difference between NoDisplay and Hidden.
208 next if (exists($apps{$app}->{NoDisplay}) && $apps{$app}->{NoDisplay}) ||
209 (exists($apps{$app}->{Hidden}) && $apps{$app}->{Hidden});
211 if (exists($apps{$app}->{TryExec})) {
212 my $tryexec = $apps{$app}->{TryExec};
213 if (substr($tryexec, 0, 1) eq '/') {
214 # Skip if absolute path is not executable.
215 next unless -x $tryexec;
217 # Search in $PATH for the executable.
219 for my $path (split(':', $ENV{PATH})) {
220 next unless -x "$path/$tryexec";
228 if (exists($choices{$name})) {
229 # There are two .desktop files which contain the same “Name” value.
230 # I’m not sure if that is allowed to happen, but we disambiguate the
231 # situation by appending “ (2)”, “ (3)”, etc. to the name.
233 # An example of this happening is exo-file-manager.desktop and
234 # thunar-settings.desktop, both of which contain “Name=File Manager”.
236 $inc++ while exists($choices{"$name ($inc)"});
237 $name = "$name ($inc)";
240 $choices{$name} = $app;
243 # %choices now looks like this:
246 # 'Dokumentenbetrachter' => 'evince.desktop',
247 # 'gedit' => 'gedit.desktop'
250 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
251 # ┃ Run dmenu to ask the user for her choice ┃
252 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
254 # open2 will just make dmenu’s STDERR go to our own STDERR.
255 my ($dmenu_out, $dmenu_in);
256 my $pid = open2($dmenu_out, $dmenu_in, $dmenu_cmd);
257 binmode $dmenu_in, ':utf8';
258 binmode $dmenu_out, ':utf8';
260 # Feed dmenu the possible choices.
261 say $dmenu_in $_ for sort keys %choices;
265 my $status = ($? >> 8);
267 # Pass on dmenu’s exit status if there was an error.
268 exit $status unless $status == 0;
270 my $choice = <$dmenu_out>;
272 # Exact match: the user chose “Avidemux (GTK+)”
273 if (exists($choices{$choice})) {
274 $app = $apps{$choices{$choice}};
277 # Not an exact match: the user entered “Avidemux (GTK+) ~/movie.mp4”
278 for my $possibility (keys %choices) {
279 next unless substr($choice, 0, length($possibility)) eq $possibility;
280 $app = $apps{$choices{$possibility}};
281 substr($choice, 0, length($possibility)) = '';
282 # Remove whitespace separating the entry and arguments.
286 if (!defined($app)) {
287 die "Invalid input: “$choice” does not match any application.";
291 # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
292 # ┃ Make i3 start the chosen application. ┃
293 # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
295 my $name = $app->{Name};
296 my $exec = $app->{Exec};
297 my $location = $app->{_Location};
299 # Quote as described by “The Exec key”:
300 # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
303 $str =~ s/("|`|\$|\\)/\\$1/g;
304 $str = qq|"$str"| if $str ne "";
308 $choice = quote($choice);
309 $location = quote($location);
311 # Remove deprecated field codes, as the spec dictates.
312 $exec =~ s/%[dDnNvm]//g;
314 # Replace filename field codes with the rest of the command line.
315 # Note that we assume the user uses precisely one file name,
316 # not multiple file names.
317 $exec =~ s/%[fF]/$choice/g;
319 # If the program works with URLs,
320 # we assume the user provided a URL instead of a filename.
321 # As per the spec, there must be at most one of %f, %u, %F or %U present.
322 $exec =~ s/%[uU]/$choice/g;
324 # The translated name of the application.
325 $exec =~ s/%c/$name/g;
327 # XXX: Icons are not implemented. Is the complexity (looking up the path if
328 # only a name is given) actually worth it?
329 #$exec =~ s/%i/--icon $icon/g;
331 # location of .desktop file
332 $exec =~ s/%k/$location/g;
334 # Literal % characters are represented as %%.
339 if (exists($app->{Terminal}) && $app->{Terminal}) {
340 # For applications which specify “Terminal=true” (e.g. htop.desktop),
341 # we need to create a temporary script that contains the full command line
342 # as the syntax for starting commands with arguments varies from terminal
343 # emulator to terminal emulator.
344 # Then, we launch that script with i3-sensible-terminal.
345 my ($fh, $filename) = tempfile();
346 binmode($fh, ':utf8');
353 chmod 0755, $filename;
355 $cmd = qq|exec i3-sensible-terminal -e "$filename"|;
357 # i3 executes applications by passing the argument to i3’s “exec” command
358 # as-is to $SHELL -c. The i3 parser supports quoted strings: When a string
359 # starts with a double quote ("), everything is parsed as-is until the next
360 # double quote which is NOT preceded by a backslash (\).
362 # Therefore, we escape all double quotes (") by replacing them with \"
365 if (exists($app->{StartupNotify}) && !$app->{StartupNotify}) {
366 $nosn = '--no-startup-id';
368 $cmd = qq|exec $nosn "$exec"|;
371 system('i3-msg', $cmd) == 0 or die "Could not launch i3-msg: $?";
377 i3-dmenu-desktop - run .desktop files with dmenu
381 i3-dmenu-desktop [--dmenu='dmenu -i']
385 i3-dmenu-desktop is a script which extracts the (localized) name from
386 application .desktop files, offers the user a choice via dmenu(1) and then
387 starts the chosen application via i3 (for startup notification support).
388 The advantage of using .desktop files instead of dmenu_run(1) is that dmenu_run
389 offers B<all> binaries in your $PATH, including non-interactive utilities like
390 "sed". Also, .desktop files contain a proper name, information about whether
391 the application runs in a terminal and whether it supports startup
394 The .desktop files are searched in $XDG_DATA_HOME/applications (by default
395 $HOME/.local/share/applications) and in the "applications" subdirectory of each
396 entry of $XDG_DATA_DIRS (by default /usr/local/share/:/usr/share/).
398 Files with the same name in $XDG_DATA_HOME/applications take precedence over
399 files in $XDG_DATA_DIRS, so that you can overwrite parts of the system-wide
400 .desktop files by copying them to your local directory and making changes.
402 i3-dmenu-desktop displays the "Name" value in the localized version depending
403 on LC_MESSAGES as specified in the Desktop Entry Specification.
405 You can pass a filename or URL (%f/%F and %u/%U field codes in the .desktop
406 file respectively) by appending it to the name of the application. E.g., if you
407 want to launch "GNU Emacs 24" with the patch /tmp/foobar.txt, you would type
408 "emacs", press TAB, type " /tmp/foobar.txt" and press ENTER.
410 .desktop files with Terminal=true are started using i3-sensible-terminal(1).
412 .desktop files with NoDisplay=true or Hidden=true are skipped.
414 UTF-8 is supported, of course, but dmenu does not support displaying all
415 glyphs. E.g., xfce4-terminal.desktop's Name[fi]=Pääte will be displayed just
416 fine, but not its Name[ru]=Терминал.
422 =item B<--dmenu=command>
424 Execute command instead of 'dmenu -i'. This option can be used to pass custom
425 parameters to dmenu, or to make i3-dmenu-desktop start a custom (patched?)
436 Michael Stapelberg, C<< <michael at i3wm.org> >>
438 =head1 LICENSE AND COPYRIGHT
440 Copyright 2012 Michael Stapelberg.
442 This program is free software; you can redistribute it and/or modify it
443 under the terms of the BSD license.