Skip to content

Instantly share code, notes, and snippets.

@sans-serif
Last active March 29, 2022 09:43
Show Gist options
  • Save sans-serif/be3ef716d0c6a16d16bf to your computer and use it in GitHub Desktop.
Save sans-serif/be3ef716d0c6a16d16bf to your computer and use it in GitHub Desktop.
[Awesome WM] Random, unique Wallpaper for every tag

Random, unique Wallpaper for every tag in awesome wm

Awesome version >= 3.5

About

This is a way to get a random and unique wallpaper for every tag (or rather the last selected tab, since multiple tags can be selected) in the awesome window manager. The wallpapers are selected randomly from a provided path (which should only contain suitable pictures) and the algorithm guarantees a unique wallpaper for every tag.

Where to place

In the config file for awesome wm, which should be located at

~/.config/awesome/rc.lua

Important: The code snippet has to be below the declaration of tag names!

Code

-- {{{ Tag Wallpaper
-- Set according to wallpaper directory
local path = os.getenv("HOME") .."/.wallpaper/"
-- Set to number of used tags
local num_tabs = 9
-- Other variables
local num_files = 0
local wp_all = {}
local wp_selected = {}
math.randomseed(os.time());
-- To guarantee unique random numbers on every platform, pop a few
for i = 1,10 do
	math.random()
end

-- LUA implementation of PHP scan dir
-- Returns all files (except . and ..) in "directory"
function scandir(directory)
	num_files, t, popen = 0, {}, io.popen
	for filename in popen('ls -a "'..directory..'"'):lines() do
		-- If case to disregard "." and ".."
		if(not(filename == "." or filename == "..")) then
			num_files = num_files + 1
			t[num_files] = filename
		end
	end
	return t
end

-- Basically a modern Fisher-Yates shuffle
-- Returns "tabs" elements from an table "wp" of length "files"
-- Guarantees no duplicated elements in the return while having linear runtime 
function select(wp,files,tabs)
	local selected = {}
	for i=1,tabs do
		position = math.random(1,files)
		selected[i] = wp[position]
		wp[position] = wp[files]
		files = files - 1
	end
	return selected
end

-- Get the names of "num_tabs" files from "num_files" total files in "path"
wp_selected = select(scandir(path),num_files,num_tabs)

-- For each screen
for s = 1, screen.count() do
	-- Set wallpaper on first tab (else it would be empty at start up)
	gears.wallpaper.fit(path .. wp_selected[1], s)
	-- Go over each tab
	for t = 1, num_tabs do
		tags[s][t]:connect_signal("property::selected", function (tag)
		-- And if selected
			if not tag.selected then return end
			-- Set wallpaper
			gears.wallpaper.fit(path .. wp_selected[t], s)
		end)
	end
end
-- }}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment