Tk Source Code

Artifact [b1fdaabf]
Login

Artifact b1fdaabf80dc74c55f75353460d455cc15a425d7:

Attachment "ASCIItoXBM.tcl" to ticket [516751ff] added by ericm 2002-02-13 08:58:12.
# Take ASCII art and make XBM format from it.
proc ::tk::ASCIItoXBM {data} {
    set output ""
    set data [string trim $data]
    set lines [split $data "\n"]
    set h [llength $lines]
    set w [string length [string trim [lindex $lines 0]]]
    
    set data [join $data ""]
    append output "#define bm_width $w\n"
    append output "#define bm_height $h\n"
    append output "static char bm_bits\[\] = {\n"

    # Figure out the width rounded up to the nearest multiple of 8 bits.
    if { $w % 8 != 0 } {
        set paddedWidth [expr {(($w / 8) + 1) * 8}]
    } else {
        set paddedWidth $w
    }


    # Process line by line, because each line has to be padded to a full
    # byte.
    foreach line $lines {
        # Trim whitespace, which often gets in there when you copy off 
        # web pages, etc.
        set line [string trim $line]
        set len [string length $line]
        set rem [expr {$len % 8}]

        # Corner case:  an empty line.  Not sure what the right thing to
        # do is, but setting it to a bunch of zeroes seems OK.
        if { $len == 0 } {
            set line [string repeat "." $paddedWidth]
        } elseif { $rem != 0 } {
            # Pad the line to a multiple of 8.
            append line [string repeat "." [expr {$paddedWidth - $rem}]]
        }

        # Process the data in groups of 8 "bits".
        for {set i 0} {$i < $paddedWidth} {incr i 8} {
            set bits [string range $line $i [expr {$i + 7}]]
            set byte 0
            for {set j 0} {$j < 8} {incr j} {
                set bit [expr {[string index $bits $j] eq "@" ? 1 : 0}]
                set byte [expr {$byte | ($bit << ($j))}]
            }
            append output " [format 0x%02x $byte],"
        }
    }
    append output "};\n"
    return $output
}