File: taputils.tcl

package info (click to toggle)
tkman 2.2-2etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 928 kB
  • ctags: 291
  • sloc: tcl: 8,264; sh: 400; makefile: 242
file content (655 lines) | stat: -rw-r--r-- 15,007 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#
# some functions which should be part of Tcl, but aren't
#
# Tom Phelps (phelps@ACM.org)
#


#
# UNIXish
#

# like find, but just for -name <pattern> for now
# could have signature of find <dir> <expr w/file(xxx) as returned by Tcl's file stat, with fast path for just name>
# why not just exec find?  sidestep exec, available on non-UNIX, standardizes options
# symbolic links always followed

# tests: <, =, >, <=, >=, !=  on "depth" and "file" variables, and "f()" array of "file stat <file>"
# fields of f: atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, uid
# refer to file(n)/file stat
# always have to do a stat so know what the directories are (sigh)

set findx(matches) {}
set findx(expr) {}
set findx(rexpr) {}
set findx(seen) 0
# starting directory, expression to match, expression for recurse
# e.g., find . *.txt
#       find /usr/sww/doc/RFC {[string match rfc*.txt $file]} {[llength $findx(matches)]==0 || $depth>3}
proc findfile {dir filepattern} {
	find $dir [subst -nocommands {[string match $filepattern \$file]}]
}
#proc fib {depth} { find / {[regexp {^s?bin$} $f(tail)]} "\$depth<=$depth" }
#proc fim {depth} { find / {[regexp {^s?man$} $f(tail)]} "\$depth<=$depth" }
# terrible bug if depth<=3 or 4 -- Tcl's fault?
proc find {dir expr {rexpr 1}} {
	global findx
	set olddir [pwd]

	set findx(matches) {}
	set findx(expr) $expr
	set findx(rexpr) $rexpr
	set findx(seen) 0
	# can handle time elapsed in "user space"
#	cd [file dirname $dir]
	find1 $dir 0 $olddir

#	cd $olddir
	return $findx(matches)
}

proc find1 {dir depth updir} {
	global findx

	# matches in current directory
#puts "$findx(rexpr) => [expr $findx(rexpr)]"
	if {$findx(rexpr) eq ""} return
#puts "[llength $findx(matches)], $depth"
#	if {$dir ne "/" && [catch {cd [file tail $dir]}]} return
#puts [expr {$dir ne "/" && [catch {cd $dir}]}]
	if {[catch {cd $dir}]} return
#	set curdir [pwd]
	set f(dir) $dir
	foreach file [glob -nocomplain *] {
		incr findx(seen)
		#if {[pwd] ne $curdir} {cd $curdir}
		if {[catch {file lstat $file f}]} continue
		set subupdir ..; if {$f(type) eq "link" && [file isdirectory $file]} {set f(type) "directory"; set subupdir [pwd]}
		set f(tail) $file
		set relpath [file join $dir $file]
#puts "$findx(expr) => [expr $findx(expr)] ($file in $dir)"
		# no brackets around $findx(expr)
#puts "$findx(expr), file=$file => [subst $findx(expr)]"
		if {[subst $findx(expr)]} {lappend findx(matches) $relpath}

		# matches in subdirectories
		if {[file isdirectory $relpath]} {
			foreach match [find1 $relpath [expr {$depth+1}] $subupdir] {lappend findx(matches) $match}
		}
	}
#	cd ..; # weird symbolic links sometimes so [pwd]!=$curdir kludge above
#if {$updir ne ".."} {puts "$dir up to $updir"}
	cd $updir
}


# pipeexp - expand file names in a pipe
proc pipeexp {p} {
	set p [string trim $p]

	set expp ""
	foreach i $p {
		if {[regexp {^[.~/$]} $i]} {lappend expp [fileexp $i]} \
		else {lappend expp $i}
	}
	return $expp
}

proc assert {bool msg {boom 0}} {
	if {!$bool} {
		puts stderr $msg
		if {$boom} {exit 1}
	}
}

# fileexp perform file spec expansion: ~ . .. $
proc fileexp {f} {
	global env

	set f [string trim $f]
	set l [string length $f]
	set expf ""

	set dir [pwd]
	foreach i [split $f "/"] {
#puts "$dir | $expf + $i"
		switch -glob $i {
			"" {set dir ""}
			{[A-Za-z]:} {set dir "$i"}
			~  {set dir $env(HOME)}
		 $* {set val $env([string trim [string range $i 1 end] ()])
				 if {[string match /* $val]} {set dir $val} else {append expf /$val)}}
			.  {set dir $dir}
	 .. {set dir [file dirname $dir]}
	 default {append expf /$i}
		}
	}

	return $dir$expf
}


# in:  f = (partial) file name
# out:   "" (NULL) if no matches
#        full name if exactly one match
#        list      w/first==longest match, if multiple matches

# on /usr/sww/, Tcl's file tail returns sww -- want ""
proc filetail {f} {
	set tail [file tail $f]
	if {[string match */ $f]} {set tail ""}
	return $tail
}
proc filedirname {f} {
	set dirname [file dirname $f]
	if {[string match ?*/ $f]} {set dirname [string range $f 0 [expr {[string length $f]-2}]]}
	return $dirname
}

proc filecomplete {f} {
	set expf [fileexp [filedirname $f]]/[filetail $f]
	set posn [string last [filetail $f] $f]; if {[string match */ $f]} {set posn [string length $f]}
	#if [string match */ $f] {set expf $f; set tail ""; set posn [string length $f]}
#puts "$posn, expf=$expf"
	set l [glob -nocomplain $expf*]
	set ll [llength $l]

	if {!$ll} {
		# maybe indicate that partial name not good
		set tail ""
	} elseif {$ll==1} {
		set tail [file tail $l]
		if {[file isdirectory $l]} {append tail /}
	} else {
		# determine the longest common prefix
		set lf [lfirst $l]; set lfl [string length $lf]
		set last $lfl
		set ni [expr {[string last / $lf]+1}]
		foreach i $l {
			for {set j $ni} {$j<=$last} {incr j} {
				if {[string index $lf $j] ne [string index $i $j]} break
			}
			set last [min $last [expr {$j-1}]]
		}
		set tail [filetail [string range [lfirst $l] 0 $last]]
	}

#puts "$ll, $tail"
	# compose original directory specification with (possibly) new tail
	if {$posn>0 && $ll} {
		# can't use dirname because it expands ~'s
		set tail [string range $f 0 [expr {$posn-1}]]$tail
	}

	if {$ll<2} {return $tail} else {return "$tail $l"}
}


proc tr {s c1 c2} {
#	regsub -all \\$c1 $s $c2 s2
	regsub -all "\[$c1\]" $s $c2 s2
	return $s2
}

# reverse glob
#    pass expanded filename, list of shortenings
#set file(globList) ~
proc bolg {f {l ""}} {
	if {$l eq ""} {global file; set l $file(globList)}

	foreach i $l {
		if {[regsub ([glob -nocomplain $i])(.*) $f "$i\\2" short]} {return $short}
	}
	return $f
}


proc setinsert {l i e} {
	return [linsert [lfilter $e $l] $i $e]
}
# short enough to just inline: if [lsearch $l $e]==-1 {lappend $l $e}
#proc setinsert {l e} {
#   if {[lsearch $l $e]==-1} {
#      return [lappend $l $e]
#   } else {
#      return $l
#   }
#}


proc unsplit {l c} {
	foreach i $l {
		append l2 $i $c
	}
#   return [string trimright $l2 $c]
	return [string range $l2 0 [expr {[string length $l2]-2}]]
}

proc bytes2prefix {x} {
	set pfx {bytes KB MB GB TB QB}
	set k 1024.0
	set sz $k

	if {$x<$k} {return "$x bytes"}

	set y BIG
	for {set i 0} {$i<[llength $pfx]} {incr i} {
		if {$x<$sz} {
			return [format " %0.1f [lindex $pfx $i]" [expr {$x/($sz/$k)}]]
		}
		set sz [expr {$sz*$k}]
	}
}



#
# Lispish
#

# unfortunately, no way to have more-convenient single quote form
proc quote {x} {return $x}

# should sort beforehand
proc uniqlist {l} {
	set e ""
	set l2 ""
	foreach i $l {
		if {$e ne $i} {
			lappend l2 $i
			set e $i
		}
	}
	return $l2
}


proc min {args} {
	if {[llength $args]==1} {set args [lindex $args 0]}
	set x [lindex $args 0]
	foreach i $args {
		if {$i<$x} {set x $i}
	}
	return $x
}

proc avg {args} {
	set sum 0.0

	if {[string $args ""]} return
	
	foreach i $args {set sum [expr {$sum+$i}]}
	return [expr {($sum+0.0)/[llength $args]}]
}

proc max {args} {
	if {[llength $args]==1} {set args [lindex $args 0]}
	set x [lindex $args 0]
	foreach i $args {
		if {$i>$x} {set x $i}
	}
	return $x
}


proc lfirst {l} {return [lindex $l 0]}
proc lsecond {l} {return [lindex $l 1]}
proc lthird {l} {return [lindex $l 2]}
proc lfourth {l} {return [lindex $l 3]}
# five is enough to get all pieces of `configure' records
proc lfifth {l} {return [lindex $l 4]}
proc lsixth {l} {return [lindex $l 5]}
proc lseventh {l} {return [lindex $l 6]}
proc lrest {l} {return [lrange $l 1 end]}

proc llast {l} {
	return [lindex $l end]
}

proc setappend {l e} {
	return "[lfilter $e $l] $e"
}

# filter out elements matching pattern p from list l
proc lfilter {p l} {
	set l2 ""

	foreach i $l {
		if {![string match $p $i]} "lappend l2 [list $i]"
	}
	return $l2
}

# keep elements matching pattern p in list l
proc lmatches {p l} {
	set l2 ""
	foreach i $l { if {[string match $p $i]} {lappend l2 [list $i]} }
	return $l2
}

proc lassoc {l k} {
	foreach i $l {
		if {[lindex $i 0]==$k} {return [lrange $i 1 end]}
	}
	return ""
}

# (ab)use foreach <var-list> <val-list> {}
#proc lset {l args} {
#	foreach val $l var $args {
#		upvar $var x
#		set x $val
#	}
#}

# like lassoc, but search on second element, returns first
proc lbssoc {l k} {

	foreach i $l {
		if {[lindex $i 1]==$k} {return [lindex $i 0]}
	}
	return ""
}

proc lreverse {l {block 1}} {
	set lrev {}
	for {set i [expr {[llength $l]-$block}]} {$i>=0} {incr i -$block} {
		lappend lrev [lrange $l $i [expr {$i+$block-1}]]
	}
	set flatten [eval concat $lrev]
	return $flatten
}


#
# X-ish
#

proc geom2posn {g} {
	if {[regexp {(=?\d+x\d+)([-+]+\d+[-+]+\d+)} $g both d p]} {
		return $p
	} else { return $g }
}

proc geom2size {g} {
	if {[regexp {(=?\d+x\d+)([-+]+\d+[-+]+\d+)} $g both d p]} {
		return $d
	} else { return $g }
}



#
# Tcl-ish
#


# translate ascii names into single character versions
# this should be a bind option

set name2charList {
	minus plus percent ampersand asciitilde at less greater equal
	numbersign dollar asciicircum asterisk quoteleft quoteright
	parenleft parenright bracketleft bracketright braceleft braceright
	semicolon colon question slash bar period underscore backslash
	exclam comma
}

proc name2char {c} {
	global name2charList

	if {[set x [lsearch $name2charList $c]]!=-1} {
		 return [string index "-+%&~@<>=#$^*`'()\[\]{};:?/|._\\!," $x]
	} else {return $c}
}

# 0=none="", 1=Shift=S, 2=Alt?, 4=Ctrl=C, 8=meta=M, 16=Alt?, 32=Alt or NumLock, 64=NumLock
proc key_state2mnemon {n} {
	set mod ""

#	set trans "SLCMAAN"
	set trans "S CMA  "; # ignore spaced modifiers

	for {set bp 0} {$bp<[string length $trans]} {incr bp} {
		set t [string index $trans $bp]
		if {$t ne " " && $n&(1<<$bp)} {append mod $t}
	}

	return $mod
}

proc lmatch {mode list {pattern ""}} {
	if {$pattern eq ""} {set pattern $list; set list $mode; set mode "-glob"}
	return [expr {[lsearch $mode $list $pattern]!=-1}]
}


# remove all char c from string s

proc stringremove {s {c " "}} {
	regsub -all -- \\$c $s "" s2
	return $s2
}


# backquote all regular expression meta-characters
proc stringregexpesc {s} { 
	return [stringesc $s {\||\*|\+|\?|\.|\^|\$|\\|\[|\]|\(|\)|\-}]
# try this:	return [stringesc $s {[][|*+?.^$\\()-]}]
#	return [stringesc $s {[\|\*\+\?\.\^\$\\\[\]\(\)\-]}]
}
# backquote Tcl meta-characters
#proc stringesc {s {c {\\|\$|\[|\{|\}|\]|\"}}} {
proc stringesc {s {c {[][\\\${}"]}}} {
	regsub -all -- $c $s {\\&} s2
	return $s2
}


proc tk_listboxNoSelect args {
	 foreach w $args {
		  bind $w <Button-1> {format x}
	bind $w <B1-Motion> {format x}
	bind $w <Shift-1> {format x}
	bind $w <Shift-B1-Motion> {format x}
	 }
}

# could do with "listbox select&highlight pattern"

proc listboxshowS {lb s {first 0} {cnstr yes}} {
	set sz [$lb size]

	for {set i $first} {$i<$sz} {incr i} {
		if {[string match $s [$lb get $i]]} {
			listboxshowI $lb $i $cnstr
			return $i
		}
	}
	return -1
}

proc listboxshowI {lb high {cnstr yes}} {
#   if {$high>=[$lb size] || $high<0} return
	set high [max 0 [min $high [expr {[$lb size]-1}]]]

	set hb [lindex [split [$lb cget -geometry] x] 1]
	set hx [max 0 [expr {[$lb size]-$hb}]]
	if {$cnstr eq "yes"} {set hl [expr {$high<$hb?0:[min $high $hx]}]} else {set hl $high}
	$lb select from $high
	$lb yview $hl
}

proc listboxreplace {lb index new} {
	$lb delete $index
	$lb insert $index $new
	# don't lose selection
	$lb select from $index
}


# preserves selection, yview

proc listboxmove {l1 l2} {
	listboxcopy $l1 $l2
	$l1 delete 0 end
}

proc listboxcopy {l1 l2} {

	$l2 delete 0 end
	listboxappend $l1 $l2
	catch {$l2 select from [$l1 curselection]}
# use NEW yview to keep same yview position
#   catch {$l2 yview [$l1 yview]}
}

proc listboxappend {l1 l2} {

	set size [$l1 size]

	for {set i 0} {$i<$size} {incr i} {
		$l2 insert end [$l1 get $i]
	}
}

###

#option add *Entry.relief sunken
#option add *Text.relief sunken
option add *Text.borderwidth 2
#option add *Menubutton.relief raised
#option add *Radiobutton.relief ridge
#option add *Radiobutton.borderwidth 3
#option add *Checkbutton.relief ridge
#option add *Button.relief ridge
#option add *Button.borderwidth 3

###


proc tabgroup {args} {
	if {[llength $args]==1} {set wins [lindex $args 0]} else {set wins $args}

	set l [llength $wins]
	for {set i 0} {$i<$l} {incr i} {
		set w [lindex $wins $i]
		set pw [lindex $wins [expr {($i-1)%$l}]]
		set nw [lindex $wins [expr {($i+1)%$l}]]

		bind $w <KeyPress-Tab> "focus $nw; break"
		bind $w <Shift-KeyPress-Tab> "focus $pw; break"
	}
}


proc winstderr {w msg {type "bell & flash"}} {
	if {![winfo exists $w]} return
	set bell [string match "*bell*" $type]
	set flash [string match "*flash*" $type]
#	regsub -all "\n" $msg " // " msg

	set fg [$w cget -foreground]; set bg [$w cget -background]

	set msgout [string range $msg 0 250]
	if {[string length $msg]>250} {
		append msgout " ... (truncated; full message sent to stdout)"
		puts stderr $msg
	}
	winstdout $w $msgout
	if {$flash} {$w configure -foreground $bg -background $fg}
	if {$bell} bell
	if {$flash} {
		update idletasks; after 500
		$w configure -foreground $fg -background $bg
	}
}

proc winstdout {w {msg AnUnLiKeMeSsAgE} {update 0}} {
	if {![winfo exists $w]} return
	if {$update eq "update"} {set update 1}

	if {$msg ne "AnUnLiKeMeSsAgE"} {
		$w configure -text $msg
		if {$update} { update idletasks }
	}
	return [$w cget -text]
}

proc yviewcontext {w l c} {
	if {$l eq "sel"} {
		set cnt [scan [$w tag ranges sel] %d l]
		if {$cnt<=0} return
	}

	incr l -1; # 0-based!

	scan [$w index end] %d n
	set prev [expr {$l-$c}]; set next [expr {$l+$c}]

	if {$prev>=0} {$w yview -pickplace $prev}
	if {$next<=$n} {$w yview -pickplace $next}
	$w yview -pickplace $l
}


proc screencenter {xy wh} {
	if {$xy eq "x"} {
		return [expr {([winfo screenwidth .]-$wh)/2}]
	} else {
		return [expr {([winfo screenheight .]-$wh)/2}]
	}
}

# this doesn't work
#button .a -cursor watch
#proc cursorBusy {} {
#   focus .a; grab .a
#}
#
#proc cursorUnBusy {} {
#   global win
#   grab release .a; focus \$win.list
#}

proc cursorBusy {{up 1}} {
	if {[. cget -cursor] ne "watch"} {
		cursorSet watch; if {$up} {update idletasks}
	}
}
proc cursorSet {c {w .}} {
	global cursor
#if {$w eq "."} {puts "cursorSet"}
	set cursor($w) [$w cget -cursor]
#puts "cursor($w) = $cursor($w)"
	$w configure -cursor $c
	foreach child [winfo children $w] {cursorSet $c $child}
}
proc cursorUnset {{w .}} {
	global cursor
#if {$w eq "."} {puts "cursorUnset"}
	catch {$w configure -cursor $cursor($w)}
	foreach child [winfo children $w] {cursorUnset $child}
}

proc configurestate {wins {flag "menu"}} {
	set flag0 $flag
	foreach w $wins {
		set flag $flag0
		if {$flag eq "menu"} {
			if {[winfo class $w] eq "Menubutton"} {
				set m [$w cget -menu]; set end [$m index end]
				set flag [expr {$end ne "none" && (![$m cget -tearoff] || $end>0)} ]
			} else { set flag 0 }
		}
		$w configure -state [expr {$flag?"normal":"disabled"}]
	}
}

# Tk-related

# singleton menu
proc smenu {m args} {
	if {![winfo exists $m]} {eval menu $m $args}
	return $m
}