Skip to content

Instantly share code, notes, and snippets.

@gpoulter
Last active May 2, 2023 10:45
Show Gist options
  • Save gpoulter/bef645c26949e317bf534560b99a6e49 to your computer and use it in GitHub Desktop.
Save gpoulter/bef645c26949e317bf534560b99a6e49 to your computer and use it in GitHub Desktop.
Log active application window every few seconds
#!/usr/bin/fish
# Regularly logs the active application and window title to a CSV file.
# Project name to include in the filename.
set project "none"
# Duration in seconds of samples, sleep until timestamp divisible.
set duration 60
# Directory in which to write CSV files.
set dir "$HOME/Documents/Tracking"
# Process arguments
argparse -n winstats 'p/project=' 'd/duration=' -- $argv or exit 1
set -q _flag_project; and set project $_flag_project
set -q _flag_duration; and set duration $_flag_duration
# True if intro printed.
set printed_intro ""
# Headings for CSV columns.
set csvheader 'Date,Duration,Project,Application,Title'
# Time tracking loop
while true
# Sleep to align time to duration-length intervals.
set time_secs (date +%s)
sleep (math $duration - $time_secs % $duration)
# Get minute-aligned date and time
set datetime (date +'%Y-%m-%d %H:%M:%S')
# Set up year directory
set yeardir $dir/(date +%Y)
if test ! -d $yeardir
mkdir $yeardir
end
# Set up log file
set logfile $yeardir/(date +%Y-%m-%d.csv)
if test ! -f $logfile
echo $csvheader > $logfile
end
if ! set -q printed
echo "Writing to" $logfile
echo $csvheader
set printed "true"
end
# Write a log line
set -l focused_window_id (xprop -root 32x '\t$0' _NET_ACTIVE_WINDOW | cut -f 2)
set -l window_title (xprop -id $focused_window_id WM_NAME | string match -g -r '"([^"]*)"')
set -l window_classes (xprop -id 0x2000190 WM_CLASS | string match -a -g -r '"([^"]*)"')
set -l window_class $window_classes[-1]
echo "$datetime,$duration,$project,\"$window_class\",\"$window_title\"" | tee --append $logfile
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment