Swatch Sniper

@xzenile / swatch-sniperv1.1.0Public

Grab the color under your pointer into a palette strip, then copy any swatch's hex code from a menu.

Files

Version 1.1.0 (current)

gfx-swatch-sniper.luau14.5 KB

--[[
  rebind: min_sdk=3.13.0
  rebind: name=GFX · Swatch Sniper
  rebind: version=1.1.0
  rebind: author=PLACEHOLDER
  rebind: description=Grab the color under your pointer into a palette strip, then copy any swatch's hex code from a menu.
  rebind: permissions=screen,clipboard:write
  rebind: permission_reason="screen: Reads the one pixel under your pointer when you press the grab key"
  rebind: instance=single
]]

-- Swatch Sniper v1.1.0 (works over any app)
--   Grab key (default Ctrl+Alt+G): adds the color under the pointer to the palette strip.
--   Palette key (default Ctrl+Alt+Shift+F7): a menu of your swatches; pick one to copy its code.
--   Ctrl+Alt+Shift+Z opens Edit hotkeys (Bind Board) to change these keys from the overlay.
--   The strip shows the newest swatch on the left. Options set the size, count and copy format.
-- Permissions: screen (one pixel read per grab) and clipboard:write (copying a code). It never
--   reads the clipboard. The palette is saved in the script's data folder (@data/palette.json).
-- Hotkeys: grab, palette menu and "Edit hotkeys" all go through the shared Bind Board block below.
-- APIs: rb.screen.pixel_hex (screen permission), rb.system.mouse, rb.overlay.surface/menu/toast/status (3.11.1),
--   rb.clipboard.set (clipboard:write), rb.file read_json/write_json with @data (3.13.0), rb.ui.*, rb.bind,
--   rb.timer, rb.script.reload. min_sdk 3.13.0. No app keys are sent, so there are no vendor shortcuts to cite.
-- Platforms: Windows and macOS. On macOS, pixel reads need Screen capture turned on in Rebind's
--   Settings (and the macOS Screen Recording grant); until then a grab shows a toast instead.
--   The overlay is hidden over exclusive full-screen games on Windows.

local DEFAULTS = {
  max_swatches = 10,
  swatch_size = 28,
  anchor = "bottom",
  format = "#RRGGBB",
  keep = true,
  show_strip = true,
}
local GRAB_DEFAULT = "LCtrl+LAlt+G"
local MENU_DEFAULT = "LCtrl+LAlt+LShift+F7"
local BOARD_DEFAULT = "LCtrl+LAlt+LShift+Z"

local cfg = rb.ui.schema({
  grab_key = rb.ui.keybind(GRAB_DEFAULT, {
    label = "Grab color",
    tooltip = "Adds the color under the pointer.",
    group = "Hotkeys",
  }),
  menu_key = rb.ui.keybind(MENU_DEFAULT, {
    label = "Palette menu",
    tooltip = "Opens the menu to copy a swatch.",
    group = "Hotkeys",
  }),
  board = rb.ui.keybind(BOARD_DEFAULT, {
    label = "Edit hotkeys",
    tooltip = "Opens the Bind Board over any app: pick a hotkey, then press the new key.",
    group = "Hotkeys",
  }),

  format = rb.ui.select(DEFAULTS.format, { "#RRGGBB", "RRGGBB", "#rrggbb", "rgb(r, g, b)" }, {
    label = "Copy as",
    group = "Palette",
  }),
  max_swatches = rb.ui.slider(DEFAULTS.max_swatches, {
    label = "Swatches kept",
    min = 4,
    max = 16,
    step = 1,
    tooltip = "The oldest swatch drops off when the strip is full.",
    group = "Palette",
  }),
  keep = rb.ui.toggle(DEFAULTS.keep, {
    label = "Remember the palette",
    tooltip = "Saves the palette in the script's data folder so it survives a restart.",
    group = "Palette",
  }),

  show_strip = rb.ui.toggle(DEFAULTS.show_strip, { label = "Show the palette strip", group = "Strip" }),
  swatch_size = rb.ui.slider(DEFAULTS.swatch_size, {
    label = "Swatch size",
    min = 16,
    max = 48,
    step = 2,
    suffix = " px",
    group = "Strip",
  }),
  anchor = rb.ui.select(DEFAULTS.anchor,
    { "bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right", "left", "right" },
    { label = "Strip position", group = "Strip" }),

  reset = rb.ui.toggle(false, {
    label = "Reset to defaults",
    tooltip = "Resets the Palette and Strip settings. Hotkeys reset from Edit hotkeys.",
    group = "Reset",
  }),
})

local SAVE = "@data/palette.json"
local palette = {} -- lowercase "rrggbb", newest first

local function loadPalette()
  if rb.file.exists(SAVE) then
    return rb.file.read_json(SAVE)
  end
  return nil
end

if cfg.keep then
  local ok, data = pcall(loadPalette)
  if ok and type(data) == "table" then
    for _, hex in data do
      if type(hex) == "string" and hex:match("^%x%x%x%x%x%x$") then
        table.insert(palette, hex:lower())
      end
    end
  end
end

local function save()
  if not cfg.keep then
    return
  end
  local ok, why = pcall(rb.file.write_json, SAVE, palette)
  if not ok then
    rb.log.warn("palette not saved: " .. tostring(why))
  end
end

local function formatHex(hex)
  local f = cfg.format
  if f == "RRGGBB" then
    return hex:upper()
  end
  if f == "#rrggbb" then
    return "#" .. hex:lower()
  end
  if f == "rgb(r, g, b)" then
    local r = tonumber(hex:sub(1, 2), 16)
    local g = tonumber(hex:sub(3, 4), 16)
    local b = tonumber(hex:sub(5, 6), 16)
    return string.format("rgb(%d, %d, %d)", r, g, b)
  end
  return "#" .. hex:upper()
end

local surface = nil
local drawnKey = ""

local function removeStrip()
  if surface then
    pcall(function()
      surface:remove()
    end)
    surface = nil
  end
end

local function redraw()
  local n = #palette
  local key = table.concat(palette, ",") .. "|" .. cfg.swatch_size .. "|" .. cfg.anchor .. "|" .. tostring(cfg.show_strip)
  if key == drawnKey then
    return
  end
  drawnKey = key
  removeStrip()
  if not cfg.show_strip or n == 0 then
    return
  end

  local sz, gap, pad = cfg.swatch_size, 4, 6
  local labelH = 16
  local w = pad * 2 + n * sz + (n - 1) * gap
  local h = pad * 2 + sz + labelH
  local ops = {
    { kind = "rect", x = 0, y = 0, w = w, h = h, fill = "#1b1d24e6", radius = 8, border = "#ffffff22", border_width = 1 },
  }
  for i, hex in palette do
    local x = pad + (i - 1) * (sz + gap)
    table.insert(ops, {
      kind = "rect",
      x = x,
      y = pad,
      w = sz,
      h = sz,
      fill = "#" .. hex,
      radius = 4,
      border = i == 1 and "#ffffffcc" or "#ffffff44",
      border_width = i == 1 and 2 or 1,
    })
  end
  table.insert(ops, { kind = "text", x = pad, y = pad + sz + 2, size = 11, text = formatHex(palette[1]), color = "#e6e6e6" })

  local ok, s = pcall(rb.overlay.surface, { width = w, height = h, anchor = cfg.anchor, offset_y = 12 })
  if not ok then
    rb.log.warn("strip not shown: " .. tostring(s))
    return
  end
  surface = s
  surface:draw(ops)
end

local function grab()
  local x, y = rb.system.mouse()
  local ok, hex = pcall(rb.screen.pixel_hex, x, y)
  if not ok or type(hex) ~= "string" then
    rb.overlay.toast("Couldn't read the screen: " .. tostring(hex), { title = "Swatch Sniper", duration = 5000 })
    return
  end
  hex = hex:lower()
  for i, v in palette do -- grabbing a color again moves it to the front
    if v == hex then
      table.remove(palette, i)
      break
    end
  end
  table.insert(palette, 1, hex)
  while #palette > cfg.max_swatches do
    table.remove(palette)
  end
  save()
  redraw()
  rb.overlay.toast(formatHex(hex), { title = "Swatch grabbed", duration = 1200 })
end

local function clearPalette()
  palette = {}
  save()
  redraw()
end

local function openPalette()
  if #palette == 0 then
    local grabKey = tostring(rb.ui.get("grab_key") or GRAB_DEFAULT):gsub("@.*$", "")
    rb.overlay.toast("No swatches yet. Press " .. grabKey .. " over a color.", { title = "Swatch Sniper" })
    return
  end
  local items = {}
  for i, hex in palette do
    local code = formatHex(hex)
    table.insert(items, {
      label = code,
      hint = i == 1 and "newest" or nil,
      action = function()
        rb.clipboard.set(code)
        rb.overlay.toast("Copied " .. code, { title = "Swatch Sniper", duration = 1500 })
      end,
    })
  end
  table.insert(items, { label = "Clear palette", hint = "removes all", action = clearPalette })
  local m, why = rb.overlay.menu(items, { title = "Swatch Sniper", subtitle = "Enter or 1-9 copies. Esc closes." })
  if not m then
    rb.log.warn("menu not shown: " .. tostring(why))
  end
end

-- ===== Bind Board v1.3 (shared; paste above your binds) =====
-- Usage: BB.bind("snooze", "Snooze", "LCtrl+LAlt+B", fn)  and  BB.board("board", "LCtrl+LAlt+K")
local BB = { rows = {}, order = {}, busy = false }
local MODS = { "LCtrl", "RCtrl", "LShift", "RShift", "LAlt", "RAlt", "LWin", "RWin" }
local IS_MOD = {}
for _, m in MODS do
  IS_MOD[m] = true
end
local REFUSE = { Escape = "Esc always cancels", Mouse1 = "a plain left click can't be a hotkey" }

local function cur(id)
  return rb.ui.get(id) or BB.rows[id].default
end

local function shown(k) -- hide a pinned device id
  return (string.match(k, "^[^@]+"))
end

local function chord(key)
  local parts = {}
  for _, m in MODS do
    if m ~= key and rb.input.is_down(m) then
      table.insert(parts, m)
    end
  end
  table.insert(parts, key)
  return table.concat(parts, "+")
end

local function apply(id, key)
  local r = BB.rows[id]
  local ok, h = pcall(rb.bind, key, r.fn, r.opts)
  if not ok then
    return false
  end
  if r.handle then
    r.handle:stop()
  end
  r.handle = h
  rb.ui.set(id, key)
  return true
end

local function guarded(opts) -- pause this script's Bind Board binds while capture listens
  local g = {}
  for k, v in opts or {} do
    g[k] = v
  end
  local orig = g.when
  g.when = function(d)
    return not BB.busy and (orig == nil or orig(d))
  end
  return g
end

function BB.bind(id, label, default, fn, opts)
  opts = guarded(opts)
  local r = { label = label, default = default, fn = fn, opts = opts }
  BB.rows[id] = r
  table.insert(BB.order, id)
  local key = cur(id)
  local ok, h = pcall(rb.bind, key, fn, opts)
  if not ok and key ~= default then -- a bad saved key falls back to the default
    ok, h = pcall(rb.bind, default, fn, opts)
    if ok then
      rb.ui.set(id, default)
      rb.overlay.toast(label .. " couldn't use " .. shown(key) .. ", so it's back to " .. default .. ".")
    end
  end
  if ok then
    r.handle = h
  else
    rb.overlay.toast(label .. " has no hotkey. Set one in Edit hotkeys or the Options tab.")
  end
end

local function restart_menu(text)
  rb.overlay.menu({
    { label = "Restart script now", action = function() rb.script.reload() end },
    { label = "Later" },
  }, { title = text, subtitle = "Restart to apply" })
end

local function saved(r, key)
  rb.overlay.toast(r.label .. " is now " .. shown(key) .. ".", { title = "Hotkey saved" })
end

local function swap(id, key, clash, mine)
  local r, r2 = BB.rows[id], BB.rows[clash]
  if r2.handle then
    r2.handle:stop()
  end
  r2.handle = nil
  rb.ui.set(clash, mine) -- saved first, so a restart never doubles a key
  if not apply(id, key) then -- put the other action back on its key
    rb.ui.set(clash, key)
    local ok, h = pcall(rb.bind, key, r2.fn, r2.opts)
    if ok then
      r2.handle = h
    end
    rb.overlay.toast("Couldn't use " .. shown(key) .. ". Nothing changed.")
    return
  end
  if apply(clash, mine) then
    saved(r, key)
    return
  end
  restart_menu("Swapped. " .. r2.label .. " is saved as " .. shown(mine))
end

local function set_key(id, key)
  local r, clash = BB.rows[id], nil
  for _, o in BB.order do
    if o ~= id and cur(o) == key then
      clash = o
    end
  end
  if not clash then
    if apply(id, key) then
      saved(r, key)
      return
    end
    rb.ui.set(id, key)
    restart_menu("Saved " .. shown(key) .. " for " .. r.label)
    return
  end
  local mine = cur(id)
  rb.overlay.menu({
    { label = "Cancel" },
    { label = "Swap the two keys", hint = BB.rows[clash].label .. " → " .. shown(mine),
      action = function() swap(id, key, clash, mine) end },
  }, { title = shown(key) .. " is already " .. BB.rows[clash].label, subtitle = "Nothing changes unless you pick Swap" })
end

local function capture(id)
  local r = BB.rows[id]
  local status = rb.overlay.status("Press the new key for " .. r.label .. "  ·  Esc cancels")
  local hDown, hScroll, timer
  local function done()
    BB.busy = false
    status.remove()
    if hDown then
      hDown:stop()
    end
    if hScroll then
      hScroll:stop()
    end
    if timer then
      timer:stop()
    end
  end
  hDown = rb.on("down", function(key)
    if not BB.busy then
      return
    end
    if IS_MOD[key] then -- let modifiers through; wait for the real key
      return
    end
    done()
    if key == "Escape" then
      rb.overlay.toast("Nothing changed.")
      return false
    end
    if REFUSE[key] and chord(key) == key then
      rb.overlay.toast("Can't use " .. key .. ": " .. REFUSE[key] .. ".")
      return false
    end
    set_key(id, chord(key))
    return false
  end)
  hScroll = rb.on("scroll", function(delta)
    if not BB.busy then
      return
    end
    done()
    set_key(id, chord(delta > 0 and "WheelUp" or "WheelDown"))
    return false
  end)
  timer = rb.timer.after(10000, function()
    if not BB.busy then
      return
    end
    done()
    rb.overlay.toast("No key pressed. Nothing changed.")
  end)
end

local function reset_all()
  local failed = {}
  for _, id in BB.order do
    if not apply(id, BB.rows[id].default) then
      table.insert(failed, BB.rows[id].label)
    end
  end
  if #failed == 0 then
    rb.overlay.toast("Every hotkey is back to its default.")
  else
    rb.overlay.toast("Couldn't reset: " .. table.concat(failed, ", ") .. ".")
  end
end

function BB.open()
  if BB.busy then
    return
  end
  local items = {}
  for _, id in BB.order do
    table.insert(items, {
      label = BB.rows[id].label,
      hint = shown(cur(id)),
      action = function()
        BB.busy = true
        capture(id)
      end,
    })
  end
  table.insert(items, { label = "Reset all to defaults", action = reset_all })
  table.insert(items, { label = "Done" })
  local m, why = rb.overlay.menu(items, { title = "Edit hotkeys", subtitle = "Pick one, then press the new key" })
  if not m then
    rb.overlay.toast("Can't open the editor: " .. why .. ".")
  end
end

function BB.board(id, default)
  BB.bind(id, "Edit hotkeys", default, BB.open)
end
-- ===== end Bind Board =====

-- Bind Board: every hotkey in this script.
BB.bind("grab_key", "Grab color", GRAB_DEFAULT, grab)
BB.bind("menu_key", "Palette menu", MENU_DEFAULT, openPalette)
BB.board("board", BOARD_DEFAULT)

rb.timer.every(500, function()
  if cfg.reset then
    for k, v in DEFAULTS do
      rb.ui.set(k, v)
    end
    cfg.reset = false
    rb.ui.notify("Palette and Strip settings reset to defaults.", "success")
  end
  if #palette > cfg.max_swatches then
    while #palette > cfg.max_swatches do
      table.remove(palette)
    end
    save()
  end
  redraw()
end)

redraw()
rb.log.info("Swatch Sniper ready")

3 files, 18.5 KB.