Sunday, January 27, 2013

Checking to see which entry has the active input focus.

Gtk provides no simple way telling a calling program which entry widget contains the active keyboard focus. Specific widgets can be interrogated as to whether they possess keyboard input focus on either a global scale or simply within their own toplevel window. My own pet project is working on the translation of Chinese texts and the api of my translation editor will have multiple editable widgets on screen at any one time. Up till now I've used focus events to set a global variable identifying which widget has focus, but there are other ways. Today I just added the hasToplevelFocus and has hasGlobalFocus commands to the gnocl::text widget. There always was, of course the option to use cget -hasFocus. Here's my test script.

#---------------
# test-chinese-punct-toolbar.tcl
#---------------
#
#!/bin/sh
#\
exec tclsh "$0" "$@"

package require Gnocl

#---------------
# insert punc mark it currently active text
#---------------
proc do_chn_punc { mark } {

    foreach w $::texts {
        if { [$w isToplevelFocus] == 1 } {
            $w insert cursor $mark
        }
    }
}

#---------------
# Insert punctuation marks suited to differing character sets.
#---------------
proc chn_punc { {type jianti} } {

    set marks {
        。    {Full Stop}
        ‘    {Open Single Quote}
        “    {Open Double Quote}
        ”    {Close Double Quote}
        ’    {Close Single Quote}
        、    {Enumeration comma}
        ‧    {Middle dot}
        《    {Open Double Title Mark}
        》    {Close Double Title Mark}
        ……    {Ellipsis}
        ——    {Em Dash}
        —    {En Dash}
        ~    {Wavy Dash}
        }

    if {$type eq "fanti" } {   
    set marks {
        。    {Full Stop}
        「    {Open Single Quote}
        『    {Open Double Quote}
        』    {Close Double Quote}
        」    {Close Single Quote}
        、    {Enumeration comma}
        ‧    {Middle dot}
        《    {Open Double Title Mark}
        〈    {Open Single (Section) Title Mark}
        〉    {Close Single (Section) Title Mark}
        》    {Close Double Title Mark}
        ……    {Ellipsis} 
        ——    {Em Dash}
        —    {En Dash}
        ~    {Wavy Dash}
    } }

    set tb [gnocl::toolBar -style text ]
       
    foreach {mark tip} $marks {
        $tb add item \
            -icon %#New \
            -text $mark \
            -tooltip $tip \
            -onClicked "do_chn_punc $mark"
    }
   
    return $tb
}


set box [gnocl::box -orientation vertical]
set txt(1) [gnocl::text -baseFont {Serif 12}]
set txt(2) [gnocl::text -baseColor #D1FEFF -baseFont {Serif 14}]
gnocl::window -child $box
$box add [chn_punc]
$box add [chn_punc fanti]
$box add $txt(1)
$box add $txt(2)

# list of available texts
set texts [list $txt(1) $txt(2)]
puts $texts

$txt(1) grabFocus





No comments: