#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"

load ../src/gnocl.so

set target [gnocl::box -label "Drag'n Drop Target" -orientation vertical]
gnocl::dnd setDestination $target \
      {STRING text/plain text/uri-list application/x-color} \
      {dropFunc %T %t %l %d}

proc dropFunc { type time length data } {
   puts "drop type: $type"
   puts "time: $time"
   puts "length: $length"
   puts -nonewline "data length: "
   puts -nonewline [string bytelength $data]
   puts -nonewline " != "
   puts [string length $data]
   puts $data
   switch -- $type {
      application/x-color { 
            binary scan $data s4 val
            # print unsigned 16 bit integer
            foreach el $val {
               puts -nonewline [format "%4d " \
                     [expr {($el + 0x10000) % 0x10000}]]
            }
            puts ""
            # print unsigned 8 bit integer
            foreach el $val {
               puts -nonewline [format "%4d " \
                     [expr {(($el + 0x10000) % 0x10000)>>8}]]
            }
            puts "" }
   }
   puts ""
}

set source [gnocl::box -label "Drag'n Drop Source" -orientation vertical]
set box [gnocl::box -orientation vertical]
$box add "$target $source"

set lab [gnocl::eventBox -child [gnocl::label -text "STRING: \"some text\""]]
gnocl::dnd setSource $lab {STRING} {dragFunc %T "some text" }
$source add $lab

set lab [gnocl::eventBox -child \
      [gnocl::label -text "text/plain: \"other text\""]]
gnocl::dnd setSource $lab {text/plain} {dragFunc %T "other text" }
$source add $lab

set val "\[]}{$; "
set lab [gnocl::eventBox -child [gnocl::label -text $val]]
# escape the "$", otherwise $val would be evaluated when executing
# the callback function
gnocl::dnd setSource $lab {STRING text/plain} "dragFunc %T \$val" 
$source add $lab

set lab [gnocl::eventBox -child \
      [gnocl::label -text "application/x-color: 1234"]]
gnocl::dnd setSource $lab {application/x-color} \
      {dragFunc %T [binary format s4 {1 2 3 4}] }
$source add $lab

proc dragFunc { targets val } {
   puts "drag target: $targets\n"
   return $val
}


if { $argc == 1 } {
   set win [gnocl::plug [lindex $argv 0] -child $box]
} else {
   set win [gnocl::window -child $box -width 200 -height 200]
}

gnocl::mainLoop

