Really having things my way

In yesterday’s post about implementing keyboard shortcuts to control headphone volume, I noted at the end that I wasn’t happy with the look of the passive feedback display that kdialog provided. I am happy to report that I’ve found a solution.

The default volume control feedback (triggered by Fn+F?) is provided by a KDE daemon called kmilo. On a hunch, I poked around the DCOP interface exposed by kmilod and much to my joy, it provides functions called displayProgress and displayText - just what I needed! Herewith, the updated script:

#!/bin/sh
# vol.sh
# by deepak sarda
# public domain

# functions
usage() {
    echo "Usage: $0 (less|more|mute)"
}

popup() {
    # echo "$*"
    # display popup with 1 second delay. Also, background the process so that
    # script doesn't block. This lets us invoke the script in quick succession.
    kdialog --title "Headphone" --passivepopup "$*" 1 &
}

displayProgress() {
    if [ $kmilo ]; then
        dcop kded kmilod displayProgress "$1" "$2" &
    else
        popup "$1 $2%"
    fi
}

displayText() {
    if [ $kmilo ]; then
        dcop kded kmilod displayText "$*" &
    else
        popup $*
    fi
}

currentVol() {
    current_vol=`$app absoluteVolume $dev`
    return $(($current_vol*100/$max_vol))
}

# Usage check
if [ $# -ne 1 ]; then
    usage
    exit
fi

kmilo=`dcop kded | grep -m 1 ^kmilod`

if [ ! `dcop | grep -m 1 ^kmix` ]; then
    displayText "kmix not found"
    exit
fi

app="dcop kmix `dcop kmix | grep ^Mixer`"
dev=2 # The headphone is device index 2 on my system
max_vol=`$app absoluteVolumeMax $dev`

if [ "$1" = "less" ]; then
    $app decreaseVolume $dev
    currentVol
    displayProgress "Headphone Volume" $?
elif [ "$1" = "more" ]; then
    $app increaseVolume $dev
    currentVol
    displayProgress "Headphone Volume" $?
elif [ "$1" = "mute" ]; then
    $app toggleMute $dev
    if [ `$app mute $dev` = "true" ]; then
        displayText "Headphone mute on"
    else
        displayText "Headphone mute off"
    fi
else
    usage
fi