summary refs log tree commit diff
path: root/bin/iconez
blob: 104158ef8e0f15d65a58391a1fa108eb6d76b42c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/sh

set -e
[ -n "$DEBUG" ] && set -x

by_pid=
by_name=
fuzzy=
desktop_files=
scalable=
while getopts n:p:dfsh opt; do
	case "$opt" in
	n) by_name="${OPTARG}" ;;
	p) by_pid="${OPTARG}" ;;
	f) fuzzy=1 ;;
	d) desktop_files=1 ;;
	s) scalable=1 ;;
	h | ?)
		printf "usage: %s [-h]\n" "$(basename "$0")"
		printf "\n"
		printf "  -p \t PID\n"
		printf "  -n \t NAME\n"
		printf "  -f \t enable fuzzy matching (NAME only)\n"
		printf "  -d \t try to match NAME desktop file\n"
		printf "  -s \t only match scalable icons\n"
		printf "\n"
		exit 2
		;;
	esac
done
shift $((OPTIND - 1))

desktop_dirs="/usr/share/applications/ /usr/local/share/applications/"
icon_dirs="/usr/share/icons/ /usr/local/share/icons/"

by_name() {
	name=$1

	if [ -n "${desktop_files}" ]; then
		[ -z "${fuzzy}" ] && name="^${name}$"
		# try getting .desktop entry for name
		# shellcheck disable=2086
		ident=$(fd -e desktop "${name}" ${desktop_dirs} -x grep Icon= | cut -d= -f2 | uniq)
	fi

	if [ -z "${fuzzy}" ]; then
		ident="^${ident:-$name}\."
	else
		ident="${ident:-$name}"
	fi

	filetypes="-e svg"
	if [ -z "${scalable}" ]; then
		filetypes="${filetypes} -e png"
	fi

	# shellcheck disable=2086
	fd -t f ${filetypes} "${ident}" ${icon_dirs}

	# avoid selecting svg, can be made to prefer svg if `-v` is removed
	# svg=$(printf "%s" "${icons}" | grep -v svg)
	# [ -n "${svg}" ] && icons=${svg}

	# printf "%s\n" "${icons}"
}

by_pid() {
	pid=$1

	arg0=
	while true; do
		arg0=$(awk '{print $1}' /proc/"${pid}"/comm)
		case ${arg0} in
		*sh)
			pid=$(ps -p "${pid}" -o ppid= | xargs)
			[ "$pid" = 1 ] && exit 1
			;;
		*) break ;;
		esac
	done

	by_name "${arg0}"
}

# main
if [ -n "${by_name}" ]; then
	by_name "${by_name}"

elif [ -n "${by_pid}" ]; then
	by_pid "${by_pid}"

fi