You are not logged in.

#226 2020-06-16 12:05:39

damo
....moderator....
Registered: 2015-08-20
Posts: 6,701

Re: The great yad hacking thread

Naik wrote:

...

Sounds easy, but I guess I would not be able to see any of the output this script (or the comand invoked by it) is writing to stdout, right?

Is there any option to do so, other than piping it to a temporary logfile and opening another dialogue afterwards to print it?

naik --greetz

Use tee and pipe it to a terminal?


Be Excellent to Each Other...
The Bunsenlabs Lithium Desktop » Here
FORUM RULES and posting guidelines «» Help page for forum post formatting
Artwork on DeviantArt  «» BunsenLabs on DeviantArt

Offline

#227 2020-06-17 01:25:55

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

Naik wrote:

So you are saying I could come up with a little ~/bin/anonsurf-helper.sh
and call it like this in jgmenu:

yad <options> --entry --hide-text | sudo -S $HOME/bin/anonsurf-helper.sh

Well, more like this, in prepend.csv:

^tag(anonsurf)
Back,^back()
Start,x-terminal-emulator -T 'AnonSurf' -e anonsurf-helper.sh --start
Stop,x-terminal-emulator -T 'AnonSurf' -e anonsurf-helper.sh --stop

I guess I would not be able to see any of the output this script (or the comand invoked by it) is writing to stdout, right?

If like above, then you'd open a terminal and then run the helper script in it, so you'd see the output. Also, if you're running the script in a terminal, you can use sudo as normal, no need for yad.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#228 2020-06-17 20:07:45

Naik
Member
From: Lipsia
Registered: 2015-10-03
Posts: 298

Re: The great yad hacking thread

johnraff wrote:
Naik wrote:

So you are saying I could come up with a little ~/bin/anonsurf-helper.sh
and call it like this in jgmenu:

yad <options> --entry --hide-text | sudo -S $HOME/bin/anonsurf-helper.sh

Well, more like this, in prepend.csv:

^tag(anonsurf)
Back,^back()
Start,x-terminal-emulator -T 'AnonSurf' -e anonsurf-helper.sh --start
Stop,x-terminal-emulator -T 'AnonSurf' -e anonsurf-helper.sh --stop

I guess I would not be able to see any of the output this script (or the comand invoked by it) is writing to stdout, right?

If like above, then you'd open a terminal and then run the helper script in it, so you'd see the output. Also, if you're running the script in a terminal, you can use sudo as normal, no need for yad.

Running a terminal was exactly what I did at first but didn't find satisfying.
That's when I started thinking about yad in the first place.

With your patient help I put togther this little
anonsurf_helper

#!/bin/bash
#
# kali-anonsurf helper script
# provid a simple YAD-Interface for running Kali-Anonsurf
# provided under
# GNU General Public License v3.0 
# like https://github.com/Und3rf10w/kali-anonsurf itself
# by Naik <naik@nachtlicht.one>
# 
########################################################################

### Help message
function print_help {
		echo "AnonSurf_Helper"
		echo ""
		echo "Usage: anonsurf_help [command] [logfile]"
		echo ""
		echo "[Command] could be one of the following"
		echo "--help		Show this help"
		echo "--start	Start system-wide anonymous"
		echo	"			tunneling under TOR proxy through iptables"		
		echo "--stop 	Reset original iptables settings"
		echo "			and return to clear navigation"
		echo "--restart	Combines \"stop\" and \"start\" options"
		echo "--change	Changes identity restarting TOR"
		echo "--status	Check if AnonSurf is working properly"
		echo "--myip		Show your current IP address"
		echo ""
		echo "If run without arguments, one can be chosen from a yad dialogue later."
		echo "All output will be written to a single logfile [logfile]."
		echo "If none is specified its default is /tmp/anonsurf_helper.log"
		echo ""
		echo "GNU General Public License v3.0 like https://github.com/Und3rf10w/kali-anonsurf itself"
	exit
}
### Choose action via GUI
function choose_action {
	action=$(yad ---title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=294 --posx=548 --height=184 --posy=133 --entry --button="gtk-ok:0" --button="gtk-close:1" --text "Was willst Du tun?:" --entry-text "Start" "Stop" "Change" "Restart" "Status" "MyIp")	
	echo $action
}

### check if /path/to/logfile is provided as second argument
### otherwise set default logfile to $HOME/tmp/anonsurf_helper.log
LOGFILE="/tmp/anonsurf_helper.log"
if touch $2; then
	LOGFILE=$2
    echo "Log will be written to "$LOGFILE"."
elif [ -f != $LOGFILE ]; then
	touch $LOGFILE
	echo "Log will be written to "$LOGFILE"." 
fi
### choose action
if [ -z "$1" ]; then
	choose_action
else
	action=$1
fi

case $action in

  --start|Start)
    yad --title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=294 --posx=548 --height=84 --posy=333 --entry --hide-text | sudo -S anonsurf start > $LOGFILE 2>&1
    yad --notification --image="/home/naik/.local/share/icons/anon.png" --text="You are under AnonSurf tunnel." --listen --command="bash -c anonsurf_helper" &
    ;;
  --stop|Stop)
    yad --title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=294 --height=84 --posx=548 --posy=333 --entry --hide-text | sudo -S anonsurf stop > $LOGFILE 2>&1 && 
    killall yad 2>/dev/null
    ;;
  --restart|Restart)
    yad --title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=294 --height=84 --posx=548 --posy=333 --entry --hide-text | sudo -S anonsurf restart > $LOGFILE 2>&1
    ;;
  --change|Change)
    yad --title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=294 --height=84 --posx=548 --posy=333 --entry --hide-text | sudo -S anonsurf change > $LOGFILE 2>&1
    ;;
  --status|Status)
    anonsurf status > $LOGFILE 2>&1
    ;;
  --myip|MyIP)
    anonsurf myip > $LOGFILE 2>&1
    ;;
  *)
    print_help
    ;;
esac
LOG=$( cat $LOGFILE| sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" )
yad --title="Anonsurf Helper" --window-icon="/home/naik/.local/share/icons/anon.png" --width=420 --posx=430 --height=230 --posy=190 --text="$LOG"
exit

It is simply called from jgmenu like

^tag(anonsurf)
Back,^back()
Start,anonsurf_helper --start
Stop,anonsurf_helper --stop
Choose,anonsurf_helper

I really thank you!
The next thing for me is to provide a dialogue for choosing the action to take thus making $1 obsolete and figure out how to invoke a little systray icon together with the start command and kill it with the stop command, but this won't be done with yad I guess.

EDIT: It has been done and the script has been updated. I might take the time to make it click-able, but we will see.

EDIT2: Removed some unnecessary privilege escalations.

EDIT3: All TODOS have been done and the script has been Updated.
It now can be run without arguments directly from jgmenu and the choice will be made via YAD-dialogue. I only ask myself whether it would be better to clean up on exit with a trap. Usually I like clean stuff but there wouldn't be any log left for debugging...
Anyway, I'd say I'm happy for now!

Thanks again @jhonraff and all the others from whom I boroughed some snippet here and there.

naik --greetz

Last edited by Naik (2020-06-18 10:56:36)


"Kaum macht [Mensch]* es richtig, funktioniert es sofort!"
BL-Kitchen on GitHub

Offline

#229 2020-08-04 07:42:05

yadbash
Member
From: Nevada, USA
Registered: 2017-12-27
Posts: 7
Website

Re: The great yad hacking thread

Hello all, I have not been on here for quite sometime as I have been focusing my work on a new easy Remaster process that only requires Gparted (or parted), rsync and dd commands. I am looking for some guidance as I want to build a YAD GUI / bash interface that will automate the manual process that I am using. Should I use a very large one file program where I can import source from config files like this:

. /file01.source

Or, should I call sub yad / bash files for the various steps ?

Here are the steps I take to remaster any Debian Based system that uses Grub Boot Loader.


The Process in detail copy using either rsync or dd with partitioning resizing using Gparted. Then syncing uuid=number in /etc/fstab & /etc/initramfs-tools/conf.d/resume files. then updating initramfs & updating /boot/grub/grub.cfg using sudo commands.

boot to 2nd partition
mount partition to be Re-spinned.

Copy from hard drive to hard drive (partition file system copy) using rsync (For example: sda2 --> sdb1)
NOTE: Shrink source partition using Gparted (rsync copy) or Fdisk to find byte sector count number (dd count=number)

sudo rsync -qaHAXS --progress /media/mounted-partition/ /media/target-partition/

dd command can be used to create a img file and it can be compressed with gzip for maximum compression:

sudo dd if=/dev/sdxX of=./dd-image-file-of-custom-build-partiton.img bs=4M status=progress && sync

dd img file can then be compressed for maximum comp[/ression. (Example 5GB --> 1.4GB)

gzip -k -9 ./dd-image-file-of-custom-build-partition.img

resulting file is: dd-image-file-of-custom-build-partition.img.gz

To decompress file:

gzip -d ./dd-image-file-of-custom-build-partition.img

Using dd command to copy custom build respin img file to hard drive or USB Stick partition:

sudo dd if=./dd-image-file-of-custom-build-partition.img of=/dev/sdxX bs=4M status=progress && sync

Note: When copying a partition it retains same uuid=number as source partition and this can not occur on same computer. The uuid=number needs to be changed in fstab & resume file. Then needs to be update in grub.cfg file:

Find correct uuid=number

sudo blkid

Hard Drive:
Insert correct uuid=number in the new target partition /etc/fstab & /etc/initiramfs-tools/conf.d/resume files

USB Stick - Change uuid=number using Gparted (also do swap partition if applicable)
Insert correct uuid=number in the new target partition /etc/fstab & /etc/initiramfs-tools/conf.d/resume files

Run Grub update on 2nd partition on hard drive & Reboot

Highlight new partition sdxX Grub Menu & Press "e" key. Verify the last uuid=number is same as other top uuid=number. Press "F10" key.

When booted in to new partiton: (dev/sdxX = new partitoin)

sudo update-initramfs -u && sudo grub-install /dev/sdxX && sudo update-grub

DONE !

NOTE: Special configuration for USB Stick.

I use a prebuilt USB Stick build from a 1 Megabyte dd img file that has MBR, Grub, 12GB ext4 & 3GB+ linux-swap partitions.

I suggest using Gparted and Grub commands to build a base bootable USB Stick. For exmaple on a 16GB USB Stick
12GB ext4 root partition & 3GB+ linux-swap partition.

Then use dd command to place your custom Q4OS Build image .img file in the root partition on USB Stick. /dev/sdxX   (not /dev/sdb)

Or the 1MB image and detailed instructions are here: https://github.com/godistros/GoDistrOS

Offline

#230 2020-08-04 13:31:30

damo
....moderator....
Registered: 2015-08-20
Posts: 6,701

Re: The great yad hacking thread

^ This sounds like a topic for a thread all on its own in eg Help & Support (Other).

And it sounds like a great project smile


Be Excellent to Each Other...
The Bunsenlabs Lithium Desktop » Here
FORUM RULES and posting guidelines «» Help page for forum post formatting
Artwork on DeviantArt  «» BunsenLabs on DeviantArt

Offline

#231 2020-08-05 06:39:11

ohnonot
...again
Registered: 2015-09-29
Posts: 5,554

Re: The great yad hacking thread

Since you want this to work for (all) Debain based ditros you'll be busy ironing out the functionality and making it more robust for the next year or so.
Asuming a yad-driven GUI means more work, I'd focus on CLI functionality first, and write it in a way that a gui "frontend" can be created for it evtl.

All in all, yes, this should be a thread all on its own.


Give to COVAX! Here or here. (explanation)

Offline

#232 2020-08-05 07:03:00

Grover
New Member
Registered: 2020-08-03
Posts: 4

Re: The great yad hacking thread

>debian ISO remaster script Tomas Matejicek no need reinvent wheel

Offline

#233 2020-08-05 07:22:58

ohnonot
...again
Registered: 2015-09-29
Posts: 5,554

Re: The great yad hacking thread

Grover wrote:

>debian ISO remaster script Tomas Matejicek no need reinvent wheel

But there is a need to add links to your statements.
I guess you mean this but I could not find that script as a separate application.


Give to COVAX! Here or here. (explanation)

Offline

#234 2020-08-05 07:26:12

Grover
New Member
Registered: 2020-08-03
Posts: 4

Re: The great yad hacking thread

Offline

#235 2020-08-05 17:56:10

ohnonot
...again
Registered: 2015-09-29
Posts: 5,554

Re: The great yad hacking thread

^ Looking good, thanks!


Give to COVAX! Here or here. (explanation)

Offline

#236 2021-07-07 02:31:49

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

list: hidden columns are handy to store data

Discovered yad's hidden columns for lists recently so sharing  here, in case it's useful for someone.

In a checklist, or radiolist, you want to show the user some "pretty names" that they can understand easily, but when you get their choice(s) back you usually want some solid data, like a complete filepath. Instead of putting the data in an array and searching for it based on the pretty name the user chose (an associative array would actually work OK) you can store it in the yad list as a hidden column.

Then use --print-column to output just the hidden "data" column, and --separator='' so each line of yad's output is only the content of the hidden column - no problem with escaping spaces etc.

Put the contents of the list in an array in a do loop, like for <something>; do yadlist+=( "$check" "$pretty_name" "$real_data"); done and inside the yad command --column="Select:CHK" --column="Name:TEXT" --column=path:HD "${yadlist[@]}".

Trivial example: list the files in current directory, display the filename only, return the full paths of any files selected:

unset yadlist
for f in ./*
do
    [[ -d $f ]] && continue # files only
    yadlist+=(FALSE "${f##*/}" "$(readlink -f "$f")")
done
choice=$(yad --list --text="Choose some files" --center --borders=20 --width=400 --height=500 --checklist --column="Select:CHK" --column="Name:TEXT" --column=path:HD "${yadlist[@]}" --separator='' --print-column=3 --button=OK:0 --button=Cancel:1 )
echo "$choice"
/home/john/auth1_fms_19164
/home/john/jgmenu.log

...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#237 2021-07-07 11:57:34

misko_2083
Member
Registered: 2016-05-24
Posts: 500

Re: The great yad hacking thread

johnraff wrote:

Trivial example: list the files in current directory, display the filename only, return the full paths of any files selected:

Should be fine unless there are newline characters in the filenames.
Else expect this in the choice:

/home/misko/Desktop/network.desktop
/home/misko/Desktop/progbar
ddd
/home/misko/Desktop/trash-can.desktop

With --quoted-output switch in yad command it will probably look like this:

'/home/misko/Desktop/network.desktop'
'/home/misko/Desktop/progbar
ddd'
'/home/misko/Desktop/trash-can.desktop'

---------------------------------------------------

I think it's better not to store the paths in the hidden columns.
It is better is to store it in an array and fill the hidden columns with indexes.

unset yadlist
unset filelist
declare -i index=0

for f in ./*
do
    [[ -d $f ]] && continue # files only
    filelist+=("$(readlink -f "$f")")
    f="${f##*/}"
    f="${f/&/&amp;}"
    yadlist+=(FALSE "${f}" "${index}")
    let index=index+1
done

choice=$(yad --list --text="Choose some files" \
             --center --borders=20 --width=400 --height=500 \
             --checklist --column="Select:CHK" --column="Name:TEXT" \
             --column=path:HD "${yadlist[@]}" --separator=' ' \
             --print-column=3 --button=OK:0 --button=Cancel:1 )

for key in ${choice}
do
    echo "${filelist[${key}]}"
done

------------------------------------------------------
I almost forgot, yad lists don't like ampersands and files can sometimes have them in names.
Ampersands have to be escaped.
E.g. :

   echo "${f##*/}" | sed 's/&/&amp;/g'

If the path is in the hidden column that means it has to be escaped too.
That's one more reason to use the index.
It could also be faster but  who is going to measure anyway. : )

Last edited by misko_2083 (2021-07-07 15:54:18)


This content is censored by the German government.

Offline

#238 2021-07-08 04:37:04

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

^Yes newlines in data make life difficult because so many tools use them to separate items - yad too. In the case of filenames, I'd be inclined to just reject such names because the chance of a legitimate file having such a name is surely very low?
Thanks for pointing out --quoted-output which makes things clearer.

I have a directory full of strangely-named files for testing things like this:

john@lithium:~/text/oddnames$ for i in *; do [[ -d $i ]] && continue; echo "Filename: ${i}"; done
Filename: "
Filename: $HOME
Filename: a; rm b
Filename: b`whoami`c
Filename: f\\
Filename: "file with"quotes&
Filename: "fish & chips" <what's that?>
Filename: line
break
Filename: New Empty File
Filename: &quot;&gt;&lt;&apos; %percent%20end
Filename: s"s
Filename: 日本語.txt

(These are the real filenames, no escaping has been applied.)
Running the yad code I suggested above makes the yad display wrong for many of these:
aRZcIbO.png
But the filepaths in the hidden column are OK without any escaping:

john@lithium:~/text/oddnames$ echo "$choice"
/data/john/Dropbox/text/oddnames/"
/data/john/Dropbox/text/oddnames/$HOME
/data/john/Dropbox/text/oddnames/a; rm b
/data/john/Dropbox/text/oddnames/b`whoami`c
/data/john/Dropbox/text/oddnames/f\\
/data/john/Dropbox/text/oddnames/"file with"quotes&
/data/john/Dropbox/text/oddnames/"fish & chips" <what's that?>
/data/john/Dropbox/text/oddnames/line
break
/data/john/Dropbox/text/oddnames/New Empty File
/data/john/Dropbox/text/oddnames/&quot;&gt;&lt;&apos; %percent%20end
/data/john/Dropbox/text/oddnames/s"s
/data/john/Dropbox/text/oddnames/日本語.txt

Escaping ampersands was not enough to fix the displayed names though. While ' and " seem OK, < and > have to be escaped too, then the display is OK:

unset yadlist; for f in *; do [[ -d $f ]] && continue; name=${f##*/}; name=${name//&/&amp;}; name=${name//</&lt;}; name=${name//>/&gt;}; yadlist+=(FALSE "$name" "$(readlink -f "$f")"); done

cGjA5hD.png
With --quoted-output:

john@lithium:~/text/oddnames$ echo "$choice"
'/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''s that?>'

But I'm not sure how helpful the quoting really is, though, unless you plan to feed that string straight into a shell command. If the data really has to contain linebreaks then I agree it's best to put it into a separate array, though I might be more inclined to use an associative array to map keys to data. Just my personal preference:

declare -A filelist
filelist[$name]=$data

And use the returned name(s) to access the data. In that case there's no need for a hidden column.

But my original idea (not to re-invent a file selector) was to use yad instead of an array, store the data in the hidden column and make the code a little bit simpler. As long as there are no linebreaks in the data that works.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#239 2021-07-08 06:46:27

misko_2083
Member
Registered: 2016-05-24
Posts: 500

Re: The great yad hacking thread

johnraff wrote:
john@lithium:~/text/oddnames$ echo "$choice"
'/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''s that?>'

But I'm not sure how helpful the quoting really is, though, unless you plan to feed that string straight into a shell command.

That's exactly the plan. devil

It is always helpfull to print them out quoted when feeding to shell commands.
The bash builtin ${@@Q} helps:

print_quoted () {
    printf '%s\n' "${@@Q}"
}

print_quoted *

#----Output-------#
'network.desktop'
$'progbar\nddd&'
'trash-can.desktop'
#----Output-------#

Your odd named file would be printed like this:

'/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''\'\'''\''s that?>'

Last edited by misko_2083 (2021-07-08 06:47:19)


This content is censored by the German government.

Offline

#240 2021-07-08 11:05:25

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

misko_2083 wrote:

The bash builtin ${@@Q} helps

Thanks for that! Something (else) I didn't know.
It's buried deep in the manual:

       ${parameter@operator}
              Parameter transformation.  The expansion is either a  transforma‐
              tion of the value of parameter or information about parameter it‐
              self, depending on the value of operator.   Each  operator  is  a
              single letter:

              Q      The  expansion  is a string that is the value of parameter
                     quoted in a format that can be reused as input.
              E      The expansion is a string that is the value  of  parameter
                     with  backslash  escape  sequences  expanded  as  with the
                     $'...' quoting mechanism.
              P      The expansion is a string that is the result of  expanding
                     the  value of parameter as if it were a prompt string (see
                     PROMPTING below).
              A      The expansion is a string in the  form  of  an  assignment
                     statement  or  declare  command  that,  if evaluated, will
                     recreate parameter with its attributes and value.
              a      The expansion is a string consisting of flag values repre‐
                     senting parameter's attributes.

Your odd named file would be printed like this:

'/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''\'\'''\''s that?>'

You seem to have put it through an extra level of quoting there.

john@lithium:~$ s='/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''s that?>'
john@lithium:~$ echo "$s"
/data/john/Dropbox/text/oddnames/"fish & chips" <what's that?>
john@lithium:~$ echo "${s@Q}"
'/data/john/Dropbox/text/oddnames/"fish & chips" <what'\''s that?>'
# there's also printf %q
john@lithium:~$ printf '%q\n' "$s"
/data/john/Dropbox/text/oddnames/\"fish\ \&\ chips\"\ \<what\'s\ that\?\>

---
Anyway, the more I think about it, the more I like your idea of putting messy data in an array, with an index in yad's hidden column. It feels quite solid.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#241 2021-07-08 21:39:14

misko_2083
Member
Registered: 2016-05-24
Posts: 500

Re: The great yad hacking thread

johnraff wrote:

You seem to have put it through an extra level of quoting there.

Yep, that's the case.
We are using bash 5.0.3, in bash 5.1 there are few more options.
https://man7.org/linux/man-pages/man1/b … PARAMETERS


This content is censored by the German government.

Offline

#242 2021-07-09 05:26:00

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

Changes in bash 5.1: https://lists.gnu.org/archive/html/info … 00003.html

Anyway in our 5.0.3 already, ${parameter@Q} looks somewhat useful in things like pipemenus, where a word might hold a filepath:

menuItem "$label" "bl-text-editor ${filepath@Q}"

It's not really doing a great deal - surrounds with single quotes and escapes any single quotes inside with '\'' - but it helps keep the code tidy. smile I will start using it.

Looking over the other operators available, maybe E might be useful occasionally?

              E      The expansion is a string that is the value  of  parameter
                     with  backslash  escape  sequences  expanded  as  with the
                     $'...' quoting mechanism.

If you spot any others that look handy, please share.

---
Escaping for yad text: I remembered that BL ship, in /usr/lib/bunsen/common/bl-includes, a function pangoEscape(). It was meant for passing text to jgmenu but should work just as well with yad. If you have the file on your system, just source it, or else copy/paste the function in:

pangoEscape() {
    local string="${1//&/&amp;}"
    string="${string//</&lt;}"
    string="${string//>/&gt;}"
    printf '%s' "$string"
}

Then you can use it like eg

yadlist+=(FALSE "$(pangoEscape "$name") "$data")

to escape ampersands, < and >. I'm now going to go over all my yad dialogs that might have to display weird filenames and apply it.  wink


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#243 2021-07-09 14:55:17

misko_2083
Member
Registered: 2016-05-24
Posts: 500

Re: The great yad hacking thread

johnraff wrote:

If you spot any others that look handy, please share.

Q - returns single quoted string with any special characters such as \n, \t,... escaped.
It can be used to place all the lines of a file file in a single line.

printf "%q" "$(< file)"
$'line1\nline2\nline3\nline4'

var=$(<file)
echo "${var@Q}"
$'line1\nline2\nline3\nline4'

# notice $'.....'

P - is neat for tesing the looks of prompts like PS1, PS2

prompt="\\[$(tput setaf 5)\\]\\u@\\h:\\w #\\[$(tput sgr0)\\]"
echo "${prompt@P} Neat"

E - I'm not sure how usefull it is
It expands all of escaped characters.

var="one\n\ttwo\nthree"
 echo "${var}"
one\n\ttwo\nthree

echo -e "${var}"
one
	two
three

echo "${var@E}"
one
	two
three

There is probaly some use case when passing quoted variables to a script, like a thunar custom action to a script.

bash -c 'echo "${@@Q}"' _ a b c
'a' 'b' 'c'
bash -c 'echo "${@@E}"' _ 'a' 'b' 'c'
a b c
bash -c 'printf "%s\n" "${@@Q}"' _ a b c
'a'
'b'
'c'
bash -c 'printf "%s\n" "${@@E}"' _ 'a' 'b' 'c'
a
b
c
bash -c 'printf "%s\n" "${@@Q}"' _ {1..3} | yad --text-info
'1'
'2'
'3'

*If used directly as a thunar custom action instead of a script file %s option in printf must be escaped like this %%s

bash -c 'printf "%%s\n" "${@@Q}"' _ %F | yad --text-info

A - prints out the variable how it is assigned and declare option if available.

var='one\n\ttwo\nthree'
echo "${var@A}"
var='one\n\ttwo\nthree'

declare -i var=5
echo "${var@A}"
declare -i var='5'

var+=1
echo "${var@A}"
declare -i var='6'

a - returns varible's  attributes

declare -ri var='5'
echo ${var@a}
ri

Last edited by misko_2083 (2021-07-09 14:57:15)


This content is censored by the German government.

Offline

#244 2021-07-10 02:50:56

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 8,278
Website

Re: The great yad hacking thread

^thanks!

So @Q does more than just wrap single quotes - it also replaces linebreaks with \n. Good to be aware of - I'm not sure if I'd always want that to be done.

E - I'm not sure how usefull it is
It expands all of escaped characters.

Well, one obvious use might be to unescape a string that had been quoted with @Q?


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Offline

#245 2021-07-19 13:26:04

misko_2083
Member
Registered: 2016-05-24
Posts: 500

Re: The great yad hacking thread

johnraff wrote:

So @Q does more than just wrap single quotes - it also replaces linebreaks with \n. Good to be aware of - I'm not sure if I'd always want that to be done.

Yes, tabs, newlines...

johnraff wrote:

E - I'm not sure how usefull it is
It expands all of escaped characters.

Well, one obvious use might be to unescape a string that had been quoted with @Q?

Yes but I was thinking about other realms of usefulness apart from the obvious one. smile


This content is censored by the German government.

Offline

#246 2021-07-19 14:50:34

Sector11
Conky 1.9er Mod Squid
From: Upstairs
Registered: 2015-08-20
Posts: 6,769

Re: The great yad hacking thread

OFF TOPIC

misko_2083 wrote:

Yes but I was thinking about other realms of usefulness apart from the obvious one. smile

OK, in that case: Einstein's theory of Yad

      y²
E = ----- + d⁴
      ½a

Just kidding here!
because everyone need a chuckle every now and then.

Have a GREAT Monday.

We now return you to the topic at hand.
ON TOPIC


The sun will never set if you keep walking towards it. - my son
Being positive doesn't understand physics.
_______________________________
Debian 10 Buster = SharpBang ♯!

Offline

Board footer

Powered by FluxBB