Skip to content

Instantly share code, notes, and snippets.

@jtprince
Last active May 23, 2021 17:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jtprince/5961686 to your computer and use it in GitHub Desktop.
Save jtprince/5961686 to your computer and use it in GitHub Desktop.
screenshot application
#!/usr/bin/env ruby
# sc - screenshot utility using imagemagick 'import'
require 'optparse'
require 'ostruct'
require 'shellwords'
require 'fileutils'
viewers = {
'g' => 'geeqie',
'e' => 'eog',
'i' => 'inkscape',
'm' => 'gimp',
}
get_window_id = {
window: lambda { `xwininfo`[/Window id\:\s+(\w+)\s+/, 1] },
active: lambda { `xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"`.split(/\s+/).last },
root: lambda { 'root' }
}
viewers_bold_string = viewers.map do |letter,app|
app.sub(letter, "\033[1m\033[31m" + letter + "\033[0m")
end.join('|')
opt = OpenStruct.new( window: :root )
parser = OptionParser.new do |op|
op.banner = "usage: #{File.basename(__FILE__)} [OPTS] filename[.png]"
op.separator "output: filename.png [by default captures entire screen]"
op.separator ""
op.on("-d", "--delay <sec>", Float, "delay that many seconds") {|v| opt.delay = v }
op.on("-a", "--active", "capture the active window") { opt.window = :active }
op.on("-b", "--box", "draw a box to capture") { opt.window = :box }
op.on("-w", "--window", "select a window to capture") { opt.window = :window }
op.on("-o", "--open <s>", viewers_bold_string) {|v| opt.open = viewers[v] || v }
op.on("--dir <s>", "save to this directory") {|v| opt.dir = v }
op.on("--timestamp", "add a date/time stamp to filename") {|v| opt.timestamp = v }
end
parser.parse!
if ARGV.size == 0
puts parser
exit
end
filename = ARGV.shift
filename += ".png" unless filename[/\.png/i]
filename_esc = Shellwords.escape(filename)
TIME_STAMP_FORMAT = "%Y-%m-%d--%H-%M-%S"
if opt.timestamp
ext = File.extname(filename)
base = filename.chomp(ext)
filename = base + "-" + Time.now.strftime(TIME_STAMP_FORMAT) + ext
end
sleep(opt.delay) if opt.delay
# create the command
cmd_parts = ["import"]
unless opt.window == :box
cmd_parts << "-window" << get_window_id[opt.window].call
end
cmd_parts << filename_esc
cmd = cmd_parts.join(' ')
dir = (opt.dir && File.expand_path(opt.dir) ) || Dir.pwd
FileUtils.mkpath(dir) unless File.exist?(dir)
Dir.chdir(dir) do
system cmd
if opt.open
sleep(0.1)
open_cmd = "#{opt.open} #{filename_esc} &"
puts open_cmd
system open_cmd
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment