07 July 2014

Mint 17 Cinnamon: Wallpaper slideshow using crontab

I wanted to have a folder containing lots of pictures that would be used to change my desktop wallpaper every once in a while. If I added more pictures to the folder, they should be included automatically.

Before Mint 17 it was easy to use gsettings in your crontab to do this, but something had changed when they switched to Ubuntu 14.04 instead. I found a nice thread on AskUbuntu (http://askubuntu.com/questions/457016/how-to-change-gsettings-via-remote-shell) which solved a similar problem. I then adapted that solution to my own problem.

It turned out that if you try to run gsettings in crontab, it is missing an environment variable, which can be found using the script below.

1. Save this script file: pastebin link
I put mine in /home/dahlo/tools/wallpaper-change_cinnamon.bash


#!/bin/bash

# Search these processes for the session variable 
# (they are run as the current user and have the DBUS session variable set)
compatiblePrograms=( nemo pulseaudio trackerd nautilus )

# Attempt to get a program pid
for index in ${compatiblePrograms[@]}; do
    PID=$(pidof -s ${index})
    if [[ "${PID}" != "" ]]; then
        break
    fi
done
if [[ "${PID}" == "" ]]; then
    echo "Could not detect active login session"
fi

QUERY_ENVIRON="$(tr '\0' '\n' < /proc/${PID}/environ | grep "DBUS_SESSION_BUS_ADDRESS" | cut -d "=" -f 2-)"
if [[ "${QUERY_ENVIRON}" != "" ]]; then

    export DBUS_SESSION_BUS_ADDRESS="${QUERY_ENVIRON}"
    # echo "Connected to session:"
    # echo "DBUS_SESSION_BUS_ADDRESS=${DBUS_SESSION_BUS_ADDRESS}"

    # Script to randomly set Background from files in a directory

    # Directory Containing Pictures is given via command-line, could be hardcoded in there as well
    DIR=$1

    #DIR="/home/user/Picture"
    #DIR="/home/user/Documents/cultural-festivities/"

    # Command to Select a random jpg file from directory
    # Delete the *.jpg to select any file but it may return a folder
    PIC=$(find $DIR -type f -exec file {} \; | grep -o -P '^.+: \w+ image' | cut -d ':' -f 1 | shuf -n1)

    # Command to set Background Image
    gsettings set org.cinnamon.desktop.background picture-uri "file:///$PIC"



else
    echo "Could not find dbus session ID in user environment."
fi

2. Add it to your crontab and supply the path to the picture folder (/home/dahlo/tools/Wallpapers) as an argument.


# change wallpaper every 5 minutes
*/5 * * * * bash /home/dahlo/tools/wallpaper-change_cinnamon.bash /home/dahlo/tools/Wallpapers 


This will randomly select one of the image files in the folder you specify and use it as your desktop wallpaper.