1#autoload
2
3_mac_rsrc_check() {
4  [[ ! -s "$REPLY/..namedfork/rsrc" ]] && return 1
5  if [[ -x /Developer/Tools/GetFileInfo ]]; then
6    local ftype="$(command /Developer/Tools/GetFileInfo -t $REPLY)"
7    ftype="${ftype//\"/}"
8    [[ -n "$types[(r)$ftype]" ]]
9  else
10      grep --quiet "\(${(j/\|/)types}\)" "$REPLY/..namedfork/rsrc"
11  fi
12}
13
14_mac_parse_info_plist() {
15  # For now, awk is used because builtin function "read" was too slow.
16  # '<' is used for the delimiter because some Info.plist files use CR as
17  # newline but read doesn't treat them as so
18  local s='
19    BEGIN { RS="<" }
20      /^key>/ { sub(/key>/, ""); reading_key=$0 }
21      /^string>/ {
22        sub(/string>/, "")
23        if (reading_key == "CFBundleTypeExtensions") exts=exts " \"" $0 "\""
24        if (reading_key == "CFBundleTypeOSTypes") types=types " \"" $0 "\""
25      }
26      END {
27        print "exts=(" exts ")\ntypes=(" types ")"
28      }
29    '
30    command awk $s "$app_path/Contents/Info.plist" | while read; do
31      eval "$REPLY"
32    done
33}
34
35# Try to complete files for the specified application.
36_mac_files_for_application() {
37  local -a opts
38  zparseopts -D -a opts q n 1 2 P: S: r: R: W: X+: M+: F: J+: V+:
39
40  local app_path
41  _retrieve_mac_apps
42  app_path="${_mac_apps[(r)*/$1(|.app)]:-$1}"
43
44  local -a glob_patterns
45  glob_patterns=()
46
47  # Try to get extentions from "Info.plist" XML file.
48  if [[ -f "$app_path/Contents/Info.plist" ]]; then
49    local -a exts types
50    _mac_parse_info_plist
51
52    if [[ -n "$exts[(r)\*]" ]]; then
53      glob_patterns=( "*" )
54    else
55      if (( #exts != 0 )); then
56        glob_patterns+=( "*.(${(j/|/)exts})(N)" )
57      fi
58
59      if (( #types != 0 )); then
60        glob_patterns+=( "^*.[[:alnum:]]##(.Ne:_mac_rsrc_check:)" )
61      fi
62    fi
63  else
64    glob_patterns=( "*" )
65  fi
66
67  case ${#glob_patterns} in
68    0) return 1 ;;
69    1) _files "$opts[@]" -g "$glob_patterns[1]" ;;
70    *) _files "$opts[@]" -g "{${(j/,/)glob_patterns}}" ;;
71  esac
72}
73
74_mac_files_for_application "$@"
75