grahl/ch

Track when you lock your desktop

Photo CC-BY by way2go

If you do any sort of work where you have to report your activities in 15-minute increments, you have probably experienced that it is very easy to miss things, especially if you often have to deal with interruptions.

There are numerous solutions to parts of this problem such as apps which continuously poke you to update a tracker, to ones which simply log everything and sum it up. I use some of them but I also add another check to my routine to have more accurate timing information when I wasn’t paying attention. What I’m doing is writing timestamps to a file which register screen locks/unlocks as well as suspend and it has in the past year helped me to significantly become more accurate in my tracking by having reference timestamps such as the following excerpt:

Thu Jan 23 09:53:48 CET 2014: SCREEN_UNLOCKED
Thu Jan 23 10:02:21 CET 2014: SCREEN_LOCKED
Thu Jan 23 10:18:16 CET 2014: SCREEN_UNLOCKED
Thu Jan 23 10:27:02 CET 2014: SCREEN_LOCKED

If you want to do this, too, just follow one of the examples below. If you want to do something similar and customize it, the problem is rather trivial if you break it down into a trigger and an action. The first is heavily dependent on your environment, the latter could be anything.

Linux/GNOME

To react to events you’ll have to run a command at login which then continuously monitors DBUS to see if the relevant event has fired. Here is a working example:

$ #!/bin/bash

function write_log {
  if [ -z $1 ]; then
    1="unspecified"
  fi
  echo -e "$1\t$(date)" >> "/home/youruser/time.log"
}

write_log "LOGGED_IN"

# Monitor gnome for screen locking. Log these events.
dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver'" | \
  (
    while true; do
      read X;
      if echo $X | grep "boolean true" &> /dev/null; then
        write_log "SCREEN_LOCKED"
      elif echo $X | grep "boolean false" &> /dev/null; then
        write_log "SCREEN_UNLOCKED"
      fi
    done
  )

OS X

The only decent trigger method I found (albeit after only 15 minutes of googling) is the paid app Scenario. The app itself should be self-explanatory and allows you to put one or several scripts into the respective folders for sleep, lock, log out, etc. Since I’m much more familiar with shell scripting than Applescript, I’m just using the later to call the former. Obviously, this could be simplified.

Applescript in Scenario:

do shell script "~/.bin/screenlock.sh unlock"

Shell script:

#!/bin/bash

if [ $1 = "lock" ]
then
  echo -e "`date`: SCREEN_LOCKED" >> ~/time.log
elif [ "$1" = "unlock" ]
then
  echo -e "`date`: SCREEN_UNLOCKED" >> ~/time.log
else
  echo -e "`date`: UNKNOWN_ACTION" >> ~/time.log
fi