2

I want to use the zenity text input for file selection so i can just drag and drop. Seems like it should work but doesn't. When I drag in a file it doesn't find it, but the path and file name seem correct.

The "cut" is to remove the leading "file:/" from the input text.

xinput=$(zenity --entry \
--title="Drag in file" \
--text="" \
--entry-text "" \ )

xfile=$(echo "$xinput" | cut -c 7-)

if test -f "$xfile"; then
   echo "Found!"
else 
   echo "Not Found!"
fi
echo $xfile
Elrik
  • 25
  • 5

1 Answers1

1

It seems like the drag-and-drop prepends file:// and appends \r to the file path. It also converts the potentially problematic characters to their url-encoded version.

#!/bin/bash

xinput=$(
    zenity --entry \
    --title="Drag in file" \
    --text="" \
    --entry-text ""
)

# extract the part of interest
[[ $xinput =~ ^file://(.*)$'\r'$ ]] || exit 1

# decode the string
printf -v xfile %b "${BASH_REMATCH[1]//%/\\x}"

if [[ -e "$xfile" ]]
then
    printf '%q\n' "$xfile"
else
    printf 'No such file or directory: %q\n' "$xfile"
fi

remark: I tested the code with a path containing all the ASCII characters (0x01 to 0x7F)

Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • That's odd. On my Linux install, it doesn't, it just returns the filename entered in the box. Are you speaking of using WSL under windows? – David C. Rankin Aug 11 '22 at 01:44
  • I tested it on Linux; if I type the path myself in the dialog box then `zenity` doesn't modify it. I guess it's not related to `zenity` but to how the window manager handles the _drag & drop_ – Fravadona Aug 11 '22 at 07:25
  • That's the fly in the ointment. Each toolkit, Qt, Gtk, WxWidgets, Windows, etc.. all do it a bit differently. I suppose if you were looking to make a broad cross-platform script, you would have to check for and handle each of the different types of drag-n-drop file paths provide (like in a `case` statement of `if ... elif ... elif... else ... fi`.) I've never done too much drag-n-drop -- for that reason. – David C. Rankin Aug 11 '22 at 17:08