Created
September 3, 2010 21:39
-
-
Save jterk/564613 to your computer and use it in GitHub Desktop.
I use this script to save and restore window positions on OS X when attaching and removing an external monitor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'appscript' | |
include Appscript | |
DATA_FILE = File.expand_path "~/.saved_windows" | |
# Adium is very special. | |
ADIUM = "Adium" | |
ADIUM_CONTACTS = "Contacts" | |
def marshal_windows(positions) | |
File.open(DATA_FILE, "w+") do |file| | |
Marshal.dump(positions, file) | |
end | |
end | |
def restore_process(process, name, positions) | |
if process && process.exists | |
for i in 0...process.windows.count | |
restore_window(process.windows[i], positions[i]) | |
end | |
if name == ADIUM | |
restore_window(process.windows[ADIUM_CONTACTS], positions[ADIUM_CONTACTS]) | |
end | |
end | |
end | |
def restore_window(window, position) | |
window.position.set(position[:position]) | |
window.size.set(position[:size]) | |
end | |
def restore_windows(processes) | |
positions = unmarshal_windows | |
positions.each do |name, positions| | |
if (processes[name]) | |
restore_process(processes[name], name, positions) | |
end | |
end | |
end | |
def run | |
sys = app("System Events") | |
if ARGV.size != 1 | |
puts "Usage: windows (-save|-restore)" | |
elsif ARGV[0].match /^-s/ | |
save_windows sys.processes.get | |
elsif ARGV[0].match /^-r/ | |
restore_windows sys.processes | |
else | |
puts "Unknown argument #{ARGV[0]}" | |
end | |
end | |
def save_process(process, positions) | |
count = process.windows.count | |
if count > 0 | |
name = process.name.get | |
if name == ADIUM | |
positions[name] = {} | |
positions[name][ADIUM_CONTACTS] = save_window(process.windows[ADIUM_CONTACTS]) | |
else | |
positions[name] = [] | |
end | |
for i in 0...count | |
positions[name][i] = save_window(process.windows[i]) | |
end | |
end | |
end | |
def save_window(window) | |
{:position => window.position.get, :size => window.size.get} | |
end | |
def save_windows(processes) | |
positions = {} | |
processes.each do |process| | |
save_process(process, positions) | |
end | |
marshal_windows(positions) | |
end | |
def unmarshal_windows | |
File.open(DATA_FILE, "r") do |file| | |
Marshal.load(file) | |
end | |
end | |
def usage | |
puts "Usage: windows (-save|-restore)" | |
end | |
run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment