Skip to content

Instantly share code, notes, and snippets.

@lrewega
Created September 8, 2018 02:23
Show Gist options
  • Select an option

  • Save lrewega/26d14a89766192b12a664f1da34303f1 to your computer and use it in GitHub Desktop.

Select an option

Save lrewega/26d14a89766192b12a664f1da34303f1 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"flag"
"fmt"
"math/rand"
"os"
"os/exec"
"time"
"github.com/fogleman/gg"
_ "github.com/mattn/go-sqlite3"
)
func updateWallpaper(filename string) error {
const dbPath = "$HOME/Library/Application Support/Dock/desktoppicture.db"
db, err := sql.Open("sqlite3", os.ExpandEnv(dbPath))
if err != nil {
return err
}
defer db.Close()
const statement = `
delete from preferences;
update data set value = ?;
insert into preferences
select
1, -- Wallpaper key
data.ROWID,
pictures.ROWID
from pictures
inner join data
on data.value = ?;
`
_, err = db.Exec(statement, filename, filename)
return err
}
// restartDock kills the Dock process, which restarts immediately, and updates
// the wallpaper at start.
func restartDock() error {
return exec.Command("killall", "Dock").Run()
}
// randomImage produces a 3x3 PNG image with random pixel colors and writes it
// to the given outputFilename.
func randomImage(outputFilename string) error {
rng := rand.New(rand.NewSource(time.Now().Unix()))
dc := gg.NewContext(3, 3)
for y := 0; y < 3; y++ {
for x := 0; x < 3; x++ {
dc.SetRGB(rng.Float64(), rng.Float64(), rng.Float64())
dc.SetPixel(x, y)
}
}
return dc.SavePNG(outputFilename)
}
func usage() {
fmt.Fprintf(flag.CommandLine.Output(), "usage: %s [<image>]\n", os.Args[0])
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
filename := os.ExpandEnv("$HOME/.wallpaper.png")
switch len(os.Args) {
default:
flag.Usage()
os.Exit(1)
case 1:
// no arguments
if err := randomImage(filename); err != nil {
fmt.Fprintf(os.Stderr, "error writing image to %q: %v", filename, err)
os.Exit(2)
}
case 2:
filename = os.Args[1]
info, err := os.Stat(filename)
if err != nil && !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "error accessing file %q: %v", filename, err)
os.Exit(3)
} else if !info.Mode().IsRegular() {
fmt.Fprintf(os.Stderr, "file %q can't be used as it's not a regular file.", filename)
os.Exit(4)
}
}
if err := updateWallpaper(filename); err != nil {
fmt.Fprintf(os.Stderr, "error setting wallpaper: %v", err)
os.Exit(5)
}
if err := restartDock(); err != nil {
fmt.Fprintf(os.Stderr, "error restarting dock: %v", err)
os.Exit(6)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment