-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenwith
584 lines (524 loc) · 18.1 KB
/
openwith
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#!/bin/bash
#
# MADE BY twix https://github.com/Twix53791/openwith-fzf
#=======================================================
# This script is intended to:
# 1) returns the default application associated
# with a file type (-d flag)
# 2) displays a fzf menu to choose dynamically
# an application to open a file, throught a
# list of potential applications, according
# to the file(s) type(s)
#
# - The -d flag returns (echo) the default application
# associated to the file(s) passed as argument.
# For EACH file it returns the default program
# associated with.
# openwith -d test.odt toto.pdf -> libreoffice zathura
#
# - The -m flag allows the output of -d option to print as first
# argument the number 1 if, in the range of files given as argument
# several different file types are found.
# openwith -dm toto.sh tata.pdf titi -> 1 nano zathura zathura
#
# - Without the -d flag, openwith displays a fzf menu to choose
# the application with which to open the file.
#
# It accepts MANY files as arguments, virtually an infinite number.
# The setting 'maxargs' set a limit above which openwith will not
# check any argument, to avoid mistakes...
# By default, it is set to 100. But openwith is still fast
# for hundreds, even thousands of files, at least the _deepcheck
# function is not executed on a such number of files.
# _extcheck on 200 files: 0.040 s; _deepcheck on 50 files: 0.200
# Of course, opening a such number of files with an application is
# another ball of wax...
#
#:::::::::::::::::::::: WARNING :::::::::::::::::::::::::
#
# This script is part of my personnal desktop setting.
# It's 'amateur' and it has been tested only in my
# configuration (arch linux + bspwm).
# I do not guarantee its stability !!!
# Feel free to improve it!
#
#::: SET YOUR DEFAULT APPLICATIONS ::::::::::::::::::::::
#
# 1) in the _applist function, see the section below,
# associate your application with a variable
# ex: [[ $gi == 1)) && applist+="gimp\n"
# The syntax have to be that one, 'gimp' is the real
# name of the program, which will be taken as a command
# to run to open the files.
# If you want to display a different name in the fzf menu
# than the command run, set in _applist the custom name, then
# use the _command function to set the command associated with
# this name.
# 2) Edit or create the variables in the 'ASSOCIATED
# APPLICATIONS' below.
# ex: image='gi=1 && no=1 && echo 'nomacs''
# will set the category 'image', for which the default
# application is nomacs (echo nomacs) and the possible
# others applications, to display in the fzf menu, are
# gimp (gi variable) and also nomacs (no=1). You can add
# here as much as you want of "associated applications",
# but of course only one "default".
# 3) To associate the category 'image' with a file type,
# edit the _extcheck function (checks file extension)
# and the _deepcheck function (checks by mime type).
# ex:
# in _extcheck:
# elif [[ $file == *.jpg ]];then eval $image
# associates files ending by .jpg to the category 'image'
# in _deepcheck:
# case $ftype in
# jpeg) eval $image;;
#
#:::::::::: DEPENDENCIES ::::::::::::::::::::::::::::::::
# fzf
# openrule is used by default, but you can desactivate it
# see below, the _openwithfzf function
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# TIPS : Check all file extensions in a dir and subdirs:
# for file in $(find); do echo "${file##*\.}";done
# l='';for f in $(find); do e=$(echo "${f##*\.}");[[ $(echo ${#e}) -lt 7 ]] && t=$e;[[ "$l" != *"$t"* ]] && echo "$t | $f";l+="$t "; done
# BUT if the file has no ext, it returns its name...
#
# TIPS : echo all file types in a dir and subdirs¬:
# l='';for f in $(find); do t=$(file -Lb --mime-type "$f" | cut -d' ' -f1);[[ "$l" != *"$t"* ]] && echo "$t | $f";l+="$t "; done
#
# DEBUG/TEST IT: openwith -d $(echo "$(fd | cut -b3-)")
#
#============================================================
#=== Settings ===============================================
#============================================================
## Set this value to a max, to avoid executing file command
# on large number of files, slowing the all process.
# Setting it to 0 disables the "deep check" completely
# maxargs have to be higher or equal to make it effective
maxdeepcheck=50
## To avoid any CPU bolting
maxargs=100
## Set alphabetic sort
alphsort=1
## Choose the 'opening' method
openmethod='openrule'
#openmethod='default'
#openmethod='machinegun'
## Warning messages file location
logfile="/tmp/openwithlog"
## Enable files count/warning messages fzf preview display
warningmsg=1
filescount=1
## Files counts color
export OWFCOLOR="\e[35m"
## Set the fzf default options
# In my case, there are set in bashrc
source ~/.bashrc
#export FZF_DEFAULT_OPTS='the default options you want'
#======= List of the variables below ===========================
# (not necessary, but well to visualize here all app variables)
at=0 # atom
da=0 # darktable
em=0 # emacs
fir=0 # firefox
fo=0 # fontmatrix
gi=0 # gimp
li=0 # litemdview
lo=0 # libreoffice
na=0 # nano
no=0 # nomacs
za=0 # zathura
si=0 # sioyek
vl=0 # vlc
#=========== SET HERE THE ASSOCIATED APPLICATIONS ==============
# The names of the variables can be anything you want. Nothing
# related to the file type or extension.
md='em=1 && lo=1 && at=1 && na=1 && li=1 && echo 'litemdview''
pdf='em=1 && za=1 && si=1 && fir=1 && echo 'zathura''
epub='za=1 && echo 'zathura''
djvu='za=1 && echo 'zathura''
html='em=1 && na=1 && at=1 && lo=1 && fir=1 && echo 'nano''
json='fi=1 && em=1 && at=1 && lo=1 && na=1 && echo 'emacs''
nef='da=1 && no=1 && echo 'darktable''
svg='em=1 && gi=1 && no=1 && echo 'gimp''
gif='gi=1 && no=1 && echo 'nomacs''
libreoffice='lo=1 && echo 'libreoffice''
gimp='gi=1 && echo 'gimp''
darktable='da=1 && echo 'darktable''
emacs='em=1 && echo 'emacs''
zathura='za=1 && echo 'zathura''
genericimage='em=1 && da=1 && gi=1 && no=1 && echo 'nomacs''
rareimage='gi=1 && da=1 && echo 'gimp''
image='da=1 && gi=1 && no=1 && echo 'nomacs''
video='vl=1 && ha=1 && echo 'vlc''
text='na=1 && em=1 && at=1 && lo=1 && echo nano'
officedoc='lo=1 && em=1 && echo 'libreoffice''
unknown='na=1 && echo 'nano''
#============ APPLICATIONS LIST ================================
# Set here the applications associated with the variables above
#### Set the apps list ###
# The order is important, as it will set the order of the fzf menu
# but if "alphabetic sort" is used
# Footer is a fixed list always display at the end ot the fzf menu
_applist (){
((gi==1)) && applist+="gimp\n"
((da==1)) && applist+="darktable\n"
((ha==1)) && applist+="handbrake\n"
((vl==1)) && applist+="vlc\n"
((em==1)) && applist+="emacs\n"
((at==1)) && applist+="atom\n"
((lo==1)) && applist+="libreoffice\n"
((si==1)) && applist+="sioyek\n"
((za==1)) && applist+="zathura\n"
((fir==1)) && applist+="firefox\n"
((no==1)) && applist+="nomacs\n"
((li==1)) && appalist+="litemdview\n"
((fo==1)) && applist+="fontmatrix\n"
((na==1)) && applist+="nano\n"
# Footer = applications always part of the list,
# for any file type
[[ -z $applist ]] && footer="dragon-drop" ||
footer="\ndragon-drop"
}
# Use this to execute a different command than the one
# displayed in the fzf menu
_command (){
case $1 in
handbrake) echo "ghb";;
*) echo "$1";;
esac
}
#===============================================================
#=============== FUNCTIONS =====================================
#===============================================================
_deepcheck (){
for file in "${@:1:${maxdeepcheck}}"; do
mime=$(file -Lb --mime-type "$file")
mtype=${mime%%/*}
ftype=${mime##*/}
# Set here rules responding to file types
case $ftype in
pdf) eval $pdf;;
epub) eval $epub;;
vnd.djvu) eval $djvu;;
vnd.djvu+multipage) eval $djvu;;
ogg) eval $video;;
mpeg4-iod) eval $video;;
mpeg4-muxcodetable) eval $video;;
jpeg) eval $image;;
vnd.openxmlformats-officedocument.wordprocessingml.document) eval $officedoc;;
vnd.oasis.opendocument.text) eval $officedoc;;
vnd.oasis.opendocument.text-template) eval $libreoffice;;
vnd.oasis.opendocument.presentation) eval $officedoc;;
vnd.openxmlformats-officedocument.spreadsheetml.sheet) eval $officedoc;;
vnd.ms-excel) eval $officedoc;;
msword) eval $officedoc;;
excel) eval $libreoffice;;
msexcel) eval $libreoffice;;
mspowerpoint) eval $libreoffice;;
rtf) eval $libreoffice;;
ppt) eval $emacs;;
csv) eval $officedoc;;
plain) eval $text;;
json) eval $json;;
x-empty) eval $text;;
*) ftype=0;;
esac
# Set here general rules to mime types, if no file type is found above
if [[ $ftype == 0 ]];then
case $mtype in
image) eval $image;;
video) eval $video;;
application) eval $text;;
text) eval $text;;
*) eval $unknown;;
esac
fi
# Check if there are differents file types
[[ -f $exttmp ]] && ext=$(cat $exttmp) &&
[[ "$ext" != "$mime" ]] && ext=1
if [[ -z $ext ]]; then
ext=$mime
elif [[ $ext != 1 ]]; then
[[ $ext != $mime ]] && ext=1
fi
done
[[ $ext == 1 ]] && echo -n 111
}
_extcheck (){
fcount=0
for file in "${@:1:${maxargs}}";do
if [[ -f $file ]]; then
((fcount++))
# Checks if there are different files types
fname="${file##*/}"
if [[ $fname == *.* ]]; then
if [[ -z $ext ]]; then
match="${fname##*.}"
matchtype=$(file -Lb --mime-type "$file")
((${#match} <= 5)) && ext=$match
elif [[ $ext != 1 ]]; then
[[ $ext != "${fname##*\.}" ]] && ext=1
fi
fi
# Set the applist according to the file extensions finded
### Main used files on my desktop ###
if [[ $file == *.pdf ]];then eval $pdf
elif [[ $file == *.jpg ]];then eval $genericimage
elif [[ $file == *.png ]];then eval $genericimage
elif [[ $file == *.NEF ]];then eval $nef
elif [[ $file == *.mp4 ]];then eval $video
elif [[ $file == *.mkv ]];then eval $video
elif [[ $file == *.avi ]];then eval $video
elif [[ $file == *.svg ]];then eval $svg
elif [[ $file == *.md ]];then eval $md
elif [[ $file == *.txt ]];then eval $text
elif [[ $file == *.sh ]];then eval $text
elif [[ $file == *.zsh ]];then eval $text
elif [[ $file == *.py ]];then eval $text
elif [[ $file == *.html ]];then eval $html
elif [[ $file == *.djvu ]];then eval $zathura
elif [[ $file == *.cbz ]];then eval $zathura
elif [[ $file == *.cbr ]];then eval $zathura
elif [[ $file == *.odt ]];then eval $officedoc
elif [[ $file == *.doc ]];then eval $officedoc
elif [[ $file == *.docx ]];then eval $officedoc
### rare text/code files ###
elif [[ $file == *.xml ]];then eval $text
elif [[ $file == *.log ]];then eval $text
elif [[ $file == *.ini ]];then eval $text
elif [[ $file == *.yml ]];then eval $text
elif [[ $file == *.yaml ]];then eval $text
elif [[ $file == *.conf ]];then eval $text
elif [[ $file == *.toml ]];then eval $text
elif [[ $file == *.backup ]];then eval $text
elif [[ $file == *.config ]];then eval $text
### rare image files ###
elif [[ $file == *.jpeg ]];then eval $genericimage
elif [[ $file == *.gif ]];then eval $gif
elif [[ $file == *.ico ]];then eval $genericimage
elif [[ $file == *.raf ]];then eval $image
elif [[ $file == *.rw2 ]];then eval $image
elif [[ $file == *.bmp ]];then eval $image
elif [[ $file == *.dng ]];then eval $image
elif [[ $file == *.jps ]];then eval $image
elif [[ $file == *.jpe ]];then eval $image
elif [[ $file == *.nrw ]];then eval $image
elif [[ $file == *.orf ]];then eval $image
elif [[ $file == *.pam ]];then eval $image
elif [[ $file == *.pbm ]];then eval $image
elif [[ $file == *.pcd ]];then eval $image
elif [[ $file == *.pef ]];then eval $image
elif [[ $file == *.xcf ]];then eval $gimp
elif [[ $file == *.webp ]];then eval $gimp
elif [[ $file == *.jp2 ]];then eval $gimp
elif [[ $file == *.dds ]];then eval $gimp
elif [[ $file == *.fts ]];then eval $gimp
elif [[ $file == *.heif ]];then eval $gimp
elif [[ $file == *.ras ]];then eval $gimp
elif [[ $file == *.sgi ]];then eval $gimp
elif [[ $file == *.xbm ]];then eval $gimp
elif [[ $file == *.xwd ]];then eval $gimp
elif [[ $file == *.heic ]];then eval $rareimage
elif [[ $file == *.exr ]];then eval $rareimage
elif [[ $file == *.tiff ]];then eval $rareimage
elif [[ $file == *.pfm ]];then eval $rareimage
elif [[ $file == *.hdr ]];then eval $rareimage
elif [[ $file == *.erf ]];then eval $darktable
elif [[ $file == *.mng ]];then eval $darktable
elif [[ $file == *.x3f ]];then eval $darktable
elif [[ $file == *.cr2 ]];then eval $darktable
### If all test failed - unknown (and execute deep check) ###
else unknownlist+=("$file") && echo 000
fi
args+=("$file")
elif [[ -d $file ]]; then
args+=("$file") && echo dragon-drop
[[ -z $dir ]] && echo "WARNING : a directory is selected!" >> $logfile && dir=1
fi
done
[[ $ext != 1 ]] && ext=$matchtype
if [[ $default == 1 && ! -z $unknownlist ]]; then
[[ $ext == 1 ]] && echo -n 111 || echo $ext > $exttmp
for el in "${unknownlist[@]}"; do
echo "$el" >> $ufile
done
fi
}
_appsource(){
# Get the tree of PPID ancestors
pid=$$
until [[ -z $pid ]]; do
pid=$(ps -o ppid= $pid | tr -d ' ')
((pid == 1 )) && pid='' # needed to do not ask ppid of 0 pid
ancestors+="$pid "
done
# Is any of these processus running?
istabbed=$(pgrep tabbed)
dtpipe=$(pgrep dtpipe.sh)
# Checks, for each process, if it exists, if $$ is a child
if [[ ! -z $dtpipe ]]; then
for id in $dtpipe; do
[[ $ancestors == *$id* ]] && echo 'dtpipe' && break
done
fi
if [[ ! -z $istabbed ]]; then
for id in $istabbed; do
[[ $ancestors == *$id* ]] && echo 'tabbed' && break
done
fi
}
# Function executed when -d flag is passed
_get_default_app (){
default=1
app=$(_extcheck "$@")
if [[ -f $ufile ]]; then
mapfile -t deepfiles < $ufile
deep=$(_deepcheck "${deepfiles[@]}")
fi
if [[ $app == *111* || $deep == *111* ]]; then
((multiple == 1)) && echo 1
fi
app=${app/111}; deep=${deep/111}
# Reconstruct an unique list, if $deep exists
if [[ -f $ufile ]]; then
for el in $deep; do
app=${app/000/$el}
done
fi
echo "$app"
}
# Draw the fzf menu
_fzf_menu (){
_applist
#### Sorting ###
if ((alphsort == 1 ));then
fzflist="$(echo -en "$applist" | sort)$(echo -en "$footer")"
else
fzflist="$(echo -en "$applist")$(echo -en "$footer")"
fi
#### Warning if multiple file types
if [[ $ext == 1 ]]; then
echo "WARNING : multiple file types." >> $logfile
echo "Opening in an application an unsupported file type could create an error" >> $logfile
fi
((filescount == 1)) && export OWCOUNT=" files : $fcount"
((warningmsg == 1)) && export OWLOGFILE=$logfile
#### Fzf menu ###
[[ ! -f $logfile ]] && touch $logfile
if [[ $warningmsg = 1 && ! -z $(cat $logfile) || $filescount = 1 ]]; then
output=$(echo -en "$fzflist" | fzf \
--preview 'echo -e "$OWFCOLOR$OWCOUNT\e[0m"; cat $OWLOGFILE' \
--color='preview-fg:160' --preview-window="60%:wrap")
else
output=$(echo -en "$fzflist" | fzf)
fi
[[ -z $output ]] && exit
# Possible fzf options, if not configured by default with FZF_DEFAULT_OPTS:
# fzf --reverse +m
}
# Open the files selected in the fzf menu
_open (){
# I use here my own script,
# but you can use your own
# NOTE : if the app opens in the terminal, use & to run
# the script in the background seems buggy (CPU freeze)
cmd=$(_command "$output")
appsource=$(_appsource)
if [[ $appsource == dtpipe ]]; then
if [[ $cmd == nano ]]; then
openrule -k nano "${args[@]}"
else
openrule -d $cmd "${args[@]}" &
fi
elif [[ $appsource == tabbed ]]; then
for file in "${args[@]}"; do
echo "$file" >> $opwfile
done
[[ $cmd != nano ]] &&
echo "openwith $cmd" > $totabbed
echo "$(<$opwfile)"
else
if [[ $cmd == nano ]]; then
nano "${args[@]}"
else
openrule -d $cmd "${args[@]}" &
fi
fi
}
_default_open (){
$cmd "${args[@]}"
}
_machinegun_open (){
for file in "${args[@]}"; do
$cmd "$file" &
done
}
_init (){
# Init files
opwfile="/tmp/openwithoutput"
totabbed="/tmp/openwithtotabbed"
fzfpfile="/tmp/fzfzpreview"
ufile="/tmp/openwith_unknownlist"
exttmp="/tmp/openwithext"
[[ -f $totabbed ]] && rm $totabbed
# Fix a bug (https://unix.stackexchange.com/questions/503111/group-permissions-for-root-not-working-in-tmp)
if (($EUID == 0)); then
[[ ! -O $fzfpfile ]] && rm $fzfpfile && touch $fzfpfile && chmod a=rwx $fzfpfile
fi
}
_exit (){
[[ -f $opwfile ]] && rm $opwfile
[[ -f $logfile ]] && rm $logfile
[[ -f $ufile ]] && rm $ufile
[[ -f $exttmp ]] && rm $exttmp
# Echo 'open to fzfzpreview triggers the disapearance of the drop_pipe_term
echo "mode = open " > $fzfpfile
}
_openwithfzf (){
_init
_extcheck "$@" 1>/dev/null
[[ -z $args ]] && echo "File(s) not found. Is the filename valid?" &&
exit
((${#args[@]} != ${#@})) && echo "Some file(s) not found." >> $logfile
[[ ! -z $unknownlist && $maxdeepcheck != 0 ]] &&
_deepcheck "${unknownlist[@]}" 1>/dev/null
_fzf_menu
if [[ $openmethod == openrule ]]; then
_open
elif [[ $openmethod == default ]]; then
_default_open
elif [[ $openmethod == machinegun ]]; then
_machinegun
fi
}
#==================================================================
#=============== SCRIPT ===========================================
#==================================================================
# The -d flag allows to use openwith to output the default
# application to open files
# The _openwithfzf function open in the terminal a fzf menu
# to manually select which app will open the files, throught
# a default list of 'potential applications'
# Determines if a flag is given
if [[ ${1:0:1} == - ]]; then
opt=${1/-}; shift
if [[ $opt == *d* ]]; then
flag=d; opt=${opt/d}
[[ $opt == *m* ]] && flag=dm && opt=${opt/m}
[[ $1 == -m ]] && flag=dm && shift
[[ ! -z $opt ]] && flag=''
fi
fi
trap '_exit' EXIT
# Runs functions
if [[ ! -z $flag ]]; then
[[ $flag == *m* ]] && multiple=1
_init
_get_default_app "$@"
else
_openwithfzf "$@"
fi