Created
January 28, 2017 22:54
-
-
Save shurizzle/c24e43ccd7e28bcefa5dd887eb6f794b to your computer and use it in GitHub Desktop.
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 'uri' | |
require 'open-uri' | |
require 'tmpdir' | |
require 'open3' | |
module MacOS | |
module Desktop | |
BACKGROUND_TEMPLATE = "tell application \"Finder\"\n set myFile to POSIX file %s as string\n set desktop picture to file myFile\nend tell" | |
def self.background=(image) | |
begin | |
img = URI(image).read | |
image = nil | |
if img.content_type =~ /^image\/(.*)$/ | |
Dir::Tmpname.create(['background', ".#{$1}"], Dir.home) do |tmpname, n, opts| | |
mode = File::RDWR | File::CREAT | File::EXCL | |
perm = 0600 | |
if opts | |
mode |= opts.delete(:mode) || 0 | |
opts[:perm] = perm | |
perm = nil | |
else | |
opts = perm | |
end | |
tmpfile = File.open(tmpname, mode, opts) | |
begin | |
tmpfile.write img | |
image = tmpname | |
ensure | |
tmpfile.close | |
end | |
end | |
end | |
rescue URI::InvalidURIError | |
end | |
if File.readable?(image) | |
image = File.realpath(image) | |
p image | |
osa_command = BACKGROUND_TEMPLATE % [image.inspect] | |
_, s = Open3.capture2('/usr/bin/osascript', :stdin_data => osa_command) | |
return s.success? | |
end | |
false | |
end | |
end | |
end | |
if ARGV.size != 1 | |
$stderr.puts "USAGE: $0 <path/to/image or URL>" | |
exit 1 | |
end | |
MacOS::Desktop.background = ARGV[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment