Saturday, January 07, 2012

gnocl::text serialization

The GTK libs include a means of serlizaing/deserializing the contents of a GtkTextBuffer but the documentation on how to craft such handlers is basically non-existent. There is one package OSXCART which will load save a buffer as an rtf which is often discussed but the process of building such handlers is cumbersome and need to be built into the gnocl sources themselves. The whole process is more speedily handled on the Tcl side using the various tag sub-commands which will provide all the necessary information. How does the process work? Each row and column of the text is parsed firsly for changes in tag states (ie on or off) and the for the text content. If a new tag is added, its name is kept in a list of applied tags. The text is then accumulated until a further tag state change occurs whereupon firstly the tag and then text changes are written an output string. The text accumulator is then reset to empty and so the process continues. If a tag is turned off, the reverse occurs; the text is first written followed by the names of tags turned off.

The following module contains two procs, serealize and desearialize. Only tags are supported at the moment but, if necessary, marks, images and widgets could be supported too.

#---------------
# textSerialize.tcl
#---------------

#---------------
# deserialize utf8 text string and insert into widget
#---------------
# Arguments
#    data    text to deserialze
#    w       
# Returns
#    serialized text string
# Notes    
proc gnocl::textDeserialize {data txt} {
    set onTAGS {}
   
    foreach {a b} $data {
        if {$a == "tags"} {
            # apply taglist to new widget
            foreach c $b { eval "$txt tag create $c" }
        }
        if {$a == "text"} {
            foreach {c d} $b {
                switch $c {
                    tagOn {
                        lappend onTAGS $d
                    }
                    tagOff {
                        set i [lsearch $onTAGS $d]
                        set onTAGS [lreplace $onTAGS $i $i] ;# remove tag from list
                    }
                    text {
                        if {$onTAGS != {}} {
                            $txt insert end $d -tags $onTAGS
                        } else {
                            $txt insert end $d
                        }
                    }
                } ;# end switch
            } ;# end foreach
        } ;# end if
    }
}

#---------------
# obtain text contents from text widget and return as a serialized utf8 string
#---------------
# Arguments
#    txt        gnoc::text widget whose contents are to serialized
# Returns
#    serialized text in the form of a paired list of op-val
# Notes
#    tagOn tag1 text {abc} tagOff tag1 text {def}    
#---------------
proc gnocl::textSerialize {txt} {
    set str(1) {}    ;# output string, ie tags + text
    set str(2) {}    ;# the text itself
    set onTAGS {}    ;# active tage
    set tagOn {}
    set tagOff {}
   
    # create tag table
    foreach {a}  [$txt tag names ] { lappend ttable "$a [$txt tag properties $a]" }
   
    # parse the text to obtain tag changes before text content     
    for {set r 0} { $r < [$txt getLineCount ] } {incr r} {
       
        for {set c 0} { $c <= [$txt getLineLength $r ] } {incr c} {
                   
            if {$c == 0} {
                set tagOn  [$txt tag get [::list $r [expr $c -1]] -on  ]
            } else {
                set tagOn  [$txt tag get [::list $r $c ] -on  ]
                set tagOff [$txt tag get [::list $r $c ] -off ]
            }
           
            # handle tagOff       
            if {$tagOff != ""} {
                foreach t $tagOff {
                    set i [lsearch $onTAGS $t]
                    set onTAGS [lreplace $onTAGS $i $i] ;# remove tag from list
                    append str(1) "text [::list $str(2)] tagOff $t "
                    set str(2) ""
                }
            }

            # handle tagOn
            if { $tagOn != "" } {
                foreach t $tagOn {
                    # check for new tag state changes
                    if { [lsearch $onTAGS $t] == -1} {
                        # first item is a special case
                        if {$r == 0 && $c == 0} {
                            set str(1) "tagOn $t "
                            set onTAGS $t
                            continue
                        }
                        #--------------
                        append str(1) "text [::list $str(2)] "
                        set str(2) ""
                        #--------------                       
                        append str(1) "tagOn $t "
                        lappend onTAGS $t
                    }
                }           
            }
           
            # get text
            append str(2) [$txt get [::list $r $c ] [::list $r [expr $c+1] ] ]
        }
    }
   
    if {$str(2) != {}} {
        append str(1) "txt [::list $str(2)] "
    }
   
    return "tags [::list $ttable]\ntext [::list [string trim $str(1)]]"
}








Sunday, January 01, 2012

Release 0.9.96

Just uploaded the latest stable release to Sourceforge. It been some time since the last major release and a of enhancements have been made. For me the next milestone was implementing the recentFiles functionality available through Gtk+. This is working, although a lot more options and commands need to be implemented for the gnocl::recentManager widget. Having said that, though, I can see that bulk of the functionality would only be rarely used.

Regular readers of this blog may have noticed that the posts have reduced over the past few months. This isn't due to any loss of interest in Gnocl, far from it! I've also been working on my own translation tools which, I have to say, is the basic fuel which keeps the development work going.

Over the past four years or so that I've been working on Gnocl an awful lot of code has been added to the sources. Code that not only provide Tcl access to Gtk resources but provides a whole lot of advanced features which makes coding a breeze.

Happy 2012!!!

Wednesday, December 14, 2011

More on Pango Markup Strings

I don't like fiddling around with markup strings, even at the best of times. So, any convienient way of producing the right formatting is welcome news to me. Gtk widgets allow markupstrings for various text elements. So, I thought, how about creating strings on the fly using familiar Tcl means. Hence the following two procs below. One will create markup and the other remove it. The removal method is still basic, it will also strip out markup-like items such as <b> so its use is limited. It is also assumed that there will only be one "<span"  entry per string. Modifying the code to remove more that one <span group should not be too much of an issue.

The need behind creating these procs comes from wanting to quickly add/remove markup strings from tree/listview cells.

#---------------
# pango_string.tcl
#---------------
# !/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"
package require Gnocl

#---------------
# Create Pango formatted string.
#---------------
# Arguments
#    str        The text string to format.
#    args    Matched pair of options and values.
# Returns
#---------------
proc pango_string {str args} {
    set span_str ""
    foreach {a b} $args {
        puts "a = $a b = $b"
        switch -- $a {
            -big {
                if {$b} {set str  "<big>$str</big>" }
                }
            -bold {
                if {$b} { set str  "<b>$str</b>" }
                }
            -italic {
                if {$b} { set str  "<i>$str</i>" }
                }
            -small {
                if {$b} { set str  "<small>$str</small>" }
                }
            -strikethrough {
                if {$b} { set str  "<s>$str</s>" }
                }
            -sub {
                if {$b} { set str  "<sub>$str</sub>" }
                }
            -sup {
                if {$b} { set str  "<sup>$str</sup>"}
                }
            -tt {
                if {$b} { set str  "<tt>$str</tt>" }
                }
            -bg -
            -bgClr -
            -background {
                append span_str " background=\"$b\""
                }
            -fallback {
                append span_str " fallback=\"$b\""
                }
            -font {
                append span_str " font=\"$b\""
                }
            -fg -
            -fgClr -
            -foreground {
                append span_str " foreground=\"$b\""
                }
            -gravity {
                append span_str " gravity=\"$b\""
                }
            -gravityHint {
                append span_str " gravity_hint=\"$b\""
                }               
            -lang {
                append span_str " lang=\"$b\""
                }
            -rise {
                append span_str " rise=\"$b\""
                }
            -style {
                append span_str " style=\"$b\""
                }   
            -size {
                append span_str " size=\"$b\""
                }
            -letterSpacing {
                append span_str " letter_spacing=\"$b\""
                }
            -stretch {
                append span_str " stretch=\"$b\""
                }
            -strikethroughColor {
                append span_str " strikethrough_color=\"$b\""
                }
            -underline {
                if {$b == 1} {
                    set str  "<u>$str</u>"
                    } else {
                    append span_str " underline=\"$b\""
                    }
                }
            -underlineColor {
                append span_str " underline_color=\"$b\""
                }
            -variant {
                append span_str " size=\"$b\""
                }
            -weight {
                append span_str " size=\"$b\""
                }

        }
    }
   
    if {$span_str != ""} {
        set str "<span $span_str>$str</span>"
    }
   
    return $str
}


if {1} {
    set box [gnocl::box -orientation vertical]

    for {set i 0} {$i <= 5} {incr i} {
        set lab($i) [gnocl::label]
        $box add $lab($i)
    }

    $lab(0) configure -text [pango_string "Hello World" -bold 1]
    $lab(1) configure -text [pango_string "Hello World" -bold 1 -foreground red]
    $lab(2) configure -text "[pango_string "Hello" -bold 1 -foreground red] [pango_string "World" -bold 1 -foreground blue -italic 1]"
    $lab(3) configure -text "[pango_string "Hello" -stretch ultraexpanded -bold 1 -foreground red] [pango_string "World" -bold 1 -foreground blue -italic 1]"
    gnocl::window -child $box
}

#---------------
# Remove pango formatting from a string.
#---------------
# Arguments
#    str        string with pango markup
# Returns
#    plain text string
# Notes
#   Use with caution.
#    Will also strip <u> etc., from within text strings.
#---------------
proc pango_remove {str} {
    set str [string map {
        <u>     "" </u>     ""
        <b>     "" </b>     ""
        <i>     "" </i>     ""
        <s>     "" </s>     ""
        <big>   "" </big>   ""
        <small> "" </small> ""
        <sub>   "" </sub>   ""
        <sup>   "" </sup>   ""
        <tt>    "" </tt>    ""
        </span> ""
    } $str]

    # remove span
    set i [string first "<span" $str]
    if {!$i} {
        set j [string first ">" $str]
        set str [string range $str [incr j] end]
    }


    return $str
}

if {1} {
    set markup(block) "-fg red -bold 1"
    set str [eval pango_string "NO-<b>PANGO" $markup(block) ]
    puts $str
    puts ==|[pango_remove $str]|==
}


Sunday, December 11, 2011

gnocl::list add

I've finished taking a look at enhancing the add sub-command ensuring bakcward compatibility with the legacy effects. This snippet shows how it works:

widget-id add rowNum data options

$list add    { "A" 1 } -singleRow 1    ;# 1
$list add {} { "B" 2 } -singleRow 1    ;# 2
$list add  0 { "C" 3 } -singleRow 1    ;# 3
$list add -1 { "D" 4 } -singleRow 1    ;# 4
$list add  3 { "E" 5 } -singleRow 1    ;# 5

In order for the interpretor to know which row to use the second argument needs to be an integer. '0' means insert at the top of the list with -1 the bottom. In a pre-existing list, any other positive value in between will insert at the appropriate level. If the specified row is a value that exceeds the length of the list, the item will be appended to the end.
The command returns the number of the row just inserted.

Finally, providing a non integer values will also result in appending the value to the bottom of the list unless an empty string is provided which will prepend the entry to the top.

PS> Just noted that setting the -singleRow option is compulsory rather than an option! I'll look at this later today.






Saturday, December 10, 2011

**NEW COMMAND** gnocl::showURI

A simple wrapper around the gtk_show_uri utility function. This will launch the GNOME default applications for mailing and browsing.

Rather than explicitly calling a browser with:

$m4 configure -onClicked "
        exec firefox http://www.buddhism-dict.net/cgi-bin/xpr-ddb.pl?q=[$w get selectionStart selectionEnd] &
        "


The same effect can be achieved with

$m4 configure -onClicked "
        gnocl::showURI "http://www.buddhism-dict.net/cgi-bin/xpr-ddb.pl?q=[$w get selectionStart selectionEnd]
        "


Tuesday, November 29, 2011

gnocl::text new option -data, new command cget

Been adding a few tweaks to the code today. Added the -data option and the cget command. Also slightly modified the percentage substitution strings for the gnocl::entry -onIconPress event handler. Hitherto %t would have provided details about a the mousebutton event. It makes more sense to us %b allowing %t to be used to substitute the contents of the entry buffer.

Finally, I'm working on a simple text editing widget to add to the gnocl::megawidgets package. Its nothing fancy, no rich text editing, just a simple scribble pad to embed in those app which might need it!

Wednesday, November 16, 2011

gnocl::paned

Ok, there's not much left to do with this one but... Added a cget command which enable some simple querying. Still working on the binding for the handle move. For some reason there's no binding for mouse operations, just keyboard adjustment.

json_shell_utils.tcl