aboutsummaryrefslogtreecommitdiff
path: root/open-file
blob: 8b23dcc2f0c1e8621fc14a147d229d68b830f852 (plain)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/bin/sh

# Inspired by https://github.com/salman-abedin/launch.sh
# Launches files based on their mimetypes
# Requires: dmenu_path or similar (fallback), dmenu-filepicker

# Usage: open-file [-m menu] [-s launcher] [-t mimetype] [files...]

menu="dmenu -i -l 15"

# Change default apps here
video=${VIDEO:-vlc}
music=${MUSIC:-vlc}
pdf=${PDF:-zathura}
img="nsxiv"
word="libreoffice"
sheet="libreoffice"
html="firefox --new-window"
xedit="xedit"

usage() {
	echo "Usage: open-file [-m MENU] [-s LAUNCHER] [-t MIMETYPE] [files...]"
}

openfile() {
	f="$*"
	localmime="$mimetype"

	[ ! -f "$f" ] && echo "$f: bad argument" && exit 1
	[ -z "$mimetype" ] && localmime="$(file --mime-type "$f" -bL)"

	prog=""
	case "$localmime" in
		video/*)
			prog="$video"
			;;
		audio/*)
			prog="$music"
			;;
		application/pdf | application/postscript | image/vnd.djvu)
			prog="$pdf"
			;;
		image/*)
			prog="$img"
			;;
		application/msword | \
		application/vnd.oasis.opendocument.text | text/rtf | \
		application/vnd.openxmlformats-officedocument.wordprocessingml.*)
			prog="$word"
			;;
		application/ms-excel | \
		application/vnd.oasis.opendocument.spreadsheet | \
		application/vnd.openxmlformats-officedocument.spreadsheetml.*)
			prog="$sheet"
			;;
		text/html | text/enriched)
			prog="$html"
			;;
		text/*)
			prog="$xedit"
			;;
		application/zip)
			prog="unzip"
			;;
		application/x-rar-compressed)
			prog="unrar"
			;;
		application/x-archive | application/x-tar | \
		application/x-bzip2 | application/gzip | application/x-lzip | \
		application/x-lzma | application/x-xz | application/x-gtar)
			prog="tar -tavf"
			;;
		application/java-archive)
			prog="java -jar"
			;;
		*)
			if [ "$menu" = dmenu ]; then
				menuprompt="-p \"How to open $f? \""
			else
				menuprompt="--prompt=\"How to open $f? \""
			fi
			prog=$(dmenu_path | $menu "$menuprompt")
			;;
	esac

	if [ -n "$prog" ]; then
		$launcher $prog "$f"
	else
		exit 1
	fi
}

while getopts "m:s:t:" opt; do
	case "$opt" in
		m)
			menu="$OPTARG"
			;;
		s)
			launcher="$OPTARG"
			;;
		t)
			mimetype="$OPTARG"
			;;
		*)
			usage
			exit 1
			;;
	esac
done

shift $((OPTIND - 1))

if [ -n "$1" ]; then
	while [ -n "$1" ]; do
		openfile "$1" &
		shift
	done
else
	dmenu-filepicker -m "$menu" | while read -r line; do
		openfile "$line" &
	done
fi

Generated with cgit - Back to sebastiano.tronto.net