Monday, April 11, 2011

konsole tabs with dbus in kde4.6

In the continuing automation saga with konsole at my job, KDE has come far enough with the dbus interface in 4.6 to allow me to bring up tabs again and perform actions in them with a script.

For this I created the following shell functions:


# konsole dbus functions
newtab()
{
dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply /konsole/MainWindow_1 org.kde.KMainWindow.activateAction string:"new-tab"
}

renametab()
{
sessionno=$1
tabname=$2
session="/Sessions/${sessionno}"
dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply ${session} org.kde.konsole.Session.setTabTitleFormat int32:0 string:"$tabname"
dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply ${session} org.kde.konsole.Session.setTabTitleFormat int32:1 string:"$tabname"
dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply ${session} org.kde.konsole.Session.setTitle int32:1 string:"$tabname"
}

sendtab()
{
sessionno=$1
cmd=$2
session="/Sessions/${sessionno}"
" dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply ${session} org.kde.konsole.Session.sendText string:"$cmd
}

closetab()
{
dbus-send --session --dest=${KONSOLE_DBUS_SERVICE} --type=method_call --print-reply ${KONSOLE_DBUS_SESSION} org.kde.konsole.Session.close
}



In scripts that I want automation, I include these functions:


# konsole functions
. ~/bin/kons-fn.sh



I can then open a whole bunch of tabs at once and send them a command:



PORTS=( 2022 2021 )

SESSIONS="
A_FU
B_BAR
"

command="telnet ${CONSOLE_SERVER}"

j=1
index=0
for i in ${SESSIONS}
do
newtab
let index=$j-1
let j=$j+1
renametab $j $i
sendtab $j "${command} ${PORTS[${index}]}"
done

closetab
exit 0



However I haven't gotten this to work from starting 'konsole -script' from a shortcut. Launching a script like this creates an infinite number of tabs launching the script in sequence. Very weird stuff.

For now, just start a konsole session and launch the script within the first tab. As you can deduce from the functions, it has to be the first tab you launch konsole with.