summaryrefslogtreecommitdiff
path: root/common/bin/random-wallpaper
blob: 2261ca1c271cf13b3e210e00aed682c0081e3c03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/ruby

$sw, $sh = `xrandr --screen 0`
             .split("\n")[0]
             .sub(/^.+current (\d+) x (\d+).+$/, "\\1 \\2")
             .split(" ")
             .map(&:to_i)

$dims = {}
def image_dimensions img
  unless $dims[img]
    iw, ih = `identify -format "%w %h" "#{img}"`
               .split(" ")
               .map(&:to_i)
    $dims[img] = [iw, ih]
  end
  $dims[img]
end

def image_fits? img
  iw, ih = image_dimensions img
  (iw >= $sw && ih >= $sh) &&
    ((iw > ih && $sw > $sh) ||
     (ih > iw && $sh > $sw))
end

def better_fit? new, old
  oiw, oih = image_dimensions old
  niw, nih = image_dimensions new
  if ($sh - nih).abs < ($sh - oih).abs ||
     ($sw - niw).abs < ($sw - oiw).abs
    new
  else
    old
  end
end

def get_appropriate_version img
  upscale = img.sub(/\.(\w+)/, "_upscale.\\1")
  if !image_fits?(img) && File.exist?(upscale)
    return upscale
  end
  crop = img.sub(/\.(\w+)/, "_crop.\\1")
  if File.exist?(crop) && better_fit?(img, crop)
    return get_appropriate_version crop
  end
  return img
end

# def main
#   walldir = ARGV[0] || File.expand_path("~/img/wallpapers")
#   Dir[File.join(walldir, "**/*")]
#     .select {|f| File.file? f }
#     .reject {|img| img =~ /_(upscale|crop)\./ }
#     .shuffle
#     .find do |img|
#       i = get_appropriate_version img
#       if image_fits? i
#         puts i
#         exit
#       end
#     end
# end

def main
  walldir = ARGV[0] || File.expand_path("~/img/wallpapers")
  Dir[File.join(walldir, "**/*")]
    .select {|f| File.file? f }
    .each {|img| puts "#{img}\t#{image_fits? img}" }
end

main if __FILE__ == $0