Skip to content

Instantly share code, notes, and snippets.

@bankair
Created April 28, 2017 12:44
Show Gist options
  • Save bankair/81fd1494fe48ef9723238075385e18ae to your computer and use it in GitHub Desktop.
Save bankair/81fd1494fe48ef9723238075385e18ae to your computer and use it in GitHub Desktop.
require 'rumouse'
class Position
class << self
def mouse
@mouse ||= RuMouse.new
end
def current
new(*mouse.position.values)
end
def parse(str)
new(*str.split(';'))
end
end
attr_accessor :x, :y
def initialize(x, y)
self.x = x.to_f
self.y = y.to_f
end
def to_s
[x,y].join(';')
end
def -(other)
(x - other.x) ** 2 + (y - other.y) ** 2
end
def activate!
self.class.mouse.move(x, y)
self.class.mouse.press(x, y)
sleep(0.1)
self.class.mouse.release(x, y)
end
end
class Configuration
PATH = File.join(Dir.home, '.screenswap.csv')
class << self
def load!
unless File.exists?(PATH)
puts 'No configuration file found'
exit(1)
end
File.readlines(PATH).map { |line| positions << Position.parse(line) }
self
end
def check_presence!
if File.exist?(PATH)
puts "Configuration file #{PATH} already exists."
puts "[Q]uit/[r]eplace"
choice = gets.chomp
case choice.downcase
when '', 'q'
exit(0)
when 'r'
puts "Replacing file #{PATH}"
else
puts "Invalid choice #{choice.inspect}."
exit(1)
end
end
end
def positions
@positions ||= []
end
def save!
File.open(PATH, 'w') { |file| positions.each { |position| file << position } }
end
def record!
check_presence!
Kernel.loop do
puts 'Record another position?'
puts '[Y]es/[n]o'
choice = gets.chomp
case choice.downcase
when 'y'
record_position!
when 'n'
return
else
puts "Invalid choice #{choice.inspect}"
end
end
end
def record_position!
puts 'Recording position in 5 seconds'
5.times { |i| puts(5 - i); sleep(1)}
positions << "#{Position.current}\n"
save!
end
end
end
require 'optparse'
options = {}
OPTIONS_PARSER = OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} [options]"
opts.on('-c', '--configure', 'Create or replace the configuration file ($HOME/.screenswap.yml') do |c|
options[:configure] = true
end
opts.on('-h', '--help', 'Display the usage information') { puts(opts) && exit }
end
OPTIONS_PARSER.parse!
unless ARGV.empty?
puts(OPTIONS_PARSER)
exit(1)
end
if options[:configure]
Configuration.record!
exit(0)
end
positions = Configuration.load!.positions
if positions.empty?
puts 'No position found'
exit(1)
end
current = Position.current
distance = nil
index = nil
positions.each_with_index do |position, j|
current_distance = current - position
if index == nil || distance > current_distance
distance = current_distance
index = j
end
end
target = (positions[(index + 1) % positions.size])
target.activate!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment