1#!/usr/bin/env ruby
2##
3## valid.rb
4##
5## This demos shows the use of the validation mechanism of the table
6## and uses the table's cache (no -command or -variable)
7##
8## ( based on 'valid.tcl' included source archive of tktable extension )
9##
10require 'tk'
11require 'tkextlib/tktable'
12
13rows = 10
14cols = 10
15
16def colorize(num)
17  num = Integer(num)
18  return 'colored' if (num > 0 && num % 2 == 1)
19end
20
21def fill_headers(w, r=10, c=10)
22  (1..(r-1)).each{|i| w.set([i,0], i.to_s)}
23
24  (1..(c-1)).each{|j|
25    if j % 3 == 1
26      w.set([0,j], 'AlphaNum')
27    elsif j % 2 == 1
28      w.set([0,j], 'Alpha')
29    elsif j != 0
30      w.set([0,j], 'Real')
31    end
32  }
33end
34
35def validate_proc(c, val)
36  if c % 3 == 1
37    # AlphaNum
38    regexp = /^[A-Za-z0-9 ]*$/
39  elsif c % 2 == 1
40    # Alpha
41    regexp = /^[A-Za-z ]*$/
42  elsif c != 0
43    # 'Real'
44    regexp = /^[-+]?[0-9]*\.?[0-9]*([0-9]\.?e[-+]?[0-9]*)?$/
45  end
46  if val =~ regexp
47    return true
48  else
49    Tk.bell
50    return false
51  end
52end
53
54lbl = TkLabel.new(:text=>"TkTable v1 Validated Table Example")
55
56table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :cache=>1,
57                        :width=>5, :height=>5, :titlerows=>1, :titlecols=>1,
58                        :coltagcommand=>proc{|n| colorize(n)},
59                        :flashmode=>true, :selectmode=>:extended,
60                        :colstretch=>:unset, :rowstretch=>:unset,
61                        :validate=>true,
62                        :validatecommand=>proc{|e|
63                          unless e.widget.tag_include?('title', e.index)
64                            validate_proc(e.column, e.new_value)
65                          end } )
66
67fill_headers(table)
68
69table.tag_configure('colored', :bg=>'lightblue')
70table.tag_configure('title',   :fg=>'red')
71table.set_width(0,3)
72
73sx = table.xscrollbar(TkScrollbar.new)
74sy = table.yscrollbar(TkScrollbar.new)
75
76btn = TkButton.new(:text=>'Exit', :command=>proc{exit})
77
78Tk.grid(lbl, '-', :sticky=>:ew)
79Tk.grid(table, sy, :sticky=>:news)
80Tk.grid(sx, :sticky=>:ew)
81Tk.grid(btn, '-', :sticky=>:ew)
82
83Tk.root.grid_columnconfig(0, :weight=>1)
84Tk.root.grid_rowconfig(1, :weight=>1)
85
86puts "Table is #{table.path}"
87
88Tk.mainloop
89