August 7, 2007

A simple stopclock for kde and gnome

Zenity and Kdialog are two awesome applications to rapidly create simple applications with a gui frontend. Needing a simple way to start a timer for a few seconds to minutes, I chose to write a small script using zenity. Translating this later to work on kde with kdialog was an interesting exercise with some things being more difficult, but there being more flexibility too.

Feel free to try these scripts in the DE of your choice. Typing 'stopclock 10' would start a countdown to 10, for example. Not something designed for practical use, but more as a demonstration of the use of zenity and kdialog. Also this is a good illustration of the use of dcop - another very powerful application that is not very well known or documented.

1. stopclock.sh for KDE


#!/bin/sh

if [ $# -ne 1 ]
then
echo $#
echo "Usage: stopclock (number of seconds)"
exit
fi

stime=$(date +%s) #starting time
etime=0 #elapsed time
stoptime=$1 #time at which to stop
ltime=$stoptime #time left

d=$(kstart --ontop --alldesktops kdialog --progressbar "Starting countdown..." $stoptime)
dcop $d setAutoClose true

while [ "$etime" -lt "$stoptime" ]; do
sleep 1
ctime=$(date +%s) #current time
: $((etime=$ctime-$stime))
: $((ltime-=1))
label=$ltime" seconds left"
dcop $d setLabel "$label"
dcop $d setProgress $etime
done


2. stopclock.sh for Gnome


#!/bin/bash

if [ $# -ne 1 ]
then
echo $#
echo "Usage: stopclock (number of seconds)"
exit
fi

stime=$(date +%s) #starting time
etime=0 #elapsed time
stoptime=$1 #time at which to stop
ftime=0 #fraction of time elapsed
label="counting down "$stoptime" seconds"

while [ "$etime" -lt "$stoptime" ]; do
sleep 1
ctime=$(date +%s) #current time
: $((etime=$ctime-$stime))
ftime=$(echo $etime*100/$stoptime | bc -l)
echo $ftime
done | zenity --progress --text="$label"