source: tol/tolbaseBLT/lib/byswidget/btreeviewplus/btreeviewplus.tcl @ 56ade3b

1941-docker-image-to-testdevel
Last change on this file since 56ade3b was 56ade3b, checked in by Jorge Pérez <josp.jorge@…>, 10 years ago

fixes #1932, se ha creado la rama trunk/tolbaseBLT copia de trunk/tolbase

git-svn-id: ​https://www.tol-project.org/svn/tolp/trunk@7330 be4846ae-f051-483a-831f-b64e7d08527f

  • Property mode set to 100644
File size: 37.7 KB
Line 
1#/////////////////////////////////////////////////////////////////////////////
2# FILE    : btreeviewplus.tcl
3# PURPOSE : Bayes Tree View. Tree View con un menu contextual y añadidos
4#/////////////////////////////////////////////////////////////////////////////
5
6package require byscommon
7package require BLT
8package require bfunctions
9package require bfieldsdialog
10
11
12#/////////////////////////////////////////////////////////////////////////////
13::snit::widget btreeviewplus {
14#
15# PURPOSE: Treeview con menu contextual y caracteristicas adicionales
16#
17#/////////////////////////////////////////////////////////////////////////////
18# opciones especificas
19# readonly -> componente en modo de lectura o lectura/escritura
20# keypress -> Activa la busqueda de filas mediante la pulsacion de teclas
21# cols -> columnas del treeview no tiene en cuenta el "valor" principal
22# hiddencols -> columnas del treeview que no se mostraran
23# filtercols -> columnas del treeview que por las que puede realizarse filtrado
24# initialdir -> directorio inicial para los dialogos de lec/esc de archivos,...
25# orientation -> orientacion para el diálogo de añadir
26# nomenu -> Si es 1, no se mostrará el menu contextual
27# showtitles -> muestra o no los titulos de las columnas
28# dragable -> Habilita o Deshabilita entorno Drag and Drop entre Elementos
29#
30# variables
31# treeview -> el treeview de BLT sobre el que sobrecargamos funcionalidad
32# menu -> el menu contextual del treeview
33# xbar -> horizontal scrollbar
34# ybar -> vertical scrollbar
35# afterTime -> tiempo desde que se pulso la ultima tecla
36# listKey -> lista de teclas pulsadas
37#/////////////////////////////////////////////////////////////////////////////
38  widgetclass Btreeviewplus
39
40  option -readonly    0
41  option -keypress    true
42  option -colkeypress "" 
43  option -cols {}
44  option -hiddencols {}
45  option -filtercols {}
46  option -initialdir {}
47  option -orientation vertical
48  option -showtitles true
49  option -nomenu 0
50  #pedro - DragNDrop Boolean
51  option -dragable 0
52
53  variable _treeview
54  variable _menu
55  variable xbar
56  variable ybar
57  variable created 0
58 
59  variable afterTime 0
60  variable listKey   {}
61
62  delegate method * to _treeview
63  delegate option * to _treeview
64
65  #///////////////////////////////////////////////////////////////////////////
66  constructor {args} {
67  #
68  # PURPOSE: Constructor de un btreeviewplus. Crea una instancia de un Treeview
69  #
70  # PARAMETERS:
71  #   args -> opciones
72  #
73  #///////////////////////////////////////////////////////////////////////////
74
75    if {0} {
76      install _treeview using ::blt::treeview $self.tv \
77          -activeicons "" -icons {} -selectmode multiple \
78          -selectbackground grey -selectforeground white \
79          -highlightthickness 0 -borderwidth 1 -selectborderwidth 1 \
80          -nofocusselectbackground gray90 -font {Arial 9} -flat no
81    } else {
82      set _treeview [::blt::treeview $win.tv \
83                         -activeicons "" -icons {} -selectmode multiple \
84                         -selectbackground grey -selectforeground white \
85                         -highlightthickness 0 -borderwidth 1 -selectborderwidth 1 \
86                         -nofocusselectbackground gray90 -font {Arial 9} -flat no]
87    }
88
89    install _menu using menu $win.m -tearoff 0
90    install xbar using scrollbar $win.sbh -orient horizontal \
91                                           -command "$_treeview xview"
92    install ybar using scrollbar $self.sbv -orient vertical \
93                                           -command "$_treeview yview"
94
95    $_treeview style  configure text     -bg white
96    $_treeview column configure treeView -bg white
97
98    $self configure -readonly [from args -readonly]
99    $self _CreateMenu
100
101    $_treeview column configure [list BLT TreeView $_treeview] -titleborderwidth 1
102   
103    # Apply all arguments given:
104    $self configurelist $args
105    $_treeview configure -xscrollcommand "$xbar set"
106    $_treeview configure -yscrollcommand "$ybar set"
107   
108    # bind
109    $_treeview bind all <KeyPress> +[list $self _OnKeyPress %A]
110   
111    $self configure -nomenu [from args -nomenu]
112    $self configure -filtercols [from args -filtercols]
113   
114    # packing
115    grid $_treeview -row 0 -column 0 -sticky news
116    grid $ybar -row 0 -column 1 -sticky ns
117    grid $xbar -row 1 -column 0 -sticky ew
118    grid columnconfigure $self 0 -weight 1
119    grid rowconfigure    $self 0 -weight 1
120
121    ::autoscroll::autoscroll $ybar
122    ::autoscroll::autoscroll $xbar
123    set created 1
124  }
125
126  #///////////////////////////////////////////////////////////////////////////
127  #
128  # PURPOSE: Metodos cget y configure
129  #
130  #///////////////////////////////////////////////////////////////////////////
131
132  onconfigure -cols { lst } {
133   set options(-cols) $lst
134     foreach col [$self column names] {
135       $self column delete $col
136     }
137     foreach col $options(-cols) {
138       $_treeview column insert end $col -justify left
139       $_treeview column configure $col -command "$self _SortByColumn [list $col]" \
140           -titleborderwidth 1
141     }
142  }
143
144  onconfigure -hiddencols { lst } {
145    set options(-hiddencols) $lst
146    foreach col [$self column names] {
147      if { "-1" eq [lsearch $options(-hiddencols) $col] } {
148        $_treeview column configure $col -hide 0
149      } else {
150        $_treeview column configure $col -hide 1
151      }
152    }
153  }
154
155  onconfigure -showtitles { bool } {
156    set options(-showtitles) $bool
157    $_treeview configure -showtitles $bool
158    $_treeview show
159  }
160
161  onconfigure -nomenu { bool } {
162    if {$bool} {
163      # no mostrar menu
164      bind $_treeview  <Button-3>   ""     
165    } else {
166      # mostrar menu     
167      bind $_treeview <Button-3>   "tk_popup $_menu %X %Y"
168    }
169  }
170
171  onconfigure -readonly { bool } {
172    if {!($created)} {
173      set options(-readonly) $bool       
174    } else {
175      puts "Btreeviewplus widget error: option -readonly only can be set on\
176            creation time"
177    }
178  }
179 
180  #pedro - DND
181  onconfigure -dragable { bool } {
182    if { $bool } {
183      package require tkdnd
184      #pedro - Create Drag n Drop Binds & Link dnd events.
185      event add <<DragAttempt>> <Button1-Motion>
186      $self bind all <<DragAttempt>>  "dnd drag $_treeview"
187      dnd bindsource $_treeview text/plain "return 1"
188      dnd bindtarget $_treeview text/plain <Drop> "dnd_event $_treeview %x %y"
189    } else {
190      event delete <<DragAttempt>>
191    }
192  }
193 
194  #pedro- end 
195 
196  onconfigure -filtercols { lst } {
197    set cols [$self cget -cols]   
198    set hiddencols [$self cget -hiddencols]
199    if { [llength cols] && [llength hiddencols]} {
200      set filtercols {}
201      foreach col $cols {
202        if {([lsearch -exact $hiddencols  $col])} {
203          lappend filtercols $col
204        }
205      }
206      set options(-filtercols) $filtercols   
207    } else {
208      if { [llength cols] } {
209        set options(-filtercols) $options(-cols)
210      }
211    }
212  }
213 
214  #///////////////////////////////////////////////////////////////////////////
215  method _CreateMenu {args} {
216  #
217  # PURPOSE: Adds menu to treeview.
218  #
219  #///////////////////////////////////////////////////////////////////////////
220    # read option
221    $_menu add command -label [mc "Select all"] \
222      -command "$self _SelectAll"  -accelerator CTRL+E
223    $_menu add command -label [mc "Unselect all"] \
224      -command "$self selection clearall"
225    $_menu add command -label [mc "Toggle selection"] \
226      -command "$self _ToggleSelection"
227    # read/write option
228    if {!([$self cget -readonly])} {
229      # delete
230      $_menu add separator
231      #$_menu add command -label [mc "Insert"] \
232                -command "$self _OpenWR" -accelerator Ins
233      $_menu add command -label [mc "Delete all"]  \
234        -command "$self clear"
235      $_menu add command -label [mc "Delete selected"] \
236        -command "lbDeleteSelection $self"
237    }
238    # read option
239    # copy
240    $_menu add separator
241    $_menu add command -label [mc "Filter"] -command "$self _OpenFD"
242    $_menu add command -label [mc "Unfilter"] -command "$self show all"
243    $_menu add separator
244    set mc [menu $_menu.copy -tearoff 0]
245    $_menu add cascade -label [mc "Copy"] -menu $mc
246    $mc add command -label [mc "Copy all"] \
247      -command "$self _CopyToClipBoard 1 1"
248    $mc add command -label [mc "Copy selected"] \
249      -command "$self _CopyToClipBoard 1 0" -accelerator CTRL+C
250    $mc add command -label [mc "Copy unselect"] \
251      -command "$self _CopyToClipBoard 0 1"
252    # count
253    $_menu add separator
254    $_menu add command -label [mc "Count elements"] \
255      -command "$self _ShowCountItems"
256   
257    # falta el menu archivo
258    # file
259    #$_menu add separator
260    #set mf [menu $_menu.file -tearoff 0]
261    #$_menu add cascade -label [mc "File"] -menu $mf
262    #$mf add command -label "[mc "Save to file"] ..." \
263      -command "$self _SaveToFile 1 1"
264    #if {![$self cget -readonly]} {
265    #  $mf add command -label "[mc "Load form file"] ..." \
266        -command "$self _LoadFromFile"
267    #}
268    # bindings   
269    $self bind all <Control-KeyRelease> +[list $self _OnControlKey $self %K %k]
270    $self bind all <Key-Delete>    "lbDeleteSelection $self"
271    $self bind all <Key-Insert>    "$self _OpenWR"   
272    $self bind all <Shift-Up>      "$self addPrevious"
273    $self bind all <Shift-Down>    "$self addNext"
274    $self bind all <Up>            "$self previous"
275    $self bind all <Down>          "$self next"
276    $self bind all <Home>          "$self first"
277    $self bind all <End>           "$self last"
278    $self bind all <Shift-Home>    "$self addAllPrevious"
279    $self bind all <Shift-End>     "$self addAllNext"
280    $self bind all <Button-1>      +[list focus -force %W]
281  }
282  #///////////////////////////////////////////////////////////////////////////
283  method getMenu { } {
284  #
285  # PURPOSE: Devuelve el menu del btreeviewplus para poder modificarlo y
286  #          ampliarlo
287  #
288  # RETURN: La variable de instancia que apunta al menu
289  #
290  #/////////////////////////////////////////////////////////////////////////// 
291    return $_menu
292 }
293
294
295  #///////////////////////////////////////////////////////////////////////////
296  method _OnKeyPress {key} {
297  #
298  # PURPOSE: Activa la fila que coincide con las teclas pulsadas. Distinge
299  #          entre mayúculas y minúsculas
300  #
301  # PARAMETERS: key -> tecla pulsada
302  #
303  #///////////////////////////////////////////////////////////////////////////
304    if {[$self cget -keypress]} {     
305      set diference 500
306      set result [lbOnKeyPress $self $key $listKey $afterTime $diference \
307        [$self cget -colkeypress]]
308      set listKey   [lindex $result 0]
309      set afterTime [lindex $result 1]
310    }
311  }
312
313
314  #///////////////////////////////////////////////////////////////////////////
315  method _OnControlKey {_lb keysym keycode} {
316  #
317  # PURPOSE: Controla es uso de teclas rápidas para le ejecución de funciones
318  #
319  # PARAMETERS: _lb -> self
320  #             keysym -> The keysym corresponding to the event,
321  #                       substituted as a textual string
322  #             keycode -> The keycode field from the event
323  #
324  #///////////////////////////////////////////////////////////////////////////
325    switch [string toupper $keysym] {
326      E { $_lb _SelectAll }
327      C { lbToClipBoard $_lb 1 0 }
328    }
329  } 
330
331  #///////////////////////////////////////////////////////////////////////////
332  method _ShowCountItems {} {
333  #
334  # PURPOSE: Shows information on the selection of the elements
335  #
336  #///////////////////////////////////////////////////////////////////////////
337    set info [lbCountItems $self]
338    set msg "[mc "Total"]: [lindex $info 0] \n\
339             [mc "Selected"]: [lindex $info 1] \n\
340             [mc "Not Selected"]: [lindex $info 2]"
341    tk_messageBox -default ok \
342                  -icon info  \
343                  -message $msg \
344                  -type ok \
345                  -parent $self \
346                  -title [mc "numero de elementos"]
347  }
348
349
350  #/////////////////////////////////////////////////////////////////////////////
351  method _ToggleSelection {} {
352  #
353  # PURPOSE: Toggle selection elements
354  #
355  #/////////////////////////////////////////////////////////////////////////////
356    foreach i [$self get] {
357      $self selection toggle $i
358    }
359  }
360
361
362  #///////////////////////////////////////////////////////////////////////////
363  method _SelectAll { } {
364  #
365  # PURPOSE: Selection all
366  #
367  #///////////////////////////////////////////////////////////////////////////
368    foreach i [$self get] {
369      $self selection set $i
370    }
371  }
372
373
374  #/////////////////////////////////////////////////////////////////////////////
375  method _CopyToClipBoard { sl unSe {pref ""} {suf ""} {sep "\n"}} {
376  #
377  # PURPOSE: copy the elements indicates in clipboard
378  #
379  # PARAMETERS:
380  #   sl   -> Copy items selections
381  #   unSe -> Copy items not selections
382  #   pref -> Text to concatenate in the beginning. Default ""
383  #   suf  -> Text to concatenate in the end. Default ""
384  #   sep  -> Separating text of elements. Default "\n"
385  #
386  #/////////////////////////////////////////////////////////////////////////////
387    # items to copy
388    set lst {}
389    if { $sl } {
390      foreach i [$self curselection] {
391        lappend lst [$self get $i]
392      }
393    }
394    if { $unSe } {
395      foreach i [$self selection get unselected] {
396        lappend lst [$self get $i]
397      }
398    }
399    # copy
400    set str [ListToStr $lst $sep $pref $suf]
401    clipboard clear
402    clipboard append $str
403  }
404
405
406  #/////////////////////////////////////////////////////////////////////////////
407  method _SaveToFile {se unSe {pref ""} {suf ""} {sep "\n"}} {
408  #
409  # PURPOSE: Save the content from treeview in a file
410  #
411  # PARAMETERS:
412  #    sl   -> Copy items selections
413  #   unSe -> Copy items not selections
414  #   pref -> Text to concatenate in the beginning. Default ""
415  #   suf  -> Text to concatenate in the end. Default ""
416  #   sep  -> Separating text of elements. Default "\n"
417  #
418  #/////////////////////////////////////////////////////////////////////////////
419    # select file
420
421    set filNam [tk_getSaveFile -parent $self -title [mc "File selector"] \
422                               -initialdir $options(-initialdir)]
423    if {$filNam != ""} {
424      # open file to write
425      if { ![ catch { set fd [open $filNam w] } msgerr] } {
426        # text to save
427        set lst {}
428        if { $se } {
429          foreach i [$self selection get selected] {
430            lappend lst [$self get $i]
431          }
432        }
433        if { $unSe } {
434          foreach i [$self selection get unselected] {
435            lappend lst [$self get $i]
436          }
437        }
438        set str [ListToStr $lst $sep $pref $suf]
439        # write
440        puts -nonewline $fd $str
441        close $fd
442        return 1
443      }
444      error $msgerr
445    }
446  }
447
448
449
450  #/////////////////////////////////////////////////////////////////////////////
451  method  _LoadFromFile { } {
452  #
453  # PURPOSE: Load the content from treeview in a file
454  #
455  #/////////////////////////////////////////////////////////////////////////////
456    # select file
457    set filNam [tk_getOpenFile -parent $self -title [mc "File selector"] \
458                               -initialdir $options(-initialdir)]
459    if {$filNam != ""} {
460      # open file to read
461      if { ![ catch { set fd [open $filNam r] } msgerr] } {
462         while { [gets $fd line ] >= 0} {
463           $self add $line
464         }
465         close $fd     
466         return 1
467      }
468      error $msgerr
469    }
470  }
471
472 
473  #///////////////////////////////////////////////////////////////////////////
474  method _SortByColumn { col } {
475  #
476  # PURPOSE: Sorts the ListBox by the values of the given column
477  #
478  # PARAMETERS:
479  #  col -> the column which the sort is performed
480  #
481  #///////////////////////////////////////////////////////////////////////////
482    set lst [$self get]
483    set len [$self size]
484    for { set i [expr $len - 1] } { $i > 0 } { incr i -1 } {
485      for { set j 0 } { $j < $i } { incr j } {
486        set ida [lindex [$self get] $j]
487        set idb [lindex [$self get] [expr $j + 1]]
488        set a [$self get $ida $col]
489        set b [$self get $idb $col]
490        if { $a > $b } { $self move $ida after $idb }
491      }
492    }
493  }
494
495
496  #///////////////////////////////////////////////////////////////////////////
497  proc _AddWR { elem father } {
498  #
499  # PURPOSE: adds the item introduced in the dialog to the selected list
500  #
501  # PARAMETERS:
502  #  elem -> the element to insert from the add dialog
503  #  father -> The dialog's window pathname
504  #
505  #///////////////////////////////////////////////////////////////////////////
506    eval $father insert 0 $elem
507  }
508
509
510  #//////////////////////////////////////////////////////////////////////////
511  method _OpenWR {} {
512  #
513  # PURPOSE: Calls (and creates) an add dialog for insert by hand elements
514  #
515  #///////////////////////////////////////////////////////////////////////////
516       
517    destroy $self.dw
518    set dialog  [bfieldsdialog $self.dw -title [mc "Insert element"] \
519                -parent $self -orientation $options(-orientation) \
520                -fields $options(-cols) -procedure [codename _AddWR] \
521                -buttons { add exit }]
522       
523    $dialog draw
524  }
525 
526 
527  #///////////////////////////////////////////////////////////////////////////
528  proc _Filter { elem father } {
529  #
530  # PURPOSE: Filters the treeview with the filter suministred
531  #
532  # PARAMETERS:
533  #  elem -> the list with the filter fields
534  #  father -> The dialog's window pathname
535  #
536  #///////////////////////////////////////////////////////////////////////////
537    eval $father filter $elem
538  }
539
540
541  #//////////////////////////////////////////////////////////////////////////
542  method _OpenFD {} {
543  #
544  # PURPOSE: Calls (and creates) a add dialog for getting a filter
545  #
546  #///////////////////////////////////////////////////////////////////////////
547       
548    destroy $self.fd
549    set dialog  [bfieldsdialog $self.fd -title [mc "Filter elements"] \
550                -parent $self -orientation $options(-orientation) \
551                -fields $options(-filtercols) -procedure [codename _Filter] \
552                -buttons { info apply accept cancel }]
553    $dialog configure -info \
554"Los filtros admiten expresiones regulares:
555
556  expresiones regulares básicas:
557    - literales: caracteres simples
558    - brackets:  conincide con cualquier caracter especificado dentro
559       tambien pueden expecificarse rangos pe \[a-d\] equivale a \[abcd\]
560       o indicar la no coincidencia colocando como primer caracter ^
561       rangos predefinidos:
562        \[:alnum:\] equivale a \[0-9a-zA-Z\]
563        \[:alpha:\] equivale a \[a-zA-Z\]
564        \[:digit:\] equivale a \[0-9\]
565        \\w equivale a \[:alnum:\]
566        \\W equivale a \[^:alnum:\]
567        para incluir el literal - ponerlo al final del braquet
568        para incluir el literal ^ ponerlo en cualquier lugar menos el primero
569    - punto . : coincide con cualquier caracter simple
570    - ^ y $ : coinciden respectivamente con el principio o final de linea
571    - caracteres especiales: los caracteres que tienen significado en las
572      expresiones regulares pueden escribirse precediendolos con \\
573   
574  operadores sobre las expresiones:
575    - <e1><e2>: concatenacion, la expresion resultante coincide si coinciden
576         secuencialmente las expresiones
577    - <e1>|<e2> : disyuncion, coincide si coincide alguna de las expresiones
578    - <e>? : opcionalidad, coincide si la expresion anterior coincide 0 o 1 vez
579    - <e>* : repeticion, coincide si la expresion anterior coincide 0 o mas veces
580    - <e>+ : repeticion, coincide si la expresion anterior coincide 1 o mas veces
581    - <e>{n} : repeticion, coincide si la expresion anterior coincide  n veces
582    - <e>{n,} : repeticion, coincide si la exp anterior coincide n o mas veces
583    - <e>{n,m} : repeticion, coincide si la exp anterior coincide por lo menos n
584         y no mas de m veces
585
586  precedencia de los operadores:
587    - los operadores de repeticion tienen preferencia sobre la concatenacion
588    - la concatenacion tiene preferencia sobre la disyuncion
589    - las reglas pueden alterarse con el uso de parentesis
590"
591       
592    $dialog draw
593  }
594
595
596  #///////////////////////////////////////////////////////////////////////////
597  method selection { args } {
598  #
599  # PURPOSE: extends the original command to extend capabilities
600  #
601  # PARAMETERS:
602  #   args: arguments
603  #
604  #///////////////////////////////////////////////////////////////////////////
605    if { [lindex $args 0] eq "get" } {
606     if { [lindex $args 1] eq "unselected" } {
607       set result {}
608       set selected [$self curselection]
609       foreach i [$self get] {
610         if { "-1" eq [lsearch $selected $i] } {
611           lappend result $i
612         }
613       }
614       return $result
615     } else {
616      return [eval $_treeview curselection]
617     }
618    }
619
620    eval $_treeview selection $args
621  }
622
623   #///////////////////////////////////////////////////////////////////////////
624  method insert { args } {
625  #
626  # PURPOSE: inserts an element into the treeview
627  #
628  # PARAMETERS:
629  #   args: [-at node] position value list_data_values
630  #         the list_data_values must be provided in order
631  #   dragable: make the elements dragable between them.
632  #
633  #///////////////////////////////////////////////////////////////////////////   
634    set index 0
635    set father ""
636   
637    if { [lindex $args $index] eq "-at" } {
638      incr index
639      set father [lindex $args $index]
640      incr index
641    }
642
643    set pos [lindex $args $index]
644    incr index
645
646    set value [lindex $args $index]
647    incr index
648
649    set dats [lrange $args $index end]
650    if { [llength $dats] == 1 } { set dats [lindex $dats 0] }
651    set datos {}
652    set i 0
653
654    foreach col $options(-cols) {
655      lappend datos $col [lindex $dats $i]
656      incr i
657    }
658
659    if { $father == "" } {
660      if { $datos == {} } {
661       set node [$_treeview insert $pos $value]
662      } else {
663       set node [$_treeview insert $pos $value -data $datos]
664      }
665    } else {
666      if { $datos == {} } {
667       set node [$_treeview insert -at $father $pos $value]
668      } else {
669       set node [$_treeview insert -at $father $pos $value -data $datos]
670      }
671    }
672
673  }
674
675  #///////////////////////////////////////////////////////////////////////////
676  method delete { args } {
677  #
678  # PURPOSE: deletes elements from the treeview
679  #
680  # PARAMETERS:
681  #   args: the tags or ids of the items to be deleted
682  #
683  #///////////////////////////////////////////////////////////////////////////
684    # OJO un delete sobre un arbol vacio puede provocar un crash, es
685    # un bug en BLT!!!
686    eval $_treeview delete $args
687    #if { "-1" eq [lsearch $args 0] } {
688    #  eval $_treeview delete $args
689    #} else {
690    #  puts "Root node can't be deleted"
691    #}
692  }
693 
694
695  #///////////////////////////////////////////////////////////////////////////
696  method get { {id ""} {cols ""}} {
697  #
698  # PURPOSE: retrieves data from an entry identified by id
699  #
700  # PARAMETERS:
701  #  id: id of the node
702  #  cols: name of the cols from which retrieve data
703  #
704  #///////////////////////////////////////////////////////////////////////////
705    if { $id eq "" } { return [lrange [$self find] 1 end] }
706 
707    set result {}
708    set data [$_treeview entry cget $id -data]
709   
710    if { "$cols" eq "" } {
711      set cols [$self column names]
712    }
713   
714    foreach col $cols {
715      set inx [lsearch $data $col]
716      if { "-1" ne $inx } {
717        incr inx
718        lappend result [lindex $data $inx]
719      }
720    }
721    return $result
722  }
723
724
725  #///////////////////////////////////////////////////////////////////////////
726  method getName { args } {
727  #
728  # PURPOSE: retrieves name from an entry identified by id or its parent name
729  #
730  # PARAMETERS:
731  #  id: id of the node
732  #
733  #///////////////////////////////////////////////////////////////////////////
734    set id [lindex $args 0]
735    if { [llength $args] == 2 } { set id [lindex $args 1] }
736   
737    set result [$_treeview get -full $id]
738    set index  [expr [llength $result] - 2]
739
740    if { [lindex $args 0] eq "-parent" } {
741      return [lindex $result $index]
742    }
743
744    if { [lindex $args 0] eq "-full" } {
745      return $result
746    }
747
748    return [lindex [$_treeview get -full $id] end]
749  }
750
751 #///////////////////////////////////////////////////////////////////////////
752  method getId { args } {
753  #
754  # PURPOSE: retrieves id from an entry by a name pattern
755  #
756  # PARAMETERS:
757  #  name: name of the node
758  #
759  # RETURN: Id of the node
760  #
761  #///////////////////////////////////////////////////////////////////////////
762    set name [lindex $args 0]
763    if { [llength $args] == 2 } {
764      set name [lindex $args 1]
765      }   
766    set result [$_treeview find -name $name]
767    return $result
768  }
769
770
771  #///////////////////////////////////////////////////////////////////////////
772  method set { id data {cols ""}} {
773  #
774  # PURPOSE: changes data for an entry identified by id
775  #
776  # PARAMETERS:
777  #  id: id of the node
778  #  data: data to insert
779  #  cols: name of the cols for which we are providing data
780  #
781  #///////////////////////////////////////////////////////////////////////////
782    if { "$cols" eq "" } {
783      set cols [$self column names]
784    }
785    set datos {}
786    set i 0
787    foreach col $cols {
788      lappend datos $col
789      lappend datos [lindex $data $i]
790      incr i
791    }
792    return [$_treeview entry configure $id -data $datos]
793  }
794
795
796  #///////////////////////////////////////////////////////////////////////////
797  method first {} {
798  #
799  # PURPOSE: Selects and returns the first row of btreeviewplus
800  #
801  # RETURN: The index of first row
802  #
803  #///////////////////////////////////////////////////////////////////////////
804    set all [$self get]
805    set selected [$self selection get]
806    if {$selected != ""} {
807      foreach item $selected {
808        $self selection clear $item
809      }
810    }
811    $self selection set [lindex $all 0]
812    return [lindex $all 0]
813  }
814   
815   
816  #///////////////////////////////////////////////////////////////////////////
817  method last {} {
818  #
819  # PURPOSE: Selects and returns the last row of btreeviewplus
820  #
821  # RETURN: The index of last row
822  #
823  #///////////////////////////////////////////////////////////////////////////
824    set all [$self get]
825    set selected [$self selection get]
826    if {$selected != ""} {
827      foreach item $selected {
828        $self selection clear $item
829      }             
830    }
831    $self selection set [lindex $all [expr [llength $all] - 1]]
832    return [lindex $all [expr [llength $all] - 1]]           
833  }
834
835
836  #///////////////////////////////////////////////////////////////////////////
837  method addPrevious {} {
838  #
839  # PURPOSE: adds the row previous to the present selection
840  #
841  # RETURN: The index of the row previous
842  #
843  #///////////////////////////////////////////////////////////////////////////
844    set all [$self get]
845    set selected [$self selection get]
846    if {$selected == ""} {
847      return -1
848    } else  {
849      set firstSelected [lindex $selected 0]
850      set first [lindex $all 0]
851      if { $first == $firstSelected } {
852        return [lindex $all 0]
853      } else  {
854        set allPosition [lsearch -exact $all $firstSelected]
855        set firstSelected [lindex $all [expr $allPosition - 1]]
856        #set firstSelected [expr $firstSelected - 1]
857        $self selection set $firstSelected
858        return $firstSelected
859      }
860    }
861  }
862 
863
864  #///////////////////////////////////////////////////////////////////////////
865  method addNext {} {
866  #
867  # PURPOSE: Adds the following row to the present selection
868  #
869  # RETURN: The index of the following row
870  #
871  #///////////////////////////////////////////////////////////////////////////
872    set all [$self get]
873    set selected [$self selection get]
874    if {$selected == ""} {
875      return -1     
876    } else  {
877      set lastSelected [lindex $selected [expr [llength $selected] - 1] ]
878      set last [lindex $all [expr [llength $all] - 1]]
879      if { $last == $lastSelected } {
880        return [lindex $all [expr [llength $all] - 1]]
881      } else  {
882        set allPosition [lsearch -exact $all $lastSelected]
883        set lastSelected [lindex $all [expr $allPosition + 1]]
884        $self selection set $lastSelected
885        return $lastSelected
886      }
887    }   
888  }
889
890
891  #///////////////////////////////////////////////////////////////////////////
892  method previous {} {
893  #
894  # PURPOSE: selects the row previous to the present selection
895  #
896  # RETURN: The index of the row previous
897  #
898  #///////////////////////////////////////////////////////////////////////////
899    set all [$self get]
900    set selected [$self selection get]
901    if {$selected == ""} {
902      return -1
903    } else  {
904      foreach item $selected {
905        $self selection clear $item
906      }
907      set firstSelected [lindex $selected 0]
908      set first [lindex $all 0]
909      if { $first == $firstSelected } {
910        $self selection set $firstSelected
911        return [lindex $all 0]
912      } else  {
913        set allPosition [lsearch -exact $all $firstSelected]
914        set firstSelected [lindex $all [expr $allPosition - 1]]
915        $self selection set $firstSelected
916        return $firstSelected
917      }
918    }
919  }
920   
921
922  #///////////////////////////////////////////////////////////////////////////
923  method next {} {
924  #
925  # PURPOSE: selects the following row to the present selection
926  #
927  # RETURN: The index of the following row
928  #
929  #///////////////////////////////////////////////////////////////////////////
930    set all [$self get]
931    set selected [$self selection get]
932    if {$selected == ""} {
933      return -1
934    } else  {
935      foreach item $selected {
936        $self selection clear $item
937      }
938      set lastSelected [lindex $selected [expr [llength $selected] - 1] ]
939      set last [lindex $all [expr [llength $all] - 1]]
940      if { $last == $lastSelected } {
941        $self selection set $lastSelected
942        return [lindex $all [expr [llength $all] - 1]]
943      } else  {
944        set allPosition [lsearch -exact $all $lastSelected]
945        set lastSelected [lindex $all [expr $allPosition + 1]]
946        $self selection set $lastSelected
947        return $lastSelected
948      }
949    }
950  }
951   
952
953  #///////////////////////////////////////////////////////////////////////////
954  method addAllPrevious {} {
955  #
956  # PURPOSE: Selects all the previous rows
957  #
958  # RETURN: The index of the first row
959  #
960  #///////////////////////////////////////////////////////////////////////////
961    set all [$self get]
962    set selected [$self selection get]
963    if {$selected == ""} {
964      return -1
965    } else  {
966      set firstSelected [lindex $selected 0]
967      set first [lindex $all 0]
968      set allPosition [lsearch -exact $all $firstSelected]
969      while { $allPosition != 0 } {
970        $self addPrevious
971        #$self selection set $firstSelected
972        set selected [$self selection get]
973        set allPosition [lsearch -exact $all $firstSelected]
974        if { $allPosition != 0 } {
975          set firstSelected [lindex $all [expr $allPosition - 1]]
976        }
977      } 
978      return [lindex $firstSelected]
979    }
980  }
981   
982
983  #///////////////////////////////////////////////////////////////////////////
984  method addAllNext {} {
985  #
986  # PURPOSE: Selects all the following rows
987  #
988  # RETURN: The index of the last row
989  #
990  #///////////////////////////////////////////////////////////////////////////
991    set all [$self get]
992    set selected [$self selection get]
993    if {$selected == ""} {
994      return -1
995    } else  {
996      set lastSelected [lindex $selected [expr [llength $selected] - 1] ]
997      set last [lindex $all [expr [llength $all] - 1]] 
998      set allPosition [lsearch -exact $all $lastSelected]
999      while {$allPosition != [expr [llength $all] -1]} {
1000        $self addNext
1001        set selected [$self selection get]
1002        set lastSelected [lindex $selected [expr [llength $selected] - 1] ]
1003        set allPosition [lsearch -exact $all $lastSelected]
1004      }
1005      return $lastSelected
1006    }
1007  }
1008   
1009
1010  #///////////////////////////////////////////////////////////////////////////
1011  method clear {} {
1012  #
1013  # PURPOSE: deletes all nodes
1014  #
1015  #///////////////////////////////////////////////////////////////////////////
1016    #foreach i [$self get] {
1017    #  if { 0 eq $i } { continue }
1018    #  $self delete $i
1019    #}
1020    $self delete 0
1021  }
1022
1023
1024  #///////////////////////////////////////////////////////////////////////////
1025  method size {} {
1026  #
1027  # PURPOSE: calculates the treeview size
1028  #
1029  #///////////////////////////////////////////////////////////////////////////
1030    return [llength [$self get]]
1031  }
1032
1033
1034  #///////////////////////////////////////////////////////////////////////////
1035  method column { args } {
1036  #
1037  # PURPOSE: modifies a particular case of column -> column names
1038  #
1039  #///////////////////////////////////////////////////////////////////////////
1040    if { [lindex $args 0] eq "names" } {
1041      return [lrange [$_treeview column names] 1 end]
1042    }
1043    return [eval $_treeview column $args]
1044  }
1045 
1046
1047  #///////////////////////////////////////////////////////////////////////////
1048  method filter { filters } {
1049  #
1050  # PURPOSE: filters the treeview elements matching filters for each col in cols
1051  #
1052  # PARAMETERS:
1053  #  filters: list of filters for the columns above
1054  #
1055  #///////////////////////////////////////////////////////////////////////////
1056    foreach inx [$self get] {
1057      set datos [$self get $inx $options(-filtercols)]
1058      set match 1
1059      for { set i 0 } { $i < [llength $filters] } { incr i } {
1060        set match [expr $match & [regexp [lindex $filters $i] [lindex $datos $i]]]
1061      }
1062      if { ! $match } {
1063        $_treeview hide $inx
1064      } else {
1065        $_treeview show $inx
1066      }
1067    }
1068  }
1069
1070  #///////////////////////////////////////////////////////////////////////////
1071  method update { } {
1072  #
1073  # PURPOSE: method to solve bug when a expanded node of tree
1074  #          is collapsed and back to expand it.
1075  #          This bug happens when the option -opencommand is used in an
1076  #          entry of BLT treeview.
1077  #
1078  #///////////////////////////////////////////////////////////////////////////
1079    $_treeview configure -width [expr [$_treeview cget -width] - 1]
1080    $_treeview configure -width [expr [$_treeview cget -width] + 1]
1081    update
1082  }
1083
1084}
1085
1086#pedro g - DND event handler
1087#///////////////////////////////////////////////////////////////////////////////
1088proc dnd_event { w x y} {
1089# PURPOSE: Handles the Drop Event.
1090# ARGS:    w = Widget window path,
1091#          x, y = Mouse Coords over Drop-Target, this are used to get the parent
1092#
1093# Ojo:     El handler no puede realizar desplazamientos hacia el nodo
1094#          raiz del arbol por una limitacion del BLT 2.4.
1095#          Los nodos que se quieran mover al root deben ser recreados directamente
1096#          al root a partir de la cola de hijos del nodo a mover.
1097# Warning: Handler won't move nodes towards the Node 0 of the tree because
1098#          of a BLT restriction. If a node was to be re-parented to the
1099#          Tree Root node, it'd have to be recreated by gathering a recursive
1100#          Child list from the node and then doing an insert with its elements
1101#          directly into the Tree Root.
1102# TODOs:   Pendiente hacer override a evento B1 para que mantenga la selección
1103#          antes de iniciar DND.
1104#          El bindtarget se aplica a toda el area editable del widget, por tanto
1105#          aceptará información drop de cualquier fuente, hay que validar
1106#          que el numero obtenido exista dentro de los elementos del tree.
1107#          De lo contrario da error.
1108#///////////////////////////////////////////////////////////////////////////////
1109
1110# Obtenemos Origen y Destino desde los elementos seleccionados y coordenadas del
1111# Drop.
1112  set newHijo   [$w curselection]
1113  set newParent [$w nearest $x $y]
1114  #Prohibimos Drop Hacia si mismo.
1115  if { $newHijo != $newParent } {
1116   # Añadimos soporte para drag&Drop cuando existe mas de un elemento seleccionado.
1117   foreach element $newHijo {
1118     # Obtenemos nombre de nuevo Padre e Hijo.
1119     set name  [$w get -full $element]
1120     set nameP [$w get -full $newParent]
1121     # Pop-up, pregunta de "seguridad"...(..es un coñazo..remover cuanto antes)
1122     set answer [tk_messageBox -message "Mover el Elemento '$name' A '$nameP'" \
1123                 -type yesno -icon question -title "Bys TreeView - Pregunta"]
1124     if { $answer == "yes"} {
1125       # Evitamos liarla con la limitacion del BLT, pues devuelve "exit 1"
1126       if { $newParent != "0" } {
1127         if { [catch "$w move $element into $newParent" fid] } {
1128           # Mostramos mensaje de error en caso de que ocurra alguno.
1129           tk_messageBox -message "Error: !! $fid !!" -icon "error" -title "Bys TreeView - Error"
1130           return ""
1131          }
1132         return ""
1133        } else {
1134         #Mensaje en caso de usuario Animal.
1135         tk_messageBox -message "Opcion no permitida !! No puede desplazar a la raiz del Arbol"\
1136                    -title "Bys TreeView - Error" -icon "error"
1137         return ""
1138        }
1139      } else {
1140        return ""
1141      }
1142    }
1143  }
1144}
1145#pedro - end
1146
1147package provide btreeviewplus 1.0
1148
1149# ------- TEST CODE ----
1150
1151#/////////////////////////////////////////////////////////////////////////////
1152proc test_btreeviewplus {} {
1153#
1154# PURPOSE: Funcion de test de un btreeviewplus
1155#
1156#/////////////////////////////////////////////////////////////////////////////
1157  global tcl_platform
1158
1159  if { $tcl_platform(platform) != "unix" } {
1160    SendInit
1161    SendVerify
1162  }
1163 
1164  # defining the widgets
1165  variable data
1166  set data(-selected) 1
1167 
1168  destroy .top
1169  toplevel .top -width 200 -height 100
1170   
1171  TitleFrame .top.f1 -text "BTreeViewPlus test"
1172  set f1 [ .top.f1 getframe ]
1173
1174  #Añadida la opcion Dragable (boolean 1 o 0), activa o desactiva el DND.
1175  btreeviewplus $f1.blb -cols { col1 col2 col3 col4 } \
1176                    -height 150 -width 500 -orientation vertical \
1177                    -hiddencols {col4} -dragable 1
1178  puts "WIDGET btreeviewplus: $f1.blb"
1179  $f1.blb insert end numeros {1 2 3 4}
1180  $f1.blb insert end alpha   {one two three four}
1181  $f1.blb insert -at 2 end alfa    {uno dos tres cuatro}
1182  $f1.blb insert end kaka    {k kk kkk kkkk}
1183  $f1.blb insert -at 1 end zero    {0 0 0 0}
1184  $f1.blb insert end simbols {@ # $ %}
1185
1186  # packing all   
1187  grid .top.f1 -row 0 -column 0 -sticky "new" -padx 10 -pady 10
1188  #grid .top.f2 -row 1 -column 0 -sticky "new" -padx 10 -pady 10
1189  grid columnconfigure .top 0 -weight 1
1190  grid rowconfigure .top 0 -weight 0
1191  grid rowconfigure .top 1 -weight 1
1192
1193  grid $f1.blb -row 0 -column 0 -sticky "new"
1194  grid columnconfigure $f1 0 -weight 1
1195  grid rowconfigure $f1 0 -weight 1
1196
1197}
Note: See TracBrowser for help on using the repository browser.