Skip to content

Instantly share code, notes, and snippets.

@ayosec
Created July 14, 2022 22:02
Show Gist options
  • Save ayosec/1ea436f5f67ab88d42cbac29bcd8e4f2 to your computer and use it in GitHub Desktop.
Save ayosec/1ea436f5f67ab88d42cbac29bcd8e4f2 to your computer and use it in GitHub Desktop.
Clear pixels on a specific color register in a Sixel image.
#!/usr/bin/env ruby
#
# Usage:
#
# $ clear-sixel-reg register? files*
#
# The script reads Sixel images, are replaced every pixel using the
# specified color register with holes. The output is always sent to stdout.
#
# The `background selector` parameter of the protocol selector is forced
# to be 1.
#
# If `register` is omitted it is `0`.
# If no files are provided in the command-line, it reads stdin.
if ARGV.size == 0
STDERR.puts "Usage: #$0 color-register? files*"
exit 1
end
TARGET_REG = ARGV.first =~ /\A[0-9]+\Z/ ? Integer(ARGV.shift) : 0
def convert(stream)
parsing_color_reg = false
current_reg = -1
if stream.read(2) != "\033P"
STDERR.puts "Missing DCS."
return
end
loop do
case stream.getc
when "q" then break
when nil
STDERR.puts "Missing DCS."
return
end
end
print "\033P0;1;0q"
stream.each_byte do |byte|
if byte == 0x23 # "#"
parsing_color_reg = true
current_reg = 0
elsif parsing_color_reg
if (0x30..0x39).include?(byte) # "0"-"9"
current_reg = current_reg * 10 + byte - 0x30
else
parsing_color_reg = false
end
end
if (0x3F..0x7E).include?(byte) and current_reg == TARGET_REG
print "?"
else
putc byte
end
end
end
if ARGV.empty?
convert(STDIN)
else
ARGV.each do |file|
puts file if STDOUT.tty?
File.open(file) {|f| convert(f) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment