Explain now also finds Gils attributes.
[ir-tcl-moved-to-github.git] / client2 / client.tcl
1 wm title . "IrTcl Client"
2
3 # Procedure irmenu
4 proc irmenu {w} {
5     menu $w -tearoff off
6 }
7
8 proc debug-window {text} {
9     if {[winfo exists .debug-window.top.t]} {
10         .debug-window.top.t insert end "$text \n"
11     } else {
12         set w .debug-window
13         toplevel $w
14     
15         wm title $w "Debug Window" 
16         
17         frame $w.top -relief raised -border 1
18         frame $w.bot -relief raised -border 1
19         pack  $w.top -side top -fill both -expand yes
20         pack  $w.bot -fill both
21         scrollbar $w.top.s -command [list $w.top.t yview]
22         text $w.top.t -width 60 -height 10 -wrap word -relief flat \
23             -borderwidth 0 -font fixed -yscroll [list $w.top.s set]
24         pack $w.top.s -side right -fill y
25         pack $w.top.t -expand yes -fill both -expand y
26         .debug-window.top.t insert end "$text \n"
27     }
28 }
29     
30 # Procedure configure-enable-e {w n}
31 #  w   is a menu
32 #  n   menu entry number (0 is first entry)
33 # Enables menu entry
34 proc configure-enable-e {w n} {
35     $w entryconfigure $n -state normal
36 }
37
38 # Procedure configure-disable-e {w n}
39 #  w   is a menu
40 #  n   menu entry number (0 is first entry)
41 # Disables menu entry
42 proc configure-disable-e {w n} {
43     $w entryconfigure $n -state disabled
44 }
45 set noFocus [list -takefocus 0]
46
47
48 # Define dummy clock function if it is not there.
49 if {[catch {clock seconds}]} {
50     proc clock {args} {
51         return {}
52     }
53 }
54
55 # Define libdir to the IrTcl configuration directory.
56 # In the line below LIBDIR will be modified during 'make install'.
57 set libdir LIBDIR
58
59 # If the bitmaps sub directory is present with a bitmap we assume 
60 # the client is run from the source directory in which case we
61 # set libdir the current directory.
62 if {[file readable [file join bitmaps book2]]} {
63     set libdir .
64 }
65
66 # Make a final check to see if libdir was set ok.
67 if {! [file readable [file join $libdir bitmaps book2]]} {
68     puts "Cannot locate system files in ${libdir}. You must either run this"
69     puts "program from the source directory root of ir-tcl or you must assure"
70     puts "that it is installed - normally in /usr/local/lib/irtcl"
71     exit 1
72 }
73
74 # Initialize a lot of globals.
75 set hotTargets {}
76 set hotInfo {}
77 set busy 0
78
79 set profile(Default,description) {}
80 set profile(Default,host) {}
81 set profile(Default,port) 210
82 set profile(Default,authentication) {}
83 set profile(Default,maximumRecordSize) 50000
84 set profile(Default,preferredMessageSize) 30000
85 set profile(Default,comstack) tcpip
86 set profile(Default,namedResultSets) 1
87 set profile(Default,queryRPN) 1
88 set profile(Default,queryCCL) 0
89 set profile(Default,protocol) Z39
90 set profile(Default,windowNumber) 1
91 set profile(Default,largeSetLowerBound) 2
92 set profile(Default,smallSetUpperBound) 0
93 set profile(Default,mediumSetPresentNumber) 0
94 set profile(Default,presentChunk) 4
95 set profile(Default,timeDefine) {}
96 set profile(Default,timeLastInit) {}
97 set profile(Default,timeLastExplain) {}
98 set profile(Default,targetInfoName) {}
99 set profile(Default,recentNews) {}
100 set profile(Default,maxResultSets) {}
101 set profile(Default,maxResultSize) {}
102 set profile(Default,maxTerms) {}
103 set profile(Default,multipleDatabases) 0
104 set profile(Default,welcomeMessage) {}
105
106 set hostid Default
107 set currentDb Default
108 set settingsChanged 0
109 set setNo 0
110 set setNoLast 0
111 set cancelFlag 0
112 set scanEnable 0
113 set displayFormat 1
114 set popupMarcdf 0
115 set textWrap word
116 set recordSyntax None
117 set elementSetNames None
118 set delayRequest {}
119 set debugMode 0
120 set queryAutoOld 0
121 set leadText 1
122
123 set queryTypes {Simple}
124 set queryButtonsBib1 { { {I 0} {I 1} {I 2} } }
125 set queryInfoBib1 { { {Title {1=4 4=1}} {Author {1=1}} \
126         {Subject {1=21}} {Any {1=1016}} } }
127 set queryAuto 1
128 wm minsize . 0 0
129
130 set setOffset 0
131 set setMax 0
132
133 set syntaxList {None sep USMARC UNIMARC UKMARC DANMARC FINMARC NORMARC \
134     PICAMARC sep SUTRS sep GRS1}
135
136
137 set font(bb,normal) {Helvetica 24}
138 set font(bb,bold) {Helvetica 24 bold}
139 set font(b,normal) {Helvetica 24}
140 set font(b,bold) {Helvetica 18 bold}
141 set font(n,normal) {Helvetica 12}
142 set font(n,bold) {Helvetica 12 bold}
143 set font(s,bold) {Helvetica 10 bold}
144 set font(ss,bold) {Helvetica 8 bold}
145
146 # Procedure tkerror {err}
147 #   err   error message
148 # Override the Tk error handler function.
149 if {1} {
150     proc tkerror err {
151         global font
152         set w .tkerrorw
153         
154         if {[winfo exists $w]} {
155             destroy $w
156         }
157         toplevel $w
158         wm title $w "Error"
159         
160         place-force $w .
161         top-down-window $w
162         
163         label $w.top.b -bitmap error
164         message $w.top.t -aspect 300 -text "Error: $err" -font $font(b,bold)
165         pack $w.top.b $w.top.t -side left -padx 10 -pady 10
166         
167         bottom-buttons $w [list {Close} [list destroy $w]] 1
168     }
169 }
170
171 # Read tag set file (if present)
172 if {[file readable [file join $libdir tagsets.tcl]]} {
173     source [file join $libdir tagsets.tcl]
174 }
175
176 # Read the global target configuration file.
177 if {[file readable [file join $libdir irtdb.tcl]]} {
178     source [file join $libdir irtdb.tcl]
179 }
180 # Read the local target configuration file.
181 if {[file readable "irtdb.tcl"]} {
182     source "irtdb.tcl"
183 }
184
185 # Read the user configuration file.
186 if {[file readable "~/.clientrc.tcl"]} {
187     source "~/.clientrc.tcl"
188 }
189
190 set queryAutoOld $queryAuto
191 set attribute$attributeTypeSelected 1
192
193 # Convert old format to new format...
194 foreach target [array names profile] {
195     set timedef [clock seconds]
196     if {[string first , $target] == -1} {
197     if {![info exists profile($target,port)]} {
198         foreach n [array names profile Default,*] {
199             set profile($target,[string range $n 8 end]) $profile($n)
200         }
201         set profile($target,description) [lindex $profile($target) 0]
202         set profile($target,host) [lindex $profile($target) 1]
203         set profile($target,port) [lindex $profile($target) 2]
204         set profile($target,authentication) [lindex $profile($target) 3]
205         set profile($target,maximumRecordSize) \
206         [lindex $profile($target) 4]
207         set profile($target,preferredMessageSize) \
208         [lindex $profile($target) 5]
209         set profile($target,comstack) [lindex $profile($target) 6]
210         set profile($target,databases) [lindex $profile($target) 7]
211         set profile($target,timeDefine) $timedef
212         set profile($target,windowNumber) 1
213     }
214     unset profile($target)
215     }
216 }
217
218 # Assign unique ID's to each target's window number
219 set wno 1
220 foreach n [array names profile *,windowNumber] {
221     set profile($n) $wno
222     incr wno
223 }
224 set profile(Default,windowNumber) $wno
225
226 # These globals describe the current query type. They are set to the
227 # first query type.
228 if {[info exists queryButtons$attributeTypeSelected]} {
229     update
230     set queryButtonsFind [lindex [set "queryButtons$attributeTypeSelected"] 0]
231 } else {
232     set queryButtonsFind [lindex [set queryButtonsBib1] 0]
233     set queryButtons$attributeTypeSelected $queryButtonsBib1
234
235 if {[info exists queryInfo$attributeTypeSelected]} {   
236     set queryInfoFind [lindex [set "queryInfo$attributeTypeSelected"] 0]
237 } else {
238     set queryInfoFind [lindex [set queryInfoBib1] 0]
239     set queryInfo$attributeTypeSelected $queryInfoBib1
240 }    
241
242 # Procedure read-formats
243 # Read all Tcl source files in the subdirectory 'formats'.
244 # The name of each source will correspond to a display format.
245 proc read-formats {} {
246     global displayFormats libdir
247
248     set oldDir [pwd]
249     cd [file join $libdir formats]
250     set formats [glob {*.[tT][cC][lL]}]
251     foreach f $formats {
252         if {[file readable $f]} {
253             source $f
254             set l [string length $f]
255             set f [string tolower [string range $f 0 [expr $l - 5]]]
256             lappend displayFormats $f
257         }
258     }
259     cd $oldDir
260 }
261
262 # Procedure set-wrap {m}
263 #  m    boolean wrap mode
264 # Handler to enable/disable text wrap in the main record window
265 proc set-wrap {m} {
266     global textWrap
267
268     set textWrap $m
269     .data.record configure -wrap $m
270 }
271
272 # Procedure dputs {m}
273 #  m    string to be printed
274 # puts utility for debugging.
275 proc dputs {m} {
276     global debugMode
277     if {$debugMode == 1} {
278         puts $m
279     }
280 }
281
282 # Procedure apduDump {}
283 # Logs BER dump of last APDU in window if debugMode is true.
284 proc apduDump {} {
285     global debugMode
286
287     set w .apdu
288
289     if {$debugMode == 0} return
290     set x [z39 apduInfo]
291
292     set offset [lindex $x 1]
293     set length [lindex $x 0]
294
295     if {![winfo exists $w]} {
296         catch {destroy $w}
297         toplevelG $w
298
299         wm title $w "APDU information"       
300         wm minsize $w 0 0
301         
302         top-down-window $w
303         
304         text $w.top.t -font fixed -width 60 -height 12 -wrap word \
305             -relief flat -borderwidth 0 \
306             -yscrollcommand [list $w.top.s set] -background grey85
307         scrollbar $w.top.s -command [list $w.top.t yview]
308         pack $w.top.s -side right -fill y
309         pack $w.top.t -expand yes -fill both
310
311         bottom-buttons $w [list {Close} [list destroy $w]] 0
312     }
313     $w.top.t insert end "Length: ${length}\n"
314     if {$offset != -1} {
315         $w.top.t insert end "Offset: ${offset}\n"
316     }
317     $w.top.t insert end [lindex $x 2]
318     $w.top.t insert end "---------------------------------\n"
319
320 }
321
322 # Procedure set-display-format {f}
323 #  f    display format
324 # Reformats main record window to use display format given by f
325 proc set-display-format {f} {
326     global displayFormat setNo busy
327
328     set displayFormat $f
329     if {$setNo == 0} {
330         return
331     }
332     if {!$busy} {
333         .bot.a.status configure -text "Reformatting"
334     }
335     update idletasks
336     add-title-lines -1 10000 1
337 }
338
339 # Procedure initBindings
340 # Disables various default bindings for Text and Listbox widgets.
341 proc initBindings {} {
342     global TextBinding
343
344     foreach e [bind Text] {
345         set TextBinding($e) [bind Text $e]
346         bind Text $e {}
347     }
348     set w Listbox
349     bind $w <B1-Motion> {}
350     bind $w <Shift-B1-Motion> {}
351
352     set w Entry
353 }
354
355 # Procedure TextEditable 
356 # Apply "standard" events to a text widget. It should be editable now.
357 proc TextEditable {w} {
358     global TextBinding
359
360     foreach e [array names TextBinding] {
361         bind $w $e $TextBinding($e)
362     }
363 }
364
365 # Procedure destroyGW {w}
366 #   w     top level widget
367 # Saves geometry of widget w in windowGeometry array. This
368 # Procedure is used to save current geometry of a window before
369 # it is destroyed.
370 # See also topLevelG.
371 proc destroyGW {w} {
372     global windowGeometry
373     catch {set windowGeometry($w) [wm geometry $w]}
374 }    
375
376 # Procedure topLevelG
377 #   w     top level widget
378 # Makes a new top level widget named w; sets geometry of window if it 
379 # exists in windowGeometry array. The destroyGW procedure is set 
380 # to be called when the Destroy event occurs.
381 proc toplevelG {w} {
382     global windowGeometry
383
384     if {![winfo exists $w]} {
385         toplevel $w
386     }
387     if {[info exists windowGeometry($w)]} {
388         set g $windowGeometry($w)
389         if {$g != ""} {
390             wm geometry $w $g
391         }
392     } 
393     bind $w <Destroy> [list destroyGW $w]
394 }
395
396 # Procedure top-down-window {w}
397 #  w    window (possibly top level)
398 # Makes two frames inside w called top and bot.
399 proc top-down-window {w} {
400     frame $w.top -relief raised -border 1
401     frame $w.bot -relief raised -border 1
402     pack  $w.top -side top -fill both -expand yes
403     pack  $w.bot -fill both
404 }
405
406 # Procedure top-down-ok-cancel {w ok-action g}
407 #  w          top level widget with $w.bot-frame
408 #  ok-action  ok script
409 #  g          grab flag
410 # Makes two buttons in the bot frame called Ok and Cancel. The
411 # ok-action is executed if Ok is pressed. If Cancel is activated
412 # The window is destroyed. If g is true a grab is performed on the
413 # window and the procedure waits until the window is destroyed.
414 proc top-down-ok-cancel {w ok-action g} {
415     frame $w.bot.left -relief sunken -border 1
416     pack $w.bot.left -side left -expand yes -ipadx 2 -ipady 2 -padx 1 -pady 1
417     button $w.bot.left.ok -width 4 -text {Ok} -command ${ok-action}
418     pack $w.bot.left.ok -expand yes -ipadx 1 -ipady 1 -padx 2 -pady 2
419     button $w.bot.cancel -width 5 -text {Cancel} -command [list destroy $w]
420     pack $w.bot.cancel -side left -expand yes    
421
422     if {$g} {
423         grab $w
424         tkwait window $w
425     }
426 }
427
428 # Procedure bottom-buttons {w buttonList g}
429 #  w          top level widget with $w.bot-frame
430 #  buttonList button specifications
431 #  g          grab flag
432 # Makes a list of buttons in the $w.bot frame. The buttonList is a list 
433 # of button specifications. Each button specification consists of two
434 # items; the first item is button label name; the second item is a script
435 # of be executed when that button is executed. A grab is performed if g 
436 # is true and it waits for the window to be destroyed.
437 proc bottom-buttons {w buttonList g} {
438     set i 0
439     set l [llength $buttonList]
440
441     frame $w.bot.$i -relief sunken -border 1
442     pack $w.bot.$i -side left -expand yes -padx 2 -pady 2
443     button $w.bot.$i.ok -text [lindex $buttonList $i] \
444         -command [lindex $buttonList [expr $i + 1]]
445     pack $w.bot.$i.ok -expand yes -padx 2 -pady 2 -side left
446
447     incr i 2
448     while {$i < $l} {
449         button $w.bot.$i -text [lindex $buttonList $i] \
450                 -command [lindex $buttonList [expr $i + 1]]
451         pack $w.bot.$i -expand yes -padx 2 -pady 2 -side left
452         incr i 2
453     }
454     if {$g} {
455         # Grab ...
456         grab $w
457         tkwait window $w
458     }
459 }
460
461 # Procedure cancel-operation
462 # This handler is invoked when the user wishes to cancel an operation.
463 # If the system is currently busy a "Cancel" will be displayed in the
464 # status area and the cancelFlag is set to true indicating that future
465 # responses from the target should be ignored. The system is no longer
466 # busy when this procedure exists.
467 proc cancel-operation {} {
468     global cancelFlag busy delayRequest
469
470     if {$busy} {
471         set cancelFlag 1
472         set delayRequest {}
473         show-status Cancel 0 1
474     }
475 }
476
477 # Procedure show-target {target base}
478 #  target     name of target
479 #  base       name of database
480 # Displays target name and database name in the target status area.
481 proc show-target {target base} {
482     if {![string length $target]} {
483         .bot.a.target configure -text {}
484         return
485     }
486     if {![string length $base]} {
487         .bot.a.target configure -text "$target"
488     } else {
489          .bot.a.target configure -text "$target - $base"
490     }
491 }
492
493 # Procedure show-logo {v1}
494 #  v1    integer level
495 # This procedure maintains the book logo in the bottom of the screen.
496 # It is invoked only once during initialization of windows, etc., and
497 # by itself. The global 'busy' variable determines whether the logo is
498 # moving or not.
499 proc show-logo {v1} {
500     global busy libdir
501
502     if {$busy != 0} {
503         incr v1
504         if {$v1==10} {
505             set v1 1
506         }
507         .bot.logo configure -bitmap @[file join $libdir bitmaps book${v1}] 
508         after 140 [list show-logo $v1]
509         return
510     }
511     while {1} {
512         .bot.logo configure -bitmap @[file join $libdir bitmaps book1]
513         tkwait variable busy
514         if {$busy} {
515             show-logo 1
516             return
517         }
518     }
519 }
520
521 # Procedure show-status {status b sb}
522 #  status     status message string
523 #  b          busy indicator
524 #  sb         search busy indicator
525 # Display status information according to 'status' and sets the global
526 # busy flag 'busy' to b if b is non-empty. If sb is non-empty it indicates
527 # whether service buttons should be enabled or disabled.
528 proc show-status {status b sb} {
529     global busy scanEnable setOffset setMax setNo
530
531     .bot.a.status configure -text "$status"
532     if {$b == 1} {
533         if {$busy == 0} {set busy 1}
534     } else {
535         set busy 0
536     }
537     if {$sb == {}} {
538         return
539     }
540     if {$sb} {
541         .top.service configure -state normal
542         .mid.search configure -state normal
543         if {$scanEnable} {
544             .mid.scan configure -state normal
545         } else {
546             configure-disable-e .top.service.m 3
547         }
548         if {$setNo == 0} {
549             configure-disable-e .top.service.m 1
550         } elseif {[z39.$setNo nextResultSetPosition] > 0 && 
551             [z39.$setNo nextResultSetPosition] <= [z39.$setNo resultCount]} {
552             configure-enable-e .top.service.m 1
553             .mid.present configure -state normal
554         } else {
555             configure-disable-e .top.service.m 1
556             .mid.present configure -state disabled
557         }
558         if {[winfo exists .scan-window]} {
559             .scan-window.bot.2 configure -state normal
560             .scan-window.bot.4 configure -state normal
561         }
562     } else {
563         .top.service configure -state disabled
564         .mid.search configure -state disabled
565         .mid.scan configure -state disabled
566         .mid.present configure -state disabled
567
568         if {[winfo exists .scan-window]} {
569             .scan-window.bot.2 configure -state disabled
570             .scan-window.bot.4 configure -state disabled
571         }
572     }
573 }
574
575 # Procedure show-message {msg}
576 #  msg    message string
577 # Sets message the bottom of the screen to msg.
578 proc show-message {msg} {
579     .bot.a.message configure -text "$msg"
580 }
581
582 # Procedure insertWithTags {w text args}
583 #  w      text widget
584 #  text   string to be inserted
585 #  args   list of tags
586 # Inserts text at the insertion point in widget w. The text is tagged 
587 # with the tags in args.
588 proc insertWithTags {w text args} {
589     global leadText
590     set text [string trimright $text ,]
591     set start [$w index insert]
592     if {[lsearch {marc-text marc-it marc-id} $args] == -1||$leadText} {
593         $w insert insert "$text"
594     } else {
595         $w insert insert ", $text"
596     }
597     foreach tag [$w tag names $start] {
598         $w tag remove $tag $start insert
599     }
600     foreach i $args {
601         $w tag add $i $start insert
602     }
603     set leadText 0
604     if {[lsearch -exact {marc-head marc-pref marc-tag marc-small-head} $args] != -1} {
605         set leadText 1
606     }
607 }
608
609 # Procedure popup-license and displays LICENSE information.
610 proc popup-license {} {
611     global libdir
612     set w .popup-license
613     toplevel $w
614
615     wm title $w "License" 
616     wm minsize $w 0 0
617
618     top-down-window $w
619
620     text $w.top.t -width 80 -height 10 -wrap word -relief flat -borderwidth 0 \
621         -font fixed -yscrollcommand [list $w.top.s set]
622     scrollbar $w.top.s -command [list $w.top.t yview]
623     pack $w.top.s -side right -fill y
624     pack $w.top.t -expand yes -fill both
625
626     if {[file readable [file join $libdir LICENSE]]} {
627         set f [open [file join $libdir LICENSE] r]
628         while {[gets $f buf] != -1} {
629             $w.top.t insert end $buf
630             $w.top.t insert end "\n"
631         } 
632         close $f
633     }
634     bottom-buttons $w [list {Close} [list destroy $w]] 1
635 }
636
637 # Procedure about-target
638 # Displays various information about the current target, such
639 # as implementation-name, implementation-id, etc.
640 proc about-target {} {
641     set w .about-target-w
642     global hostid font
643
644     toplevel $w
645
646     wm title $w "About target"
647     place-force $w .
648     top-down-window $w
649
650     frame $w.top.a -relief ridge -border 2
651     frame $w.top.p -relief ridge -border 2 -background white
652     pack $w.top.a $w.top.p -side top -fill x
653
654     label $w.top.a.about -text "About"
655     label $w.top.a.irtcl -text $hostid -font $font(bb,bold)
656     pack $w.top.a.about $w.top.a.irtcl -side top
657
658     set i [z39 targetImplementationName]
659     label $w.top.p.in -text "Implementation name: $i" -background white
660     set i [z39 targetImplementationId]
661     label $w.top.p.ii -text "Implementation id: $i" -background white
662     set i [z39 targetImplementationVersion]
663     label $w.top.p.iv -text "Implementation version: $i" -background white
664     set i [z39 options]
665     label $w.top.p.op -text "Protocol options: $i" -background white
666     pack $w.top.p.in $w.top.p.ii $w.top.p.iv $w.top.p.op -side top -anchor nw
667
668     bottom-buttons $w [list {Close} [list destroy $w]] 1
669 }
670
671 # Procedure about-origin-logo {n}
672 #   n    integer level
673 # Displays book logo in the .about-origin-w widget
674 proc about-origin-logo {n} {
675     global libdir
676     set w .about-origin-w
677     if {![winfo exists $w]} {
678         return
679     }
680     incr n
681     if {$n==10} {
682         set n 1
683     }
684     $w.top.a.logo configure -bitmap @[file join $libdir bitmaps book$n]
685     after 140 [list about-origin-logo $n]
686 }
687
688 # Procedure about-origin
689 # Display various information about origin (this client).
690 proc about-origin {} {
691     set w .about-origin-w
692     global libdir font tk_version
693     
694     if {[winfo exists $w]} {
695         destroy $w
696     }
697     toplevel $w
698
699     wm title $w "About IrTcl"
700     place-force $w .
701     top-down-window $w
702
703     frame $w.top.a -relief ridge -border 2
704     frame $w.top.p -relief ridge -border 2
705     pack $w.top.a $w.top.p -side top -fill x
706     
707     label $w.top.a.irtcl -text "IrTcl" -font $font(bb,bold)
708     label $w.top.a.logo -bitmap @[file join $libdir bitmaps book1] 
709     pack $w.top.a.irtcl $w.top.a.logo -side left -expand yes
710
711     set i unknown
712     catch {set i [z39 implementationName]}
713     label $w.top.p.in -text "Implementation name: $i"
714     catch {set i [z39 implementationId]}
715     label $w.top.p.ii -text "Implementation id: $i"
716     catch {set i [z39 implementationVersion]}
717     label $w.top.p.iv -text "Implementation version: $i"
718     set i $tk_version
719     label $w.top.p.tk -text "Tk version: $i"
720     pack $w.top.p.in $w.top.p.ii $w.top.p.iv $w.top.p.tk -side top -anchor nw
721
722     about-origin-logo 1
723     bottom-buttons $w [list {Close} [list destroy $w] \
724                             {License} [list popup-license]] 0
725 }
726
727 # Procedure popup-marc {sno no b df}
728 #  sno     result set number
729 #  no      record position number
730 #  b       popup window number
731 #  df      display format
732 # Displays record in set $sno at position $no in window .full-marc$b.
733 # The global variable $popupMarcdf holds the current format method.
734 proc popup-marc {sno no b df} {
735     global font displayFormats popupMarcdf
736
737     if {[z39.$sno type $no] != "DB"} {
738         return
739     }
740     if {$b == -1} {
741         set b 0
742         while {[winfo exists .full-marc$b]} {
743             incr b
744         }
745     }
746     set df $popupMarcdf
747     set w .full-marc$b
748     if {![winfo exists $w]} {
749         toplevelG $w
750
751         wm minsize $w 0 0
752         
753         frame $w.top -relief raised -border 1
754         frame $w.bot -relief raised -border 1
755         pack  $w.top -side top -fill both -expand yes
756         pack  $w.bot -fill both
757
758         text $w.top.record -width 60 -height 5 -wrap word -relief flat \
759             -borderwidth 0 -font fixed \
760             -yscrollcommand [list $w.top.s set] -background white
761         scrollbar $w.top.s -command [list $w.top.record yview] 
762         $w.top.record tag configure marc-tag -foreground blue
763         $w.top.record tag configure marc-id -foreground red
764         $w.top.record tag configure marc-data -foreground black
765         $w.top.record tag configure marc-head -font $font(n,bold) \
766              -background black -foreground white
767         $w.top.record tag configure marc-pref -font $font(n,normal) -foreground blue
768         $w.top.record tag configure marc-text -font $font(n,normal) -foreground black
769         $w.top.record tag configure marc-it -font $font(n,normal) -foreground black
770
771         pack $w.top.s -side right -fill y
772         pack $w.top.record -expand yes -fill both
773         
774         bottom-buttons $w [list {Close} [list destroy $w] \
775             {Prev} {} {Next} {} {Duplicate} {}] 0
776         menubutton $w.bot.formats -text "Format" -menu $w.bot.formats.m -relief raised
777         irmenu $w.bot.formats.m
778         pack $w.bot.formats -expand yes -ipadx 2 -ipady 2 -padx 3 -pady 3 -side left
779     } else {
780         $w.bot.formats.m delete 0 last
781     }
782     set i 0
783     foreach f $displayFormats {
784         $w.bot.formats.m add radiobutton -label $f -variable popupMarcdf -value $i \
785             -command [list popup-marc $sno $no $b 0]
786         incr i
787     }
788     $w.top.record delete 0.0 end
789     set recordType [z39.$sno recordType $no]
790     wm title $w "$recordType record #$no"
791     focus $w
792
793     $w.bot.2 configure -command [list popup-marc $sno [expr $no-1] $b $df]
794     $w.bot.4 configure -command [list popup-marc $sno [expr $no+1] $b $df]
795     if {$no == 1} {
796         $w.bot.2 configure -state disabled
797     } else {
798         $w.bot.2 configure -state normal
799     }
800     if {[z39.$sno type [expr $no+1]] != "DB"} {
801         $w.bot.4 configure -state disabled
802     } else {
803         $w.bot.4 configure -state normal
804     }
805     $w.bot.6 configure -command [list popup-marc $sno $no -1 0]
806     set ffunc [lindex $displayFormats $df]
807     set ffunc "display-$ffunc"
808
809     $ffunc $sno $no $w.top.record 0
810 }
811
812 # Procedure update-target-hotlist {target base}
813 #  target     current target name
814 #  base       current database name
815 # Updates the global $hotTargets so that $target and $base are
816 # moved to the front, i.e. they become the number 1 target/base.
817 # The target menu is updated by a call to set-target-hotlist.
818 proc update-target-hotlist {target base} {
819     global hotTargets
820
821     set olen [llength $hotTargets]
822     set i 0
823     foreach e $hotTargets {
824         if {$target == [lindex $e 0] && $base == [lindex $e 1]} {
825             set hotTargets [lreplace $hotTargets $i $i]
826             break
827         }
828         incr i    
829     }
830     set hotTargets [linsert $hotTargets 0 [list $target $base]]
831     set-target-hotlist $olen
832
833
834 # Procedure delete-target-hotlist {target}
835 #  target    target to be deleted
836 # Updates the global $hotTargets so that $target is removed.
837 # The target menu is updated by a call to set-target-hotlist.
838 proc delete-target-hotlist {target} {
839     global hotTargets
840
841     set olen [llength $hotTargets]
842     set i 0
843     foreach e $hotTargets {
844         if {$target == [lindex $e 0]} {
845         set hotTargets [lreplace $hotTargets $i $i]
846         }
847         incr i
848     }
849     set-target-hotlist $olen
850 }
851
852 # Procedure set-target-hotlist {olen}
853 #  olen     number of hot target entries to be deleted from menu
854 # Updates the target menu with the targets with the first 8 entries
855 # in the $hotTargets global.
856 proc set-target-hotlist {olen} {
857     global hotTargets
858    
859     if {$olen > 0} {
860        .top.target.m delete 6 [expr 6+$olen]
861     }
862     set i 1
863     foreach e $hotTargets {
864         set target [lindex $e 0]
865         set base [lindex $e 1]
866         if {![string length $base]} {
867             .top.target.m add command -label "$i $target" -command \
868                 [list reopen-target $target {}]
869         } else {
870             .top.target.m add command -label "$i $target - $base" -command \
871                 [list reopen-target $target $base]
872         }
873         incr i
874         if {$i > 8} {
875              break
876         }
877     }
878 }
879
880 # Procedure reopen-target {target base}
881 #  target    target to be opened
882 #  base      base to be used
883 # Closes connection with current target and opens a new connection
884 # with $target and database $base.
885 proc reopen-target {target base} {
886     close-target
887     open-target $target $base
888     update-target-hotlist $target $base
889 }
890
891 # Procedure define-target-action
892 # Prepares the setup of a new target. The name of the target
893 # is read from the dialog .target-define dialog (procedure
894 # define-target-dialog) and the target definition window is displayed by
895 # a call to protocol-setup.
896 proc define-target-action {} {
897     global profile
898     
899     set target [.target-define.top.target.entry get]
900     if {![string length $target]} {
901         return
902     }
903     foreach n [array names profile *,host] {
904         if {![string compare $n ${target},host]} {
905             destroy .target-define
906             protocol-setup $n
907             return
908         }
909     }
910     foreach n [array names profile Default,*] {
911         set profile($target,[string range $n 8 end]) $profile($n)
912     }
913     incr profile(Default,windowNumber)
914     
915 #    debug-window "Target er her $target"
916     protocol-setup $target
917     destroy .target-define
918 }
919
920 # Procedure fail-response {target}
921 #  target   current target
922 # Error handler (IrTcl failback) that takes care of serious protocol
923 # errors, connection lost, etc.
924 proc fail-response {target} {
925     global debugMode
926
927     set c [lindex [z39 failInfo] 0]
928     set m [lindex [z39 failInfo] 1]
929     if {$c == 4 || $c == 5} {
930         set debugMode 1        
931         apduDump
932     }
933     close-target
934 #    tkerror "$m ($c)"
935     bgerror "$m ($c)"
936 }
937
938 # Procedure connect-response {target base}
939 #  target   current target
940 #  base     current database
941 # IrTcl connect response handler.
942 proc connect-response {target base} {
943     dputs "connect-response"
944     init-request $target $base
945 }
946
947 # Procedure open-target {target base}
948 #  target   target to be opened
949 #  base     database to be used
950 # Opens a new connection with $target/$base.
951 proc open-target {target base} {
952     global profile hostid presentChunk currentDb
953
954     z39 disconnect
955     z39 comstack $profile($target,comstack)
956     z39 protocol $profile($target,protocol)
957     eval z39 idAuthentication $profile($target,authentication)
958     z39 maximumRecordSize $profile($target,maximumRecordSize)
959     z39 preferredMessageSize $profile($target,preferredMessageSize)
960     dputs "maximumRecordSize=[z39 maximumRecordSize]"
961     dputs "preferredMessageSize=[z39 preferredMessageSize]"
962     show-status Connecting 1 0
963     set x $profile($target,largeSetLowerBound)
964     if {![string length $x]} {
965         set x 2
966     }
967     z39 largeSetLowerBound $x
968     
969     set x $profile($target,smallSetUpperBound)
970     if {![string length $x]} {
971         set x 0
972     }
973     z39 smallSetUpperBound $x
974     
975     set x $profile($target,mediumSetPresentNumber)
976     if {![string length $x]} {
977         set x 0
978     }
979     z39 mediumSetPresentNumber $x
980
981     set presentChunk $profile($target,presentChunk)
982     if {![string length $presentChunk]} {
983         set presentChunk 4
984     }
985
986     z39 failback [list fail-response $target]
987     z39 callback [list connect-response $target $base]
988     show-target $target $base
989     update idletasks
990     set err [catch {
991         z39 connect $profile($target,host):$profile($target,port)
992     } errorMessage]
993     if {$err} {
994         set hostid Default
995 #        tkerror $errorMessage
996         bgerror $errorMessage
997         show-status "Not connected" 0 {}
998         show-target {} {}
999         return
1000     }
1001     set hostid $target
1002     set currentDb $base
1003     configure-disable-e .top.target.m 0
1004     configure-enable-e .top.target.m 1
1005     configure-enable-e .top.target.m 2
1006 }
1007
1008 # Procedure close-target
1009 # Shuts down the connection with current target.
1010 proc close-target {} {
1011     global hostid cancelFlag setNo setNoLast currentDb
1012
1013     set cancelFlag 0
1014     set setNo 0
1015     set setNoLast 0
1016     .bot.a.set configure -text ""
1017     set hostid Default
1018     set currentDb Default
1019     z39 disconnect
1020     show-target {} {}
1021     show-status {Not connected} 0 0
1022 #    .top.options.m.query.slist entryconfigure 2 -state disabled
1023     configure-enable-e .top.options.m.query.slist 2
1024     init-title-lines
1025     show-message {}
1026     configure-disable-e .top.target.m 1
1027     configure-disable-e .top.target.m 2
1028     .top.rset.m delete 1 last
1029     .top.rset.m add separator
1030     configure-enable-e .top.target.m 0
1031 }
1032
1033 # Procedure load-set-action
1034 # Loads records from a file. The filename is read from the entry
1035 # .load-set.filename.entry (see function load-set)
1036 proc load-set-action {} {
1037     global setNoLast
1038
1039     incr setNoLast
1040     ir-set z39.$setNoLast z39
1041
1042     set fname [.load-set.top.filename.entry get]
1043     destroy .load-set
1044     if {$fname != ""} {
1045         show-status Loading 1 {}
1046         update
1047         z39.$setNoLast loadFile $fname
1048
1049         set no [z39.$setNoLast numberOfRecordsReturned]
1050         add-title-lines $setNoLast $no 1
1051     }
1052     set l [format "%-4d %7d" $setNoLast $no]
1053     .top.rset.m add command -label $l \
1054             -command [list add-title-lines $setNoLast 10000 1]
1055     show-status Ready 0 {}
1056 }
1057
1058 # Procedure load-set
1059 # Dialog that asks for a filename with records to be loaded
1060 # into a result set.
1061 proc load-set {} {
1062     set w .load-set
1063     toplevel $w
1064     set oldFocus [focus]
1065     place-force $w .
1066     top-down-window $w
1067
1068 #    frame $w.top.filename
1069     frame $w.top.left
1070     frame $w.top.right
1071 #    pack $w.top.filename -side top -anchor e -pady 2
1072     pack $w.top.left $w.top.right -side left -anchor e -pady 2
1073       
1074     entry-fields $w.top {left} {{Filename:}} {load-set-action} {destroy .load-set}
1075     button $w.top.right.but -text "Browse ..." \
1076         -command "fileDialog $w $w.top.left.entry open"
1077     pack $w.top.right.but -side right
1078     
1079     top-down-ok-cancel $w {load-set-action} 1
1080 #    focus $oldFocus
1081     focus $w
1082 }
1083
1084 proc fileDialog {w ent operation} {
1085     #   Type names              Extension(s)    Mac File Type(s)
1086     #
1087     #---------------------------------------------------------
1088     set types {
1089         {"Text files"           {.txt}              }
1090         {"Text files"           {}                      TEXT}
1091         {"Tcl Scripts"          {.tcl}              TEXT}
1092         {"All files"            *}
1093     }
1094     if {$operation == "open"} {
1095         set file [tk_getOpenFile -filetypes $types -parent $w]
1096     } else {
1097         set file [tk_getSaveFile -filetypes $types -parent $w \
1098             -initialfile Untitled -defaultextension .txt]
1099     }
1100     if [string compare $file ""] {
1101         $ent delete 0 end
1102         $ent insert 0 $file
1103         $ent xview end
1104     }
1105 }
1106
1107
1108 # Procedure init-request
1109 # Sends an initialize request to the target. This procedure is called
1110 # when a connect has been established.
1111 proc init-request {target base} {
1112     global cancelFlag
1113
1114     if {$cancelFlag} {
1115         close-target
1116         return
1117     }
1118     z39 callback [list init-response $target $base]
1119     show-status Initializing 1 {}
1120     set err [catch {z39 init} errorMessage]
1121     if {$err} {
1122 #        tkerror $errorMessage
1123         bgerror $errorMessage
1124         show-status Ready 0 {}
1125     }
1126 }
1127
1128 # Procedure init-response
1129 # Handles and incoming init-response. The service buttons
1130 # are enabled. The global $scanEnable indicates whether the target
1131 # supports scan.
1132 proc init-response {target base} {
1133     global cancelFlag profile scanEnable settingsChanged
1134
1135     dputs {init-response}
1136     apduDump
1137     if {$cancelFlag} {
1138         close-target
1139         return
1140     }
1141     if {![z39 initResult]} {
1142         set u [z39 userInformationField]
1143         close-target
1144 #        tkerror "Connection rejected by target: $u"
1145         bgerror "Connection rejected by target: $u"
1146     } else {
1147         z39 failback [list explain-crash $target $base]
1148         explain-check $target [list ready-response $base] $base
1149     }
1150 }
1151
1152 # Procedure explain-crash
1153 # Handles target that dies during explain.
1154 proc explain-crash {target base} {
1155     global profile settingsChanged
1156     
1157     set profile($target,timeLastInit) [clock seconds]
1158     set settingsChanged 1
1159
1160     show-message {}
1161     open-target $target $base
1162 }
1163
1164 # Procedure ready-response
1165 # Called after a target has been initialized and, possibly, explained
1166 proc ready-response {base target} {
1167     global profile settingsChanged scanEnable queryAuto
1168     
1169     z39 failback [list fail-response $target]
1170     if {[string length $base]} {
1171     set profile($target,timeLastInit) [clock seconds]
1172     set settingsChanged 1
1173
1174     z39 databaseNames $base
1175     cascade-dblist $target $base
1176     show-target $target $base
1177     }
1178     if {[lsearch [z39 options] scan] >= 0} {
1179         set scanEnable 1
1180     } else {
1181         set scanEnable 0
1182     }
1183     .data.record delete 1.0 end
1184     set desc [string trim $profile($target,description)]
1185     if {[string length $desc]} {
1186         .data.record insert end "$desc\n\n"
1187     } else {
1188         .data.record insert end "$target\n\n"
1189     }
1190     set data [string trim $profile($target,welcomeMessage)]
1191     if {[string length $data]} {
1192         .data.record insert end "Welcome Message:\n$data\n\n"
1193     }
1194     set data [string trim $profile($target,recentNews)]
1195     if {[string length $data]} {
1196         .data.record insert end "News:\n$data\n"
1197     }
1198     ready-response-actions $target $base
1199     show-message {}
1200     show-status Ready 0 1
1201 }
1202
1203 #proc ready-response-actions {target base}
1204 #This procedure take care of all the actions that should start if connect is succesfull.
1205 proc ready-response-actions {target base} {
1206     global profile queryAuto attributeTypeSelected queryTypes
1207     set autoNr [lsearch $queryTypes Auto]
1208     configureOptionsSyntax $target $base
1209 #    if {[info exists profile($target,AttributeDetails,$base,\
1210 #        $attributeTypeSelected)] && $queryAuto == 1} 
1211     if {[info exists profile($target,AttributeDetails,$base,$attributeTypeSelected)]} {
1212         changeQueryButtons $target $base
1213         change-queryInfo $target $base
1214         .top.options.m.query.slist entryconfigure $autoNr -state normal
1215         .top.options.m.query.clist entryconfigure $autoNr -state normal
1216         if {$queryAuto == 1} {
1217             query-select $autoNr
1218         } else {
1219             query-select 0
1220         }
1221     } else {
1222         query-select 0
1223 #        .top.options.m.query.slist entryconfigure $autoNr -state disabled
1224         configure-disable-e .top.options.m.query.slist $autoNr
1225 #        if {![info exists profile($target,AttributeDetails,$base,$attributeTypeSelected)]} 
1226 #            .top.options.m.query.clist entryconfigure $autoNr -state disabled
1227             configure-disable-e .top.options.m.query.clist $autoNr
1228 #        
1229     }
1230     if {[info exists attributeTypeSelected]} {
1231         global attribute[set attributeTypeSelected]
1232         set attribute$attributeTypeSelected 1
1233     } else {
1234         global attributeBib1
1235         set attributeBib1 1
1236     }
1237 }
1238
1239 # Procedure search-request
1240 #  bflag     flag to indicate if this procedure calls itself
1241 # Performs a search. If $busy is 1, the search-request is performed
1242 # at a later time (when another response arrives). This procedure
1243 # sets many search-related Z39-settings. The global $setNo is set
1244 # to the result set number (z39.$setNo).
1245 proc search-request {bflag} {
1246     global setNo setNoLast profile hostid busy cancelFlag delayRequest \
1247         recordSyntax elementSetNames
1248
1249     set target $hostid
1250     
1251     if {![string length [z39 connect]]} {
1252         return
1253     }
1254     dputs "search-request"
1255     show-message {}
1256     if {!$bflag && $busy} {
1257         dputs "busy: search-request ignored"
1258         return
1259     }
1260     if {$cancelFlag} {
1261         dputs "cancelFlag"
1262         show-status Searching 1 0
1263         set delayRequest {search-request 1}
1264         return
1265     }
1266     set delayRequest {} 
1267
1268     set query [index-query]
1269     debug-window "Query er her: \"${query}\""
1270     if {![string length $query]} {
1271         return
1272     }
1273     incr setNoLast
1274     set setNo $setNoLast
1275     ir-set z39.$setNo z39
1276     
1277     if {$profile($target,namedResultSets) == 1} {
1278         z39.$setNo setName $setNo
1279         dputs "setName=${setNo}"
1280     } else {
1281         z39.$setNo setName default
1282         dputs "setName=default"
1283     }
1284     if {$profile($target,queryRPN) == 1} {
1285         z39.$setNo queryType rpn
1286     } elseif {$profile($target,queryCCL) == 1} {
1287         z39.$setNo queryType ccl
1288     }
1289     dputs Setting
1290     dputs $recordSyntax
1291     if {![string compare $recordSyntax None]} {
1292         z39.$setNo preferredRecordSyntax {}
1293     } else {
1294         z39.$setNo preferredRecordSyntax $recordSyntax
1295     }
1296     if {![string compare $elementSetNames None]} {
1297         z39.$setNo elementSetNames {}
1298         z39.$setNo smallSetElementSetNames {}
1299         z39.$setNo mediumSetElementSetNames {}
1300     } else {
1301         z39.$setNo elementSetNames $elementSetNames
1302         z39.$setNo smallSetElementSetNames $elementSetNames
1303         z39.$setNo mediumSetElementSetNames $elementSetNames
1304     }
1305     z39 callback {search-response}
1306     z39.${setNo} search $query
1307     show-status Searching 1 0
1308 }
1309
1310 # Procedure scan-copy {y entry}
1311 #  y       y-position of mouse pointer
1312 #  entry   a search entry in the top
1313 # Copies the term in the list nearest $y to the query entry specified
1314 # by $entry
1315 proc scan-copy {y entry} {
1316     set w .scan-window
1317     set no [$w.top.list nearest $y]
1318     dputs "no=$no"
1319     .lines.$entry.e delete 0 end
1320     .lines.$entry.e insert 0 [string range [$w.top.list get $no] 8 end]
1321 }
1322
1323 # Procedure scan-request
1324 # Performs a scan on term "0" with the current attributes in entry
1325 # specified by the global $curIndexEntry.
1326 proc scan-request {} {
1327     set w .scan-window
1328
1329     global profile hostid scanView scanTerm curIndexEntry queryButtonsFind \
1330         queryInfoFind cancelFlag delayRequest
1331
1332     dputs "scan-request"
1333     if {$cancelFlag} {
1334         dputs "cancelFlag"
1335         show-status Scanning 1 0
1336         set delayRequest scan-request
1337         return
1338     }
1339     set delayRequest {} 
1340     set target $hostid
1341     set scanView 0
1342     set scanTerm {}
1343     set b [lindex $queryButtonsFind $curIndexEntry]
1344     set attr {}
1345     foreach a [lrange [lindex $queryInfoFind [lindex $b 1]] 1 end] {
1346         set attr "@attr $a $attr"
1347     }
1348     set title [lindex [lindex $queryInfoFind [lindex $b 1]] 0]
1349     ir-scan z39.scan z39
1350
1351     if {![winfo exists $w]} {
1352         toplevelG $w
1353         
1354         wm minsize $w 0 0
1355
1356         top-down-window $w
1357
1358         entry $w.top.entry -relief sunken 
1359         pack $w.top.entry -fill x -padx 4 -pady 2
1360         bind $w.top.entry <KeyRelease> [list scan-term-h $attr]
1361         listbox $w.top.list -yscrollcommand [list $w.top.scroll set] \
1362             -font fixed -background white
1363         scrollbar $w.top.scroll -orient vertical -border 1
1364         pack $w.top.list -side left -fill both -expand yes
1365         pack $w.top.scroll -side right -fill y
1366         $w.top.scroll config -command [list $w.top.list yview]
1367         
1368         bottom-buttons $w [list {Close} [list destroy $w] \
1369             {Up} [list scan-up $attr] {Down} [list scan-down $attr]] 0
1370         bind $w.top.list <Up> [list scan-up $attr]
1371         bind $w.top.list <Down> [list scan-down $attr]
1372         focus $w.top.entry
1373     }
1374     bind $w.top.list <Double-Button-1> [list scan-copy %y $curIndexEntry]
1375     wm title $w "Scan $title"
1376         
1377     z39 callback [list scan-response $attr 0 35]
1378     z39.scan numberOfTermsRequested 5
1379     z39.scan preferredPositionInResponse 1
1380     z39.scan scan "${attr} 0"
1381     
1382     show-status Scanning 1 0
1383 }
1384
1385 # Procedure scan-term-h {attr} 
1386 # attr    attribute specification
1387 # This procedure is called whenever a key is released in the entry in the
1388 # scan window (.scan-window). A scan is then initiated with the new contents
1389 # of the entry as the starting term.
1390 proc scan-term-h {attr} {
1391     global busy scanTerm
1392
1393     if {$busy} {
1394         return
1395     }
1396     set w .scan-window
1397     set nScanTerm [$w.top.entry get]
1398     if {$nScanTerm == $scanTerm} {
1399         return
1400     }
1401     set scanTerm $nScanTerm
1402     z39 callback [list scan-response $attr 0 35]
1403     z39.scan numberOfTermsRequested 5
1404     z39.scan preferredPositionInResponse 1
1405     dputs "${attr} \{${scanTerm}\}"
1406     if {![string length $scanTerm]} {
1407         z39.scan scan "${attr} 0"
1408     } else {
1409         z39.scan scan "${attr} \{${scanTerm}\}"
1410     }
1411     show-status Scanning 1 0
1412 }
1413
1414 # Procedure scan-response {attr start toget}
1415 #  attr   attribute specification
1416 #  start  position of first term in the response
1417 #  toget  number of total terms to get
1418 # This procedure handles all scan-responses. $start specifies the list
1419 # entry number of the first incoming term. The $toget indicates the total
1420 # number of terms to be retrieved from the target. The $toget may be
1421 # negative in which case, scan is performed 'backwards' (- $toget is
1422 # the total number of terms in this case). This procedure usually calls
1423 # itself several times in order to get small scan-term-list chunks.
1424 proc scan-response {attr start toget} {
1425     global cancelFlag delayRequest scanTerm scanView
1426
1427     set w .scan-window
1428     dputs "In scan-response"
1429     apduDump
1430     set m [z39.scan numberOfEntriesReturned]
1431     dputs $m
1432     dputs attr=$attr
1433     dputs start=$start
1434     dputs toget=$toget
1435
1436     if {![winfo exists .scan-window]} {
1437         if {$cancelFlag} {
1438             set cancelFlag 0
1439             dputs "Handling cancel"
1440             if {$delayRequest != ""} {
1441                 eval $delayRequest
1442             }
1443             return
1444         }
1445         show-status Ready 0 1
1446         return
1447     }
1448     set nScanTerm [$w.top.entry get]
1449     if {$nScanTerm != $scanTerm} {
1450         z39 callback [list scan-response $attr 0 35]
1451         z39.scan numberOfTermsRequested 5
1452         z39.scan preferredPositionInResponse 1
1453         set scanTerm $nScanTerm
1454         dputs "${attr} \{${scanTerm}\}"
1455         if {![string length $scanTerm]} {
1456             z39.scan scan "${attr} 0"
1457         } else {
1458             z39.scan scan "${attr} \{${scanTerm}\}"
1459         }
1460         show-status Scanning 1 0
1461         return
1462     }
1463     set status [z39.scan scanStatus]
1464     if {$status == 6} {
1465 #        tkerror "Scan fail"
1466         bgerror "Scan fail"
1467         show-status Ready 0 1
1468         set cancelFlag 0
1469         return
1470     }
1471     if {$toget < 0} {
1472         for {set i 0} {$i < $m} {incr i} {
1473             set term [lindex [z39.scan scanLine $i] 1]
1474             set nostr [format " %-6d" [lindex [z39.scan scanLine $i] 2]]
1475             $w.top.list insert $i "$nostr $term"
1476         }
1477         incr scanView $m
1478         $w.top.list yview $scanView
1479     } else {
1480         $w.top.list delete $start end
1481         for {set i 0} {$i < $m} {incr i} {
1482             set term [lindex [z39.scan scanLine $i] 1]
1483             set nostr [format " %-6d" [lindex [z39.scan scanLine $i] 2]]
1484             $w.top.list insert end "$nostr $term"
1485         }
1486     }
1487     if {$cancelFlag} {
1488         dputs "Handling cancel"
1489         set cancelFlag 0
1490         if {$delayRequest != ""} {
1491             eval $delayRequest
1492         }
1493         return
1494     }
1495     set delayRequest {}
1496     if {$toget > 0 && $m > 1 && $m < $toget} {
1497         set ntoget [expr $toget - $m + 1]
1498         dputs ntoget=$ntoget
1499         z39 callback [list scan-response $attr [expr $start + $m - 1] $ntoget]
1500         set q $term
1501         dputs "down continue: $q"
1502         if {$ntoget > 10} {
1503             z39.scan numberOfTermsRequested 10
1504         } else {
1505             z39.scan numberOfTermsRequested $ntoget
1506         }
1507         z39.scan preferredPositionInResponse 1
1508         dputs "${attr} \{$q\}"
1509         z39.scan scan "${attr} \{$q\}"
1510         return
1511     }
1512     if {$toget < 0 && $m > 1 && $m < [expr - $toget]} {
1513         set ntoget [expr - $toget - $m]
1514         dputs ntoget=$ntoget
1515         z39 callback [list scan-response $attr 0 -$ntoget]
1516         set q [string range [$w.top.list get 0] 8 end]
1517         dputs "up continue: $q"
1518         if {$ntoget > 10} {
1519             z39.scan numberOfTermsRequested 10
1520             z39.scan preferredPositionInResponse 11
1521         } else {
1522             z39.scan numberOfTermsRequested $ntoget
1523             z39.scan preferredPositionInResponse [incr ntoget]
1524         }
1525         dputs "${attr} \{$q\}"
1526         z39.scan scan "${attr} \{$q\}"
1527         return
1528     }
1529     show-status Ready 0 1
1530 }
1531
1532 # Procedure scan-down {attr}
1533 #  attr   attribute specification
1534 # This procedure is called when the user hits the Down button the scan
1535 # window. A new scan is initiated with a positive $toget passed to the
1536 # scan-response handler.
1537 proc scan-down {attr} {
1538     global scanView cancelFlag delayRequest
1539
1540     dputs {scan-down}
1541     if {$cancelFlag} {
1542         dputs "cancelFlag"
1543         show-status {Scanning down} 1 0
1544         set delayRequest [list scan-down $attr]
1545         return
1546     }
1547     set delayRequest {} 
1548
1549     set w .scan-window
1550     set scanView [expr $scanView + 5]
1551     set s [$w.top.list size]
1552     if {$scanView > $s} {
1553         z39 callback [list scan-response $attr [expr $s - 1] 25]
1554         set q [string range [$w.top.list get [expr $s - 1]] 8 end]
1555         dputs "down: $q"
1556         z39.scan numberOfTermsRequested 10
1557         z39.scan preferredPositionInResponse 1
1558         show-status Scanning 1 0
1559         dputs "${attr} \{$q\}"
1560         z39.scan scan "${attr} \{$q\}"
1561         return
1562     }
1563     $w.top.list yview $scanView
1564 }
1565
1566 # Procedure scan-up {attr}
1567 #  attr   attribute specification
1568 # This procedure is called when the user hits the Up button the scan
1569 # window. A new scan is initiated with a negative $toget passed to the
1570 # scan-response handler.
1571 proc scan-up {attr} {
1572     global scanView cancelFlag delayRequest
1573
1574     dputs {scan-up}
1575     if {$cancelFlag} {
1576         dputs "cancelFlag"
1577         show-status Scanning 1 0
1578         set delayRequest [list scan-up $attr]
1579         return
1580     }
1581     set delayRequest {} 
1582
1583     set w .scan-window
1584     set scanView [expr $scanView - 5]
1585     if {$scanView < 0} {
1586         z39 callback [list scan-response $attr 0 -25]
1587         set q [string range [$w.top.list get 0] 8 end]
1588         dputs "up: $q"
1589         z39.scan numberOfTermsRequested 10
1590         z39.scan preferredPositionInResponse 11
1591         show-status Scanning 1 0
1592         z39.scan scan "${attr} \{$q\}"
1593         return
1594     }
1595     $w.top.list yview $scanView
1596 }
1597
1598 # Procedure search-response
1599 # This procedure handles search-responses. If the search is successful
1600 # this procedure will try to retrieve a total of 20 records from the target;
1601 # however not more than $presentChunk records at a time. This procedure
1602 # affects the following globals:
1603 #   $setOffset        current record position offset
1604 #   $setMax           total number of records to be retrieved
1605 proc search-response {} {
1606     global setNo setOffset setMax cancelFlag busy delayRequest presentChunk
1607
1608     apduDump
1609     dputs "In search-response"
1610     if {$cancelFlag} {
1611         dputs "Handling cancel"
1612         set cancelFlag 0
1613         if {$delayRequest != ""} {
1614             eval $delayRequest
1615         }
1616         return
1617     }
1618     set setOffset 0
1619     set delayRequest {}
1620     init-title-lines
1621     set setMax [z39.$setNo resultCount]
1622     show-status Ready 0 1
1623     set status [z39.$setNo responseStatus]
1624     if {![string compare [lindex $status 0] NSD]} {
1625         z39.$setNo nextResultSetPosition 0
1626         set code [lindex $status 1]
1627         set msg [lindex $status 2]
1628         set addinfo [lindex $status 3]
1629 #        tkerror "NSD$code: $msg: $addinfo"
1630         bgerror "NSD$code: $msg: $addinfo"
1631         return
1632     }
1633     show-message "${setMax} hits"
1634     if {$setMax == 0} {
1635         return
1636     }
1637     set setOffset 1
1638     show-status Ready 0 1
1639     set l [format "%-4d %7d" $setNo $setMax]
1640     .top.rset.m add command -label $l -command [list recall-set $setNo]
1641     if {$setMax > 20} {
1642         set setMax 20
1643     }
1644     set no [z39.$setNo numberOfRecordsReturned]
1645     dputs "Returned $no records, setOffset $setOffset"
1646     add-title-lines $setNo $no $setOffset
1647     set setOffset [expr $setOffset + $no]
1648
1649     set toGet [expr $setMax - $setOffset + 1]
1650     if {$toGet > 0} {
1651         if {$setOffset == 1} {
1652             set toGet 1
1653         } elseif {$toGet > $presentChunk} {
1654             set toGet $presentChunk
1655         }
1656         z39 callback {present-response}
1657         z39.$setNo present $setOffset $toGet
1658         show-status Retrieving 1 0
1659     }
1660 }
1661
1662 # Procedure present-more {number}
1663 #  number      number of records to be retrieved
1664 # This procedure starts a present-request. The $number variable indicates
1665 # the total number of records to be retrieved. The global $presentChunk
1666 # specifies the number of records to be retrieved at a time. If $number
1667 # is the empty string all remaining records in the result set are 
1668 # retrieved.
1669 proc present-more {number} {
1670     global setNo setOffset setMax busy cancelFlag delayRequest presentChunk
1671
1672     dputs "present-more"
1673     if {$cancelFlag} {
1674         show-status Retrieving 1 0
1675         set delayRequest "present-more $number"
1676         return
1677     }
1678     set delayRequest {}
1679
1680     if {$setNo == 0} {
1681         dputs "setNo=$setNo"
1682     return
1683     }
1684     set setOffset [z39.$setNo nextResultSetPosition]
1685     dputs "setOffest=${setOffset}"
1686     dputs "setNo=${setNo}"
1687     set max [z39.$setNo resultCount]
1688     if {$max < $setOffset} {
1689         dputs "max=$max"
1690         dputs "setOffset=$setOffset"
1691         show-status Ready 0 1
1692         return
1693     }
1694     if {![string length $number]} {
1695         set setMax $max
1696     } else {
1697         incr setMax $number
1698         if {$setMax > $max} {
1699             set setMax $max
1700         }
1701     }
1702     z39 callback {present-response}
1703     
1704     set toGet [expr $setMax - $setOffset + 1]
1705     if {$toGet <= 0} {
1706         return
1707     }
1708     if {$toGet > $presentChunk} {
1709         set toGet $presentChunk
1710     } 
1711     z39.$setNo present $setOffset $toGet
1712     show-status Retrieving 1 0
1713 }
1714
1715 # Procedure init-title-lines 
1716 # Utility that cleans the main record window.
1717 proc init-title-lines {} {
1718     .data.record delete 1.0 end
1719 }
1720
1721 # Procedure recall-set {setno}
1722 #  setno    Set number to recall
1723 proc recall-set {setno} {
1724     add-title-lines $setno 10000 1
1725 }
1726
1727 # Procedure add-title-lines {setno no offset}
1728 #  setno    Set number
1729 #  no       Number of records
1730 #  offset   Starting offset
1731 # This procedure displays the records $offset .. $offset+$no-1 in result
1732 # set $setno in the main record window by using the display format in the
1733 # global $displayFormat
1734 proc add-title-lines {setno no offset} {
1735     global displayFormats displayFormat setNo busy
1736
1737     dputs "add-title-lines offset=${offset} no=${no}"
1738     if {$setno != -1} {
1739         set setNo $setno
1740     } else {
1741         set setno $setNo
1742     }
1743     if {$offset == 1} {
1744         .bot.a.set configure -text $setno
1745         .data.record delete 1.0 end
1746     }
1747     set ffunc [lindex $displayFormats $displayFormat]
1748     dputs "ffunc=$ffunc"
1749     set ffunc "display-$ffunc"
1750     for {set i 0} {$i < $no} {incr i} {
1751         set o [expr $i + $offset]
1752         set type [z39.$setno type $o]
1753         if {![string length $type]} {
1754             dputs "no more at $o"
1755             break
1756         }
1757         .data.record tag bind r$o <Any-Enter> {}
1758         .data.record tag bind r$o <Any-Leave> {}
1759         set insert0 [.data.record index insert]
1760         $ffunc $setno $o .data.record 1
1761         .data.record tag add r$o $insert0 insert
1762         .data.record tag bind r$o <1> [list popup-marc $setno $o 0 0]
1763         update idletasks
1764     }
1765     if {!$busy} {
1766         show-status Ready 0 1
1767     }
1768 }
1769
1770 # Procedure present-response
1771 # Present-response handler. The incoming records are displayed and a new
1772 # present request is performed until all records ($setMax) is returned
1773 # from the target.
1774 proc present-response {} {
1775     global setNo setOffset setMax cancelFlag delayRequest presentChunk
1776
1777     dputs "In present-response"
1778     apduDump
1779     set no [z39.$setNo numberOfRecordsReturned]
1780     dputs "Returned $no records, setOffset $setOffset"
1781     add-title-lines $setNo $no $setOffset
1782     set setOffset [expr $setOffset + $no]
1783     if {$cancelFlag} {
1784         dputs "Handling cancel"
1785         set cancelFlag 0
1786         if {$delayRequest != ""} {
1787             eval $delayRequest
1788         }
1789         return
1790     }
1791     set status [z39.$setNo responseStatus]
1792     if {![string compare [lindex $status 0] NSD]} {
1793         show-status Ready 0 1
1794         set code [lindex $status 1]
1795         set msg [lindex $status 2]
1796         set addinfo [lindex $status 3]
1797 #        tkerror "NSD$code: $msg: $addinfo"
1798         bgerror "NSD$code: $msg: $addinfo"
1799         return
1800     }
1801     if {$no > 0 && $setOffset <= $setMax} {
1802         dputs "present-request from ${setOffset}"
1803         set toGet [expr $setMax - $setOffset + 1]
1804         if {$toGet > $presentChunk} {
1805             set toGet $presentChunk
1806         }
1807         z39.$setNo present $setOffset $toGet
1808     } else {
1809         show-status Ready 0 1
1810     }
1811 }
1812
1813 # Procedure left-cursor {w}
1814 #  w    entry widget
1815 # Tries to move the cursor left in entry window $w
1816 proc left-cursor {w} {
1817     set i [$w index insert]
1818     if {$i > 0} {
1819         incr i -1
1820         $w icursor $i
1821     }
1822     dputs left
1823 }
1824
1825 # Procedure right-cursor {w}
1826 #  w    entry widget
1827 # Tries to move the cursor right in entry window $w
1828 proc right-cursor {w} {
1829     set i [$w index insert]
1830     incr i
1831     dputs right
1832     $w icursor $i
1833 }
1834
1835 # Procedure bind-fields {list returnAction escapeAction}
1836 #  list          list of entry widgets
1837 #  returnAction  return script
1838 #  escapeAction  escape script
1839 # Each widget in list are assigned bindings for <Tab>, <Left>, <Right>,
1840 # <Return> and <Escape>.
1841 proc bind-fields {list returnAction escapeAction} {
1842     set max [expr [llength $list]-1]
1843     for {set i 0} {$i < $max} {incr i} {
1844         bind [lindex $list $i] <Return> $returnAction
1845         bind [lindex $list $i] <Escape> $escapeAction
1846         bind [lindex $list $i] <Tab> [list focus [lindex $list [expr $i+1]]]
1847         bind [lindex $list $i] <Left> [list left-cursor [lindex $list $i]]
1848         bind [lindex $list $i] <Right> [list right-cursor [lindex $list $i]]
1849     }
1850     bind [lindex $list $i] <Return> $returnAction
1851     bind [lindex $list $i] <Escape> $escapeAction
1852     bind [lindex $list $i] <Tab>  [list focus [lindex $list 0]]
1853     bind [lindex $list $i] <Left> [list left-cursor [lindex $list $i]]
1854     bind [lindex $list $i] <Right> [list right-cursor [lindex $list $i]]
1855     focus [lindex $list 0]
1856 }
1857
1858 # Procedure entry-fields {parent list tlist returnAction escapeAction}
1859 #  list          list of frame widgets
1860 #  tlist         list of text to be used as lead of each entry
1861 #  returnAction  return script
1862 #  escapeAction  escape script
1863 # Makes label and entry widgets in each widget in $list.
1864 proc entry-fields {parent list tlist returnAction escapeAction} {
1865     set alist {}
1866     set i 0
1867     foreach field $list {
1868         set label ${parent}.${field}.label
1869         set entry ${parent}.${field}.entry
1870         label $label -text [lindex $tlist $i] -anchor e
1871         entry $entry -width 32 -relief sunken
1872         pack $label -side left
1873         pack $entry -side right
1874         lappend alist $entry
1875         incr i
1876     }
1877     bind-fields $alist $returnAction $escapeAction
1878 }
1879
1880 # Procedure define-target-dialog
1881 # Dialog that asks for new target to be defined.
1882 proc define-target-dialog {} {
1883     set w .target-define
1884
1885     toplevel $w
1886     place-force $w .
1887     top-down-window $w
1888     frame $w.top.target
1889     pack $w.top.target -side top -anchor e -pady 2 
1890     entry-fields $w.top {target} {{Target:}} \
1891         {define-target-action} {destroy .target-define}
1892     top-down-ok-cancel $w {define-target-action} 1
1893 }
1894
1895 # Procedure place-force {window parent}
1896 #  window      new top level widget
1897 #  parent      parent widget used as base
1898 # Sets geometry of $window relative to $parent window.
1899 proc place-force {window parent} {
1900     set g [wm geometry $parent]
1901     set p1 [string first + $g]
1902     set p2 [string last + $g]
1903     set x [expr 40+[string range $g [expr {$p1 + 1}] [expr {$p2 -1}]]]
1904     set y [expr 60+[string range $g [expr {$p2 + 1}] end]]
1905     wm geometry $window +${x}+${y}
1906 }
1907
1908 # Procedure add-database-action {target w}
1909 #  target      target to be defined
1910 #  w           top level widget for the target definition
1911 # Adds the contents of .database-select.top.database.entry to list of
1912 # databases.
1913 proc add-database-action {target w} {
1914     global profile
1915
1916     $w.top.databases.list insert end [.database-select.top.database.entry get]
1917     destroy .database-select
1918 }
1919
1920 # Procedure add-database {target wp}
1921 #  target      target to be defined
1922 #  wp          top level widget for the target definition
1923 # Makes a dialog in which the user enters new database
1924 proc add-database {target wp} {
1925     global profile
1926
1927     set w .database-select
1928     toplevel $w
1929     set oldFocus [focus]
1930     place-force $w $wp
1931     top-down-window $w
1932     frame $w.top.database
1933     pack $w.top.database -side top -anchor e -pady 2
1934     entry-fields $w.top {database} {{Database to add:}} \
1935         [list add-database-action $target $wp] {destroy .database-select}
1936
1937     top-down-ok-cancel $w [list add-database-action $target $wp] 1
1938     focus $oldFocus
1939 }
1940
1941
1942 # Procedure delete-database {target w}
1943 #  target     target to be defined
1944 #  w          top level widget for the target definition
1945 # Asks the user if he/she really wishes to delete a database and removes
1946 # the database from the database-list if requested.
1947 proc delete-database {target w} {
1948     global profile
1949
1950     set l {}
1951     foreach i [$w.top.databases.list curselection] {
1952         set b [$w.top.databases.list get $i]
1953         set l "$l $b"
1954     }
1955     set a [alert "Are you sure you want to remove the database(s)${l}?"]
1956     if {$a} {
1957         foreach i [lsort -decreasing \
1958                 [$w.top.databases.list curselection]] {
1959             $w.top.databases.list delete $i
1960         }
1961     }
1962 }
1963
1964 # Procedure advanced-setup {target b}
1965 #  target     target to be defined
1966 #  b          window number of target top level
1967 # Makes a dialog in which the user may modify/view advanced settings
1968 # of a target definition (profile).
1969 proc advanced-setup {target b} {
1970     global profile profileS
1971
1972     set w .advanced-setup-$b
1973     toplevelG $w
1974     wm title $w "Advanced setup $target"
1975     top-down-window $w
1976     if {![string length $target]} {
1977         set target Default
1978     }
1979     dputs target
1980     
1981     frame $w.top.largeSetLowerBound
1982     frame $w.top.smallSetUpperBound
1983     frame $w.top.mediumSetPresentNumber
1984     frame $w.top.presentChunk
1985     frame $w.top.maximumRecordSize
1986     frame $w.top.preferredMessageSize
1987
1988     pack $w.top.largeSetLowerBound $w.top.smallSetUpperBound \
1989         $w.top.mediumSetPresentNumber $w.top.presentChunk \
1990         $w.top.maximumRecordSize $w.top.preferredMessageSize \
1991         -side top -anchor e -pady 2
1992     
1993     entry-fields $w.top {largeSetLowerBound smallSetUpperBound \
1994         mediumSetPresentNumber presentChunk maximumRecordSize \
1995         preferredMessageSize} \
1996         {{Large Set Lower Bound:} {Small Set Upper Bound:} \
1997         {Medium Set Present Number:} {Present Chunk:} \
1998         {Maximum Record Size:} {Preferred Message Size:}} \
1999         [list advanced-setup-action $target $b] [list destroy $w]
2000
2001     $w.top.largeSetLowerBound.entry configure -textvariable \
2002     profileS($target,largeSetLowerBound)
2003     $w.top.smallSetUpperBound.entry configure -textvariable \
2004     profileS($target,smallSetUpperBound)
2005     $w.top.mediumSetPresentNumber.entry configure -textvariable \
2006     profileS($target,mediumSetPresentNumber)
2007     $w.top.presentChunk.entry configure -textvariable \
2008     profileS($target,presentChunk)
2009     $w.top.maximumRecordSize.entry configure -textvariable \
2010     profileS($target,maximumRecordSize)
2011     $w.top.preferredMessageSize.entry configure -textvariable \
2012     profileS($target,preferredMessageSize)
2013     
2014     bottom-buttons $w [list {Ok} [list advanced-setup-action $target $b] \
2015             {Cancel} [list destroy $w]] 0   
2016 }
2017
2018 # Procedure advanced-setup-action {target b}
2019 #  target     target to be defined
2020 #  b          window number of target top level
2021 # This procedure is called when the user hits Ok in the advanced target
2022 # setup dialog. The temporary result is stored in the $profileS - array.
2023 proc advanced-setup-action {target b} {
2024     set w .advanced-setup-$b
2025     global profileS
2026     
2027     set profileS($target,LSLB) [$w.top.largeSetLowerBound.entry get]
2028     set profileS($target,SSUB) [$w.top.smallSetUpperBound.entry get]
2029     set profileS($target,MSPN) [$w.top.mediumSetPresentNumber.entry get]
2030     set profileS($target,presentChunk) [$w.top.presentChunk.entry get]
2031     set profileS($target,MRS) [$w.top.maximumRecordSize.entry get]
2032     set profileS($target,PMS) [$w.top.preferredMessageSize.entry get]
2033
2034     dputs "advanced-setup-action"
2035     destroy $w
2036 }
2037
2038 # Procedure database-select-action
2039 # Called when the user commits a database select change. See procedure
2040 # database-select.
2041 proc database-select-action {} {
2042     set w .database-select.top
2043     set b {}
2044     foreach indx [$w.databases.list curselection] {
2045         lappend b [$w.databases.list get $indx]
2046     }
2047     if {$b != ""} {
2048         z39 databaseNames $b
2049     }
2050     destroy .database-select
2051 }
2052
2053 # Procedure database-select
2054 # Makes a dialog in which the user may select a database
2055 proc database-select {} {
2056     set w .database-select
2057     global profile hostid
2058
2059     toplevel $w
2060     set oldFocus [focus]
2061     place-force $w .
2062     top-down-window $w
2063
2064     frame $w.top.databases -relief ridge -border 2
2065     pack $w.top.databases -side left -pady 6 -padx 6 -expand yes -fill x
2066
2067     label $w.top.databases.label -text "List"
2068     listbox $w.top.databases.list -width 20 -height 6 \
2069         -yscrollcommand "$w.top.databases.scroll set"
2070     scrollbar $w.top.databases.scroll -orient vertical -border 1
2071     pack $w.top.databases.label -side top -fill x -padx 2 -pady 2
2072     pack $w.top.databases.list -side left -fill both -expand yes -padx 2 -pady 2
2073     pack $w.top.databases.scroll -side right -fill y -padx 2 -pady 2
2074     $w.top.databases.scroll config -command "$w.top.databases.list yview"
2075
2076     foreach b $profile($hostid,databases) {
2077         $w.top.databases.list insert end $b
2078     }
2079     top-down-ok-cancel $w {database-select-action} 1
2080     focus $oldFocus
2081 }
2082
2083 # Procedure cascase-dblist-select
2084 proc cascade-dblist-select {target db} {
2085     show-target $target $db
2086     z39 databaseNames $db
2087     ready-response-actions $target $db
2088 }
2089
2090 # Procedure cascade-dblist 
2091 # Makes the Service/database list with proper databases for the target
2092 proc cascade-dblist {target base} {
2093     global profile
2094
2095     set w .top.service.m.dblist
2096 #    $w delete 0 200
2097     $w delete 0 end
2098     if {[info exists profile($target,databases)]} {
2099         foreach db $profile($target,databases) {
2100             $w add command -label $db \
2101             -command [list cascade-dblist-select $target $db]
2102         }
2103     }
2104 }
2105
2106 # Procedure cascade-target-list
2107 # Makes all target/databases available in the Target|Connect
2108 # menu as well as all targets in the Target|Setup menu.
2109 # This procedure is called whenever target definitions occur.
2110 proc cascade-target-list {} {
2111     global profile
2112     
2113     foreach sub [winfo children .top.target.m.clist] {
2114         destroy $sub
2115     }
2116     .top.target.m.clist delete 0 last
2117     foreach nn [lsort [array names profile *,host]] {
2118         if {[string length $profile($nn)]} {
2119             set ll [expr {[string length $nn] - 6}]
2120             set n [string range $nn 0 $ll]
2121             
2122             set nl $profile($n,windowNumber)
2123             if {[info exists profile($n,databases)]} {
2124                 set ndb [llength $profile($n,databases)]
2125             } else {
2126                 set ndb 0
2127             }
2128             if {$ndb > 1} {
2129                 .top.target.m.clist add cascade -label $n \
2130                     -menu .top.target.m.clist.$nl
2131                 irmenu .top.target.m.clist.$nl
2132                 foreach b $profile($n,databases) {
2133                     .top.target.m.clist.$nl add command -label $b \
2134                     -command [list reopen-target $n $b]
2135                 }
2136             } elseif {$ndb == 1} {
2137                 .top.target.m.clist add command -label $n -command \
2138                     [list reopen-target $n [lindex $profile($n,databases) 0]]
2139             } else {
2140                 .top.target.m.clist add command -label $n -command \
2141                     [list reopen-target $n {}]
2142             }
2143         }
2144     }
2145     .top.target.m.slist delete 0 last
2146     foreach nn [lsort [array names profile *,host]] {
2147         set ll [expr {[string length $nn] - 6}]
2148         set n [string range $nn 0 $ll]
2149         .top.target.m.slist add command -label $n -command [list protocol-setup $n]
2150     }
2151 }
2152
2153 # Procedure query-select {i}
2154 #  i       Query type number (integer)
2155 # This procedure is called when the user selects a Query type. The current
2156 # query type information given by the globals $queryButtonsFind and
2157 # $queryInfoFind are changed by this operation.
2158 proc query-select {i} {
2159     global queryButtonsFind queryInfoFind  queryTypes queryAuto queryAutoOld \
2160         hostid currentDb profile attributeTypeSelected
2161     global queryButtons$attributeTypeSelected queryInfo$attributeTypeSelected
2162     foreach n $queryTypes {
2163         global query$n
2164         set query$n 0
2165     }
2166     set query[lindex $queryTypes $i] 1
2167     if {$queryAutoOld && !$queryAuto} {
2168         set queryAutoOld $queryAuto
2169     }
2170     if {!$queryAutoOld && $queryAuto && ![info exists profile($hostid,\
2171         AttributeDetails,$currentDb,[lindex $queryTypes $i])]} {
2172         set queryAutoOld $queryAuto
2173     }
2174     set queryInfoFind [lindex [set queryInfo$attributeTypeSelected] $i]
2175     set queryButtonsFind [lindex [set queryButtons$attributeTypeSelected] $i]
2176     index-lines .lines 1 $queryButtonsFind $queryInfoFind activate-index
2177 }
2178
2179 # Procedure query-new-action 
2180 # Commits a new query type definition by extending the globals
2181 # $queryTypes, $queryButtons and $queryInfo.
2182 proc query-new-action {} {
2183     global queryTypes settingsChanged attributeTypeSelected
2184     global queryButtons$attributeTypeSelected queryInfo$attributeTypeSelected
2185     set settingsChanged 1
2186     lappend queryTypes [.query-new.top.index.entry get]
2187     lappend queryButtons$attributeTypeSelected {}
2188     lappend queryInfo$attributeTypeSelected {}
2189
2190     destroy .query-new
2191     cascade-query-list
2192 }
2193
2194 # Procedure query-new
2195 # Makes a dialog in which the user is requested to enter the name of a
2196 # new query type.
2197 proc query-new {} {
2198     set w .query-new
2199
2200     toplevel $w
2201     set oldFocus [focus]
2202     place-force $w .
2203     top-down-window $w
2204     frame $w.top.index
2205     pack $w.top.index -side top -anchor e -pady 2 
2206     entry-fields $w.top index {{Query Name:}} \
2207             query-new-action {destroy .query-new}
2208     top-down-ok-cancel $w query-new-action 1
2209     focus $oldFocus
2210 }
2211
2212 # Procedure query-delete-action {queryNo}
2213 #  queryNo     query type number (integer)
2214 # Procedure that deletes the query type specified by $queryNo.
2215 proc query-delete-action {queryNo} {
2216     global queryTypes settingsChanged attributeTypeSelected
2217     global queryInfo$attributeTypeSelected queryButtons$attributeTypeSelected
2218
2219     set settingsChanged 1
2220
2221     set queryTypes [lreplace $queryTypes $queryNo $queryNo]
2222     set queryButtons$attributeTypeSelected [lreplace [set queryButtons$attributeTypeSelected] \
2223         $queryNo $queryNo]
2224     set queryInfo$attributeTypeSelected [lreplace [set queryInfo$attributeTypeSelected] \
2225         $queryNo $queryNo]
2226     destroy .query-delete
2227     cascade-query-list
2228 }
2229
2230 # Procedure query-delete {queryNo}
2231 #  queryNo     query type number (integer)
2232 # Asks if the user really want to delete a given query type; calls
2233 # query-delete-action if 'yes'.
2234 proc query-delete {queryNo} {
2235     global queryTypes
2236
2237     set w .query-delete
2238
2239     toplevel $w
2240     place-force $w .
2241     top-down-window $w
2242     set n [lindex $queryTypes $queryNo]
2243
2244     label $w.top.warning -bitmap warning
2245     message $w.top.quest -text "Are you sure you want to delete the \
2246         query type $n ?"  -aspect 300
2247     pack $w.top.warning $w.top.quest -side left -expand yes -padx 10 -pady 5
2248     bottom-buttons $w [list {Ok} [list query-delete-action $queryNo] \
2249         {Cancel} [list destroy $w]] 1
2250 }
2251
2252 # Procedure cascade-query-list
2253 # Updates the entries below Options|Query to list all query types.
2254 proc cascade-query-list {} {
2255     global queryTypes hostid attributeTypes queryAuto
2256     set w .top.options.m.query
2257     set i 0
2258     $w.clist delete 0 last
2259     foreach n $queryTypes {
2260         $w.clist add check -label $n -variable query$n -command [list query-select $i]
2261         global query$n
2262         incr i
2263     }
2264     set i 0
2265     $w.slist delete 0 last
2266     foreach n $queryTypes {
2267         if {$n == "Auto"} {
2268             if {$hostid == "Default"} {
2269                 $w.slist add command -label $n -state disabled \
2270                     -command [list query-setup $i]
2271             } else {
2272                 $w.slist add command -label $n -command [list query-setup $i]
2273             }
2274         } else {
2275             $w.slist add command -label $n -command [list query-setup $i]
2276         }
2277         incr i
2278     }
2279     set i 0
2280     $w.tlist delete 0 last
2281     foreach n $attributeTypes {
2282         global attribute$n
2283         $w.tlist add check -label $n -variable attribute$n \
2284             -command [list attribute-select $i]
2285         incr i
2286     }
2287     set i 0
2288     $w.dlist delete 0 last
2289     foreach n $queryTypes {
2290         if {$n == "Auto"} {
2291             $w.dlist add command -label $n -state disabled \
2292                 -command [list query-setup $i]
2293         } else {
2294             $w.dlist add command -label $n -command [list query-delete $i]
2295         }
2296         incr i
2297     }
2298 }
2299
2300 # Procedure save-geometry
2301 # This procedure saves the per-user related settings in ~/.clientrc.tcl.
2302 # The geometry information stored in the global array $windowGeometry is
2303 # saved. Also a few other user settings, such as current display format, are
2304 # saved.
2305 proc save-geometry {} {
2306     global windowGeometry hotTargets textWrap displayFormat popupMarcdf \
2307         recordSyntax elementSetNames hostid
2308
2309     set windowGeometry(.) [wm geometry .]
2310
2311     if {[catch {set f [open ~/.clientrc.tcl w]}]} {
2312         return
2313     } 
2314     if {$hostid != "Default"} {
2315         puts $f "set hostid [list $hostid]"
2316         set b [z39 databaseNames]
2317         puts $f "set hostbase [list $b]"
2318     }
2319     puts $f "set hotTargets [list $hotTargets]"
2320     puts $f "set textWrap $textWrap"
2321     puts $f "set displayFormat $displayFormat"
2322     puts $f "set popupMarcdf $popupMarcdf"
2323     puts $f "set recordSyntax $recordSyntax"
2324     puts $f "set elementSetNames $elementSetNames"
2325     foreach n [array names windowGeometry] {
2326         puts -nonewline $f "set [list windowGeometry($n)] "
2327         puts $f [list $windowGeometry($n)]
2328     }
2329     close $f
2330 }
2331
2332 # Procedure save-settings
2333 # This procedure saves the per-host related settings irtdb.tcl which
2334 # is normally kept in the directory /usr/local/lib/irtcl.
2335 # All query types and target defintion profiles are saved.
2336 proc save-settings {} {
2337     global profile libdir settingsChanged queryTypes queryAuto \
2338         attributeTypes attributeTypeSelected
2339     if {[file writable [file join $libdir irtdb.tcl]]} {
2340         set f [open [file join $libdir irtdb.tcl] w]
2341     } else {
2342         set f [open "irtdb.tcl" w]
2343     }
2344     puts $f "# Setup file"
2345     foreach n [lsort [array names profile]] {
2346         puts $f "set [list profile($n)] [list $profile($n)]"
2347     }
2348     puts $f "set attributeTypes [list $attributeTypes]"
2349     puts $f "set attributeTypeSelected [list $attributeTypeSelected]"
2350     puts $f "set queryTypes [list $queryTypes]"
2351     foreach attrtype $attributeTypes {
2352         global queryButtons$attrtype queryInfo$attrtype
2353         catch {puts $f "set queryButtons$attrtype [list [set queryButtons$attrtype]]"}
2354         catch {puts $f "set queryInfo$attrtype [list [set queryInfo$attrtype]]"}
2355     }
2356     puts $f "set queryAuto [list $queryAuto]"
2357     close $f
2358     set settingsChanged 0
2359 }
2360
2361 # Procedure alert {ask}
2362 #  ask    prompt string
2363 # Makes a grabbed dialog in which the user is requested to answer
2364 # "Ok" or "Cancel". This procedure returns 1 if the user hits "Ok"; 0
2365 # otherwise.
2366 proc alert {ask} {
2367     set w .alert
2368
2369     global alertAnswer font
2370
2371     toplevel $w
2372     set oldFocus [focus]
2373     place-force $w .
2374     top-down-window $w
2375
2376     label $w.top.warning -bitmap warning
2377     message $w.top.message -text $ask -aspect 300 -font $font(b,normal)
2378     pack $w.top.warning $w.top.message -side left -pady 5 -padx 10 -expand yes
2379   
2380     set alertAnswer 0
2381     top-down-ok-cancel $w {alert-action} 1
2382     focus $oldFocus
2383     return $alertAnswer
2384 }
2385
2386 # Procedure alert-action
2387 # Called when the user hits "Ok" in the .alert-window.
2388 proc alert-action {} {
2389     global alertAnswer
2390     set alertAnswer 1
2391     destroy .alert
2392 }
2393
2394 # Procedure exit-action
2395 # This procedure is called if the user exists the application
2396 proc exit-action {} {
2397     global settingsChanged
2398
2399     if {$settingsChanged} {
2400         save-settings
2401     }
2402     save-geometry
2403     exit 0
2404 }
2405
2406 # Procedure listbuttonaction {w name h user i}
2407 #  w       menubutton widget
2408 #  name    name information
2409 #  h       handler to be invoked
2410 #  user    user information to be passed to handler $h
2411 #  i       index passed as second argument to handler $h
2412 # Utility function to emulate a listbutton. Called when the user
2413 # Modifies the listbutton. See procedure listbuttonx.
2414 proc listbuttonaction {w name h user i} {
2415     $w configure -text [lindex $name 0]
2416     $h [lindex $name 1] $user $i
2417     if {[regexp {.lines.[ ]*([0-9]+).*} $w match j]} {
2418         global attributeTypeSelected queryTypes hostid currentDb profile
2419         global queryButtons$attributeTypeSelected
2420         set n -1
2421         foreach type $queryTypes {
2422             global query$type
2423             if {[set query$type] == 1} {
2424                 set n [lsearch $queryTypes $type]
2425             }
2426         }
2427         if {$n == -1} {
2428             return
2429         }
2430         set list [lindex [set queryButtons$attributeTypeSelected] $n]
2431         set length [llength $list]
2432         if {$j < $length} {
2433 #            set new [lreplace [lindex [set queryButtons$attributeTypeSelected] $n] $j $j [list I $i]]
2434             set new [lreplace $list $j $j [list I $i]]
2435         } else {
2436             set new [lappend $list [list I $i]]
2437         }
2438         set queryButtons$attributeTypeSelected \
2439             [lreplace [set queryButtons$attributeTypeSelected] $n $n $new]
2440         set profile($hostid,queryButtons,$currentDb) $new
2441         
2442     }
2443 #    debug-window "[lindex $name 0], [lindex $name 1], i er her $i, winduesnavnet er $w, n er $n"
2444 #    debug-window "new er $new"
2445 }
2446
2447 # Procedure listbuttonx {button no names handle user}
2448 #  button  menubutton widget
2449 #  no      initial value index (integer)
2450 #  names   list of name entries. The first entry in each name
2451 #          entry is the actual name
2452 #  handle  user function to be called when the listbutton changes
2453 #          its value
2454 #  user    user argument to the $handle function
2455 # Makes an extended listbutton.
2456 proc listbuttonx {button no names handle user} {
2457     set width 10
2458     foreach name $names {
2459         set buttonName [lindex $name 0]
2460         if {[string length $buttonName] > $width} {
2461             set width [string length $buttonName]
2462         }
2463     } 
2464     if {[winfo exists $button]} {
2465         $button configure -width $width -text [lindex [lindex $names $no] 0]
2466         ${button}.m delete 0 last
2467     } else {
2468         menubutton $button -text [lindex [lindex $names $no] 0] \
2469             -width $width -menu ${button}.m -relief raised -border 1
2470         irmenu ${button}.m
2471         ${button}.m configure -tearoff off
2472     }
2473     set i 0
2474     foreach name $names {
2475         ${button}.m add command -label [lindex $name 0] \
2476             -command [list listbuttonaction ${button} $name $handle $user $i]
2477         incr i
2478     }
2479 }
2480
2481 # Procedure listbutton {button no names}
2482 #  button  menubutton widget
2483 #  no      initial value index (integer)
2484 #  names   list of possible values.
2485 # Makes a listbutton. The functionality is emulated by the use menubutton-
2486 # and menu widgets.
2487 proc listbutton {button no names} {
2488     menubutton $button -text [lindex $names $no] -width 10 -menu ${button}.m \
2489         -relief raised -border 1
2490     irmenu ${button}.m
2491     ${button}.m configure -tearoff off
2492     foreach name $names {
2493         ${button}.m add command -label $name \
2494                 -command [list ${button} configure -text $name]
2495     }
2496 }
2497
2498 # Procedure listbuttonv-action {button var names i}
2499 #  button   menubutton widget
2500 #  var      global variable to be affected
2501 #  names    list of possible names and values
2502 # This procedure is called when the user alters a menu created by the
2503 # listbuttonv procedure. The global variable $var is updated.
2504 proc listbuttonv-action {button var names i} {
2505     global $var
2506
2507     set $var [lindex $names [expr {$i+1}]]
2508     $button configure -text [lindex $names $i]
2509 }
2510
2511 # Procedure listbuttonv {button var names}
2512 #  button   menubutton widget
2513 #  var      global variable to be affected
2514 #  names    List of name/value pairs, i.e. {n1 v1 n2 v2 ...}.
2515 # This procedure emulates a listbutton by means of menu/menubutton widgets.
2516 # The global variable $var is automatically updated and set to one of the
2517 # values v1, v2, ...
2518 proc listbuttonv {button var names} {
2519     global $var
2520
2521     set n "-"
2522     set val [set $var]
2523     set l [llength $names]
2524     for {set i 1} {$i < $l} {incr i 2} {
2525         if {$val == [lindex $names $i]} {
2526             incr i -1
2527             set n [lindex $names $i]
2528             break
2529         }
2530     }
2531     if {[winfo exists $button]} {
2532         $button configure -text $n
2533         return
2534     }
2535     menubutton $button -text $n -menu ${button}.m -relief raised -border 1
2536     irmenu ${button}.m
2537     ${button}.m configure -tearoff off
2538     for {set i 0} {$i < $l} {incr i 2} {
2539         ${button}.m add command -label [lindex $names $i] \
2540                 -command [list listbuttonv-action $button $var $names $i]
2541     }
2542 }
2543
2544 # Procedure query-add-index-action {queryNo}
2545 #  queryNo       query type number (integer)
2546 # Handler that makes a new query index.
2547 proc query-add-index-action {queryNo} {
2548     set w .query-setup
2549
2550     global queryInfoTmp queryButtonsTmp
2551
2552     set newI [.query-add-index.top.index.entry get]
2553     lappend queryInfoTmp [list $newI {}]
2554     $w.top.index.list insert end $newI
2555     destroy .query-add-index
2556     index-lines $w.top.lines 0 $queryButtonsTmp $queryInfoTmp activate-e-index
2557 }
2558
2559 # Procedure query-add-line
2560 #  queryNo      query type number (integer)
2561 # Handler that adds new query line.
2562 proc query-add-line {queryNo} {
2563     global queryInfoTmp queryButtonsTmp
2564     
2565     set w .query-setup
2566
2567     lappend queryButtonsTmp {I 0}
2568     
2569     set height [expr [winfo height $w] + 100]
2570 #    set windowGeometry($w) ${height}x[winfo width $w]+0+0
2571     $w configure -height $height -width [winfo width $w]
2572
2573     index-lines $w.top.lines 0 $queryButtonsTmp $queryInfoTmp activate-e-index
2574 }
2575
2576 # Procedure query-del-line
2577 #  queryNo      query type number (integer)
2578 # Handler that removes query line.
2579 proc query-del-line {queryNo} {
2580     set w .query-setup
2581
2582     global queryInfoTmp queryButtonsTmp
2583
2584     set l [llength $queryButtonsTmp]
2585     if {$l <= 0} {
2586         return
2587     }
2588     incr l -1
2589     set queryButtonsTmp [lreplace $queryButtonsTmp $l $l]
2590     index-lines $w.top.lines 0 $queryButtonsTmp $queryInfoTmp activate-e-index
2591 }
2592
2593 # Procedure query-add-index
2594 #  queryNo      query type number (integer)
2595 # Handler that adds new query index.
2596 proc query-add-index {queryNo} {
2597     set w .query-add-index
2598
2599     toplevel $w
2600     set oldFocus [focus]
2601     place-force $w .query-setup
2602     top-down-window $w
2603     frame $w.top.index
2604     pack $w.top.index -side top -anchor e -pady 2 
2605     entry-fields $w.top {index} {{Index Name:}} \
2606             [list query-add-index-action $queryNo] [list destroy $w]
2607     top-down-ok-cancel $w [list query-add-index-action $queryNo] 1
2608     focus $oldFocus
2609 }
2610
2611 # Procedure query-setup-action
2612 #  queryNo      query type number (integer)
2613 # Handler that updates the query information database stored in the
2614 # globals $queryInfo and $queryButtons. This procedure is executed when
2615 # the user commits the query setup changes by pressing button "Ok".
2616 proc query-setup-action {queryNo} {
2617     global queryButtonsTmp queryInfoTmp queryButtonsFind \
2618         queryInfoFind settingsChanged hostid currentDb profile attributeTypeSelected
2619     global queryInfo$attributeTypeSelected queryButtons$attributeTypeSelected
2620     set settingsChanged 1
2621     set queryInfo$attributeTypeSelected [lreplace [set queryInfo$attributeTypeSelected] \
2622         $queryNo $queryNo $queryInfoTmp]
2623     set queryButtons$attributeTypeSelected [lreplace \
2624         [set queryButtons$attributeTypeSelected] $queryNo $queryNo $queryButtonsTmp]
2625     if {[info exists profile($hostid,AttributeDetails,$currentDb,Bib1)]} {
2626         set profile($hostid,queryButtons,$currentDb) $queryButtonsTmp
2627     }
2628     set queryInfoFind $queryInfoTmp
2629     set queryButtonsFind $queryButtonsTmp
2630     destroy .query-setup
2631     index-lines .lines 1 $queryButtonsFind $queryInfoFind activate-index
2632 }
2633
2634 #This procedure handles selection of what attribute set the user wants to use for searching.
2635 #queryNo    index in the attributeTypes list (also the menu item number in Query|Type).
2636 proc attribute-select {queryNo} {
2637     global attributeTypes attributeTypeSelected
2638     set attributeTypeSelected [lindex $attributeTypes $queryNo]
2639     foreach type $attributeTypes {
2640         global attribute[set type]
2641         set attribute$type 0
2642     }
2643     set attribute$attributeTypeSelected 1
2644 }
2645
2646 #proc changeQueryButtons {target base}
2647 #target        target name
2648 #base        database name
2649 #Substitutes the third element (the Auto element) in queryButtons with 
2650 #profile(target,queryButtons,base). The third element in queryInfo is also substituted with
2651 #profile(target,AttributeDetails,base,attributeTypeSelected)
2652 proc changeQueryButtons {target base} {
2653     global profile queryInfo attributeTypeSelected queryTypes
2654     global queryButtons$attributeTypeSelected
2655     set n [lsearch $queryTypes Auto]
2656     if {[info exists profile($target,queryButtons,$base)]} {
2657         set queryButtons$attributeTypeSelected [lreplace [set \
2658             queryButtons$attributeTypeSelected] $n $n $profile($target,queryButtons,$base)]
2659         change-queryInfo $target $base
2660     }
2661 }
2662
2663 # Procedure activate-e-index {value no i}
2664 #   value   menu name
2665 #   no      query index number
2666 #   i       menu index (integer)
2667 # Procedure called when listbutton is activated in the query type edit
2668 # window. The global $queryButtonsTmp is updated in this operation.
2669 proc activate-e-index {value no i} {
2670     global queryButtonsTmp queryIndexTmp
2671     set queryButtonsTmp [lreplace $queryButtonsTmp $no $no [list I $i]]
2672     dputs $queryButtonsTmp
2673     set queryIndexTmp $i
2674 }
2675
2676 # Procedure activate-index {value no i}
2677 #   value   menu name
2678 #   no      query index number
2679 #   i       menu index (integer)
2680 # Procedure called when listbutton is activated in the main query 
2681 # window. The global $queryButtonsFind is updated in this operation.
2682 proc activate-index {value no i} {
2683     global queryButtonsFind
2684
2685     set queryButtonsFind [lreplace $queryButtonsFind $no $no [list I $i]]
2686     dputs "queryButtonsFind $queryButtonsFind"
2687 }
2688
2689 # Procedure update-attr
2690 # This procedure creates listbuttons for all bib-1 attributes except
2691 # the use-attribute in the .index-setup window.
2692 # The globals $relationTmpValue, $positionTmpValue, $structureTmpValue,
2693 # $truncationTmpValue and $completenessTmpValue are maintainted by the
2694 # listbuttons.
2695 proc update-attr {} {
2696     set w .index-setup
2697     listbuttonv $w.top.relation.b relationTmpValue\
2698         {{None} 0 {Less than} 1 {Greater than or equal} 2 {Equal} 3 \
2699         {Greater than or equal} 4 {Greater than} 5 {Not equal} 6 \
2700         {Phonetic} 100 {Stem} 101 {Relevance} 102 {AlwaysMatches} 103}
2701     listbuttonv $w.top.position.b positionTmpValue {{None} 0 \
2702         {First in field} 1 {First in subfield} 2 {Any position in field} 3}
2703     listbuttonv $w.top.structure.b structureTmpValue {{None} 0 {Phrase} 1 \
2704         {Word} 2 {Key} 3 {Year} 4 {Date (norm)} 5 {Word list}  6 \
2705         {Date (un-norm)} 100 {Name (norm)} 101 {Date (un-norm)} 102 \
2706         {Structure} 103 {urx} 104 {free-form} 105 {doc-text} 106 \
2707         {local-number} 107 {string} 108 {numeric string} 109}
2708     listbuttonv $w.top.truncation.b truncationTmpValue {{Auto} 0 {Right} 1 \
2709         {Left} 2 {Left and right} 3 {No truncation} 100 \
2710         {Process #} 101 {Re-1} 102 {Re-2} 103}
2711     listbuttonv $w.top.completeness.b completenessTmpValue {{None} 0 \
2712         {Incomplete subfield} 1 {Complete subfield} 2 {Complete field} 3}
2713 }
2714
2715 # Procedure use-attr {init}
2716 #  init      init flag
2717 # This procedure creates a listbox with several Bib-1 use attributes.
2718 # If $init is 1 the listbox is created with the attributes. If $init
2719 # is 0 the current selection of the listbox is read and the global
2720 # $useTmpValue is set to the current use-value.
2721 proc use-attr {init} {
2722     global useTmpValue attributeTypeSelected
2723     set ats [string tolower $attributeTypeSelected]
2724     source ${ats}.tcl
2725     
2726     set w .index-setup
2727
2728     if {$init} {
2729         set s 0
2730         set lno 0
2731         foreach i [lsort -integer [array names $ats]] {
2732             $w.top.use.list insert end "[set ${ats}($i)]"
2733             if {$useTmpValue == $i} {
2734                 set s $lno
2735             }
2736             incr lno
2737         } 
2738         $w.top.use.list selection clear 0 end
2739         $w.top.use.list selection set $s $s
2740 #        incr s -3
2741 #        if {$s < 0} 
2742 #            set s 0
2743 #        
2744         $w.top.use.list yview $s
2745     } else {
2746         set j [lindex [$w.top.use.list curselection] 0]
2747         set i [lindex [lsort -integer [array names ${ats}]] $j]
2748 #        debug-window "[$w.top.use.list curselection] [set ${ats}($i)]"
2749 #        set useTmpValue [set ${ats}($i)]
2750         set useTmpValue $i
2751         dputs "useTmpValue=$useTmpValue"
2752     }
2753 }
2754
2755 # Procedure index-setup-action {oldAttr queryNo indexNo}
2756 #  oldAttr     original attributes (?)
2757 #  queryNo     query number
2758 #  indexNo     index number
2759 # Commits setup of a query index. The mapping from the index to 
2760 # the Bib-1 attributes are handled by this function.
2761 proc index-setup-action {oldAttr queryNo indexNo} {
2762     set attr [lindex $oldAttr 0]
2763
2764     global useTmpValue relationTmpValue structureTmpValue truncationTmpValue \
2765         completenessTmpValue positionTmpValue queryInfoTmp
2766
2767     use-attr 0
2768
2769     dputs "index-setup-action"
2770     dputs "queryNo $queryNo"
2771     dputs "indexNo $indexNo"
2772     if {$useTmpValue > 0} {
2773         lappend attr "1=$useTmpValue"
2774     }
2775     if {$relationTmpValue > 0} {
2776         lappend attr "2=$relationTmpValue"
2777     }
2778     if {$positionTmpValue > 0} {
2779         lappend attr "3=$positionTmpValue"
2780     }
2781     if {$structureTmpValue > 0} {
2782         lappend attr "4=$structureTmpValue"
2783     }
2784     if {$truncationTmpValue > 0} {
2785         lappend attr "5=$truncationTmpValue"
2786     }
2787     if {$completenessTmpValue > 0} {
2788         lappend attr "6=$completenessTmpValue"
2789     }
2790     dputs "new attr $attr"
2791     set queryInfoTmp [lreplace $queryInfoTmp $indexNo $indexNo $attr]
2792     destroy .index-setup
2793 }
2794
2795 # Procedure index-setup {attr queryNo indexNo}
2796 #  attr        original attributes
2797 #  queryNo     query number
2798 #  indexNo     index number
2799 # Makes a window with settings of a given query index which the user
2800 # may inspect/modify.
2801 proc index-setup {attr queryNo indexNo} {
2802     set w .index-setup
2803
2804     global relationTmpValue structureTmpValue truncationTmpValue \
2805         completenessTmpValue positionTmpValue useTmpValue attributeTypeSelected
2806     set relationTmpValue 0
2807     set truncationTmpValue 0
2808     set structureTmpValue 0
2809     set positionTmpValue 0
2810     set completenessTmpValue 0
2811     set useTmpValue 0
2812
2813     catch {destroy $w}
2814     toplevelG $w
2815
2816     set n [lindex $attr 0]
2817     wm title $w "Index setup: $n, $attributeTypeSelected"
2818
2819     top-down-window $w
2820
2821     set len [llength $attr]
2822     for {set i 1} {$i < $len} {incr i} {
2823         set q [lindex $attr $i]
2824         set l [string first = $q]
2825         if {$l > 0} {
2826             set t [string range $q 0 [expr {$l - 1}]]
2827             set v [string range $q [expr {$l + 1}] end]
2828             switch $t {
2829                 1
2830                 { set useTmpValue $v }
2831                 2
2832                 { set relationTmpValue $v }
2833                 3
2834                 { set positionTmpValue $v }
2835                 4
2836                 { set structureTmpValue $v }
2837                 5
2838                 { set truncationTmpValue $v }
2839                 6
2840                 { set completenessTmpValue $v }
2841             }
2842         }
2843     }
2844
2845     frame $w.top.use -relief ridge -border 2
2846     frame $w.top.relation -relief ridge -border 2
2847     frame $w.top.position -relief ridge -border 2
2848     frame $w.top.structure -relief ridge -border 2
2849     frame $w.top.truncation -relief ridge -border 2
2850     frame $w.top.completeness -relief ridge -border 2
2851
2852     update-attr
2853
2854     # Use Attributes
2855
2856     pack $w.top.use -side left -pady 6 -padx 6 -fill y
2857
2858     label $w.top.use.label -text "Use"
2859     listbox $w.top.use.list -width 26 -yscrollcommand "$w.top.use.scroll set"
2860     scrollbar $w.top.use.scroll -orient vertical -border 1
2861     pack $w.top.use.label -side top -fill x -padx 2 -pady 2
2862     pack $w.top.use.list -side left -fill both -expand yes -padx 2 -pady 2
2863     pack $w.top.use.scroll -side right -fill y -padx 2 -pady 2
2864     $w.top.use.scroll config -command "$w.top.use.list yview"
2865
2866     use-attr 1
2867
2868     # Relation Attributes
2869
2870     pack $w.top.relation -pady 6 -padx 6 -side top
2871     label $w.top.relation.label -text "Relation" -width 18
2872     
2873     pack $w.top.relation.label $w.top.relation.b -fill x 
2874
2875     # Position Attributes
2876
2877     pack $w.top.position -pady 6 -padx 6 -side top
2878     label $w.top.position.label -text "Position" -width 18
2879
2880     pack $w.top.position.label $w.top.position.b -fill x
2881
2882     # Structure Attributes
2883
2884     pack $w.top.structure -pady 6 -padx 6 -side top
2885     label $w.top.structure.label -text "Structure" -width 18
2886
2887     pack $w.top.structure.label $w.top.structure.b -fill x
2888
2889     # Truncation Attributes
2890
2891     pack $w.top.truncation -pady 6 -padx 6 -side top
2892     label $w.top.truncation.label -text "Truncation" -width 18
2893
2894     pack $w.top.truncation.label $w.top.truncation.b -fill x
2895
2896     # Completeness Attributes
2897
2898     pack $w.top.completeness -pady 6 -padx 6 -side top
2899     label $w.top.completeness.label -text "Completeness" -width 18
2900
2901     pack $w.top.completeness.label $w.top.completeness.b -fill x
2902
2903     # Ok-cancel
2904     bottom-buttons $w [list {Ok} \
2905         [list index-setup-action $attr $queryNo $indexNo] {Cancel} [list destroy $w]] 0
2906     
2907     focus $w
2908 }
2909
2910 # Procedure query-edit-index {queryNo}
2911 #  queryNo     query number
2912 # Determines if a selection of an index is active. If one is selected
2913 # the index-setup dialog is started.
2914 proc query-edit-index {queryNo} {
2915     global queryInfoTmp
2916     set w .query-setup
2917
2918     set i [lindex [$w.top.index.list curselection] 0]
2919     if {![string length $i]} {
2920         return
2921     }
2922     set attr [lindex $queryInfoTmp $i]
2923     dputs "Editing no $i $attr"
2924     index-setup $attr $queryNo $i
2925 }
2926
2927 # Procedure query-delete-index {queryNo}
2928 #  queryNo     query number
2929 # Determines if a selection of an index is active. If one is selected
2930 # the index is deleted.
2931 proc query-delete-index {queryNo} {
2932     global queryInfoTmp queryButtonsTmp
2933     set w .query-setup
2934
2935     set i [lindex [$w.top.index.list curselection] 0]
2936     if {![string length $i]} {
2937         return
2938     }
2939     set queryInfoTmp [lreplace $queryInfoTmp $i $i]
2940     index-lines $w.top.lines 0 $queryButtonsTmp $queryInfoTmp activate-e-index
2941     $w.top.index.list delete $i
2942 }
2943     
2944 # Procedure query-setup {queryNo}
2945 #  queryNo     query number
2946 # Makes a dialog in which a query type can be customized.
2947 proc query-setup {queryNo} {
2948     global queryTypes queryButtonsTmp queryInfoTmp queryIndexTmp attributeTypeSelected
2949     global queryInfo$attributeTypeSelected queryButtons$attributeTypeSelected
2950     set w .query-setup
2951
2952     set queryIndexTmp 0
2953     set queryName [lindex $queryTypes $queryNo]
2954     if {[info exists queryInfo$attributeTypeSelected]} {
2955         set queryInfoTmp [lindex [set queryInfo$attributeTypeSelected] $queryNo]
2956     } else {
2957         set queryInfoTmp [lindex $queryInfoBib1 $queryNo]
2958     }
2959     if {[info exists queryButtons$attributeTypeSelected]} {
2960         set queryButtonsTmp [lindex [set queryButtons$attributeTypeSelected] $queryNo]
2961     } else {
2962         set queryButtonsTmp [lindex $queryButtonsBib1 $queryNo]
2963     }
2964
2965     toplevelG $w
2966
2967     wm minsize $w 0 0
2968     wm title $w "Query setup $queryName - $attributeTypeSelected"
2969
2970     top-down-window $w
2971
2972     frame $w.top.lines -relief ridge -border 2
2973     pack $w.top.lines -side left -pady 6 -padx 6 -fill y
2974
2975     # Index Lines
2976
2977     index-lines $w.top.lines 0 $queryButtonsTmp $queryInfoTmp activate-e-index
2978
2979     button $w.top.lines.add -text "Add" -command [list query-add-line $queryNo]
2980     button $w.top.lines.del -text "Remove" -command [list query-del-line $queryNo]
2981     pack $w.top.lines.del -fill x -side bottom
2982     pack $w.top.lines.add -fill x -pady 10 -side bottom
2983
2984     # Indexes
2985
2986     frame $w.top.index -relief ridge -border 2
2987     pack $w.top.index -pady 6 -padx 6 -side right -fill y
2988
2989     listbox $w.top.index.list -yscrollcommand [list $w.top.index.scroll set] \
2990         -background white
2991     scrollbar $w.top.index.scroll -orient vertical -border 1 \
2992         -command [list $w.top.index.list yview]
2993     bind $w.top.index.list <Double-1> [list query-edit-index $queryNo]
2994
2995     pack $w.top.index.list -side left -fill both -expand yes -padx 2 -pady 2
2996     pack $w.top.index.scroll -side right -fill y -padx 2 -pady 2
2997
2998     $w.top.index.list selection clear 0 end
2999     $w.top.index.list selection set 0 0
3000     foreach x $queryInfoTmp {
3001         $w.top.index.list insert end [lindex $x 0]
3002     }
3003
3004     # Bottom
3005     bottom-buttons $w [list \
3006             Ok [list query-setup-action $queryNo] \
3007             Add [list query-add-index $queryNo] \
3008             Edit [list query-edit-index $queryNo] \
3009             Delete [list query-delete-index $queryNo] \
3010             Cancel [list destroy $w]] 0
3011     focus $w
3012 }
3013
3014 # Procedure index-clear
3015 # Handler that clears the search entry fields.
3016 proc index-clear {} {
3017     global queryButtonsFind
3018
3019     set i 0
3020     foreach b $queryButtonsFind {
3021         .lines.$i.e delete 0 end
3022         incr i
3023     }
3024 }
3025
3026 # Procedure index-query
3027 # The purpose of this function is to read the user's query and convert
3028 # it to the prefix query that IrTcl/YAZ uses to represent an RPN query.
3029 # Each entry in a search fields takes the form
3030 #    [relOp][?]term[?]
3031 #  Here, relOp is an optional relational operator and one of:
3032 #      >  < >= <=  <>
3033 #    which sets the Bib-1 relation to greater-than, less-than, etc.
3034 #  The ? (question-mark) is also optional. A (?) on left-side indicates
3035 #    left truncation; (?) on right-side indicates right-truncation; (?)
3036 #    on both sides indicates both-left-and-right truncation.
3037 proc index-query {} {
3038     global queryButtonsFind queryInfoFind attributeTypeSelected
3039
3040     set i 0
3041     set qs {}
3042
3043     foreach b $queryButtonsFind {
3044         set term [string trim [.lines.$i.e get]]
3045         if {$term != ""} {
3046             set attr [lrange [lindex $queryInfoFind [lindex $b 1]] 1 end]
3047
3048             set relation ""
3049             set len [string length $term]
3050             incr len -1
3051
3052             if {$len > 1} {
3053                 if {[string index $term 0] == ">"} {
3054                     if {[string index $term 1] == "=" } {
3055                         set term [string trim [string range $term 2 $len]]
3056                         set relation 4
3057                     } else {
3058                         set term [string trim [string range $term 1 $len]]
3059                         set relation 5
3060                     }
3061                 } elseif {[string index $term 0] == "<"} {
3062                     if {[string index $term 1] == "=" } {
3063                         set term [string trim [string range $term 2 $len]]
3064                         set relation 2
3065                     } elseif {[string index $term 1] == ">"} {
3066                         set term [string trim [string range $term 2 $len]]
3067                         set relation 6
3068                     } else {
3069                         set term [string trim [string range $term 1 $len]]
3070                         set relation 1
3071                     }
3072                 }
3073             } 
3074             set len [string length $term]
3075             incr len -1
3076             set left 0
3077             set right 0
3078             if {[string index $term $len] == "?"} {
3079                 set right 1
3080                 set term [string range $term 0 [expr {$len - 1}]]
3081             }
3082             if {[string index $term 0] == "?"} {
3083                 set left 1
3084                 set term [string range $term 1 end]
3085             }
3086             set term "\{${term}\}"
3087             if {$right && $left} {
3088                 set term "@attr 5=3 ${term}"
3089             } elseif {$right} {
3090                 set term "@attr 5=1 ${term}"
3091             } elseif {$left} {
3092                 set term "@attr 5=2 ${term}"
3093             }
3094             if {$relation != ""} {
3095                 set term "@attr 2=${relation} ${term}"
3096             }
3097             foreach a $attr {
3098                 set term "@attr $a ${term}"
3099             }
3100             if {$qs != ""} {
3101                 set qs "@and ${qs} ${term}"
3102             } else {
3103                 set qs $term
3104             }
3105         }
3106         incr i
3107     }
3108     debug-window "Querystring er her $qs"
3109     if {$qs == ""} {
3110         return ""
3111     } else {
3112         set qs "@attrset $attributeTypeSelected $qs"
3113         dputs "qs=  $qs"
3114         debug-window "....og nu er den $qs\n"
3115         return $qs
3116     }
3117 }
3118
3119 # Procedure index-focus-in {w i}
3120 #  w    index frame
3121 #  i    index number
3122 # This procedure handles <FocusIn> events. A red border is drawed
3123 # around the active search entry field.
3124 proc index-focus-in {w i} {
3125     global curIndexEntry
3126     $w.$i configure -background red
3127     set curIndexEntry $i
3128 }
3129
3130 # Procedure index-lines {w readOp buttonInfo queryInfo handle}
3131 #  w          search fields entry frame
3132 #  realOp     if true, search-request bindings are bound to the entries.
3133 #  buttonInfo query type button information
3134 #  queryInfo  query type field information
3135 #  handle     handler called a when a 'listbutton' changes its value
3136 # Makes one or more search areas - with listbuttons on the left
3137 # and entries on the right. 
3138 proc index-lines {w realOp buttonInfo queryInfo handle} {
3139     set i 0
3140     foreach b $buttonInfo {
3141         if {! [winfo exists $w.$i]} {
3142             frame $w.$i -border 0
3143         }
3144         listbuttonx $w.$i.l [lindex $b 1] $queryInfo $handle $i
3145
3146         if {$realOp} {
3147             if {! [winfo exists $w.$i.e]} {
3148                 entry $w.$i.e -width 32 -relief sunken -border 1
3149                 bind $w.$i.e <FocusIn> [list index-focus-in $w $i]
3150                 bind $w.$i.e <FocusOut> [list $w.$i configure -background white]
3151                 pack $w.$i.l -side left
3152                 pack $w.$i.e -side left -fill x -expand yes
3153                 pack $w.$i -side top -fill x -padx 2 -pady 2
3154                 bind $w.$i.e <Left> [list left-cursor $w.$i.e]
3155                 bind $w.$i.e <Right> [list right-cursor $w.$i.e]
3156                 bind $w.$i.e <Return> {search-request 0}
3157             }
3158         } else {
3159             pack $w.$i.l -side left
3160             pack $w.$i -side top -fill x -padx 2 -pady 2
3161         }
3162         incr i
3163     }
3164     set j $i
3165     while {[winfo exists $w.$j]} {
3166         destroy $w.$j
3167         incr j
3168     }
3169     if {! $realOp} {
3170         return
3171     }
3172     set j 0
3173     incr i -1
3174     while {$j < $i} {
3175         set k [expr {$j + 1}]
3176         bind $w.$j.e <Tab> "focus $w.$k.e"
3177         set j $k
3178     }
3179     if {$i >= 0} {
3180         bind $w.$i.e <Tab> "focus $w.0.e"
3181         focus $w.0.e
3182     }
3183 }
3184
3185 #Procedure configureOptionsSyntax {target base}
3186 #target        target name
3187 #base         database name
3188 #Changes the Options|Syntax menu acording to the information obtained via explain.
3189 proc configureOptionsSyntax {target base} {
3190     global profile syntaxList recordSyntax 
3191     set activate 0
3192     set i -1
3193     set j 0
3194     set w .top.options.m.syntax
3195     if {[info exists profile($target,RecordSyntaxes,$base)]} {
3196         foreach syntax $syntaxList {
3197             incr i
3198             if {$syntax == "sep"} {continue}
3199             incr j
3200             if {[lsearch $profile($target,RecordSyntaxes,$base) $syntax] != -1} {
3201                 configure-enable-e $w $i
3202                 if {$activate == 0} {
3203                     $w invoke $j
3204                     set recordSyntax $syntax
3205                     set activate 1
3206                 }
3207             } else {
3208                 configure-disable-e $w $i
3209             }
3210         }
3211     } else {
3212         foreach syntax $syntaxList {
3213             incr i
3214             if {$syntax == "sep"} {continue}
3215             incr j
3216             if {$syntax == $recordSyntax} {
3217                 $w invoke $j
3218             }
3219             configure-enable-e $w $i
3220         }
3221     }
3222 }
3223
3224 # Init: The geometry information for the main window is set - either
3225 # to a default value or to the value in windowGeometry(.)
3226 if {[catch {set g $windowGeometry(.)}]} {
3227     wm geometry . 500x410
3228 } else {
3229     wm geometry . $g
3230 }
3231
3232 # Init: Presentation formats are read.
3233 read-formats
3234
3235 # Init: The main window is defined.
3236 frame .top  -border 1 -relief raised
3237 frame .lines  -border 1 -relief raised
3238 frame .mid  -border 1 -relief raised
3239 frame .data -border 1 -relief raised
3240 frame .bot  -border 1 -relief raised
3241 pack .top .lines .mid -side top -fill x
3242 pack .data -side top -fill both -expand yes
3243 pack .bot -fill x
3244 #irmenu .top.file
3245
3246 # Init: Definition of File menu.
3247 menubutton .top.file -text File -menu .top.file.m -underline 0
3248 irmenu .top.file.m
3249 .top.file.m add command -label {Save settings} -command {save-settings}
3250 .top.file.m add separator
3251 .top.file.m add command -label Exit -command {exit-action}
3252
3253 # Init: Definition of Target menu.
3254 menubutton .top.target -text Target -menu .top.target.m -underline 0
3255 irmenu .top.target.m
3256 .top.target.m add cascade -label Connect -menu .top.target.m.clist
3257 .top.target.m add command -label Disconnect -command {close-target}
3258 .top.target.m add command -label About -command {about-target}
3259 .top.target.m add cascade -label Setup -menu .top.target.m.slist
3260 .top.target.m add command -label {Setup new} -command {define-target-dialog}
3261 .top.target.m add separator
3262 set-target-hotlist 0
3263
3264 configure-disable-e .top.target.m 1
3265 configure-disable-e .top.target.m 2
3266
3267 irmenu .top.target.m.clist
3268 irmenu .top.target.m.slist
3269 cascade-target-list
3270
3271 # Init: Definition of Service menu.
3272 menubutton .top.service -text Service -menu .top.service.m -underline 0
3273 irmenu .top.service.m
3274 .top.service.m add cascade -label Database -menu .top.service.m.dblist
3275 .top.service.m add cascade -label Present -menu .top.service.m.present
3276 irmenu .top.service.m.present
3277 .top.service.m.present add command -label {10 More} -command [list present-more 10]
3278 .top.service.m.present add command -label All -command [list present-more {}]
3279 .top.service.m add command -label Search -command {search-request 0}
3280 .top.service.m add command -label Scan -command {scan-request}
3281 .top.service.m add command -label Explain -command \
3282     {explain-refresh $hostid {ready-response {}} }
3283
3284 .top.service configure -state disabled
3285
3286 irmenu .top.service.m.dblist
3287
3288 # Init: Definition of Set menu.
3289 menubutton .top.rset -text Set -menu .top.rset.m -underline 1
3290 irmenu .top.rset.m
3291 .top.rset.m add command -label Load -command {load-set}
3292 .top.rset.m add separator
3293
3294 # Init: Definition of the Options menu.
3295 menubutton .top.options -text Options -menu .top.options.m -underline 0
3296 irmenu .top.options.m
3297 .top.options.m add cascade -label Query -menu .top.options.m.query
3298 .top.options.m add cascade -label Format -menu .top.options.m.formats
3299 .top.options.m add cascade -label Wrap -menu .top.options.m.wrap
3300 .top.options.m add cascade -label Syntax -menu .top.options.m.syntax
3301 .top.options.m add cascade -label Elements -menu .top.options.m.elements
3302 .top.options.m add radiobutton -label Debug -variable debugMode -value 1
3303
3304 # Init: Definition of the Options|Query menu.
3305 irmenu .top.options.m.query
3306 .top.options.m.query add cascade -label Select -menu .top.options.m.query.clist
3307 .top.options.m.query add cascade -label Type -menu .top.options.m.query.tlist
3308 .top.options.m.query add cascade -label Edit -menu .top.options.m.query.slist
3309 .top.options.m.query add command -label New -command {query-new}
3310 .top.options.m.query add cascade -label Delete -menu .top.options.m.query.dlist
3311
3312 irmenu .top.options.m.query.slist
3313 irmenu .top.options.m.query.tlist
3314 irmenu .top.options.m.query.clist
3315 irmenu .top.options.m.query.dlist
3316 cascade-query-list
3317
3318 # Init: Definition of the Options|Formats menu.
3319 irmenu .top.options.m.formats
3320 set i 0
3321 foreach f $displayFormats {
3322     .top.options.m.formats add radiobutton -label $f -value $i \
3323             -command [list set-display-format $i] -variable displayFormat
3324     incr i
3325 }
3326
3327 # Init: Definition of the Options|Wrap menu.
3328 irmenu .top.options.m.wrap
3329 .top.options.m.wrap add radiobutton -label Character \
3330         -value char -variable textWrap -command {set-wrap char}
3331 .top.options.m.wrap add radiobutton -label Word \
3332         -value word -variable textWrap -command {set-wrap word}
3333 .top.options.m.wrap add radiobutton -label None \
3334         -value none -variable textWrap -command {set-wrap none}
3335
3336 # Init: Definition of the Options|Syntax menu.
3337 proc initOptionsSyntax {} {
3338     global syntaxList recordSyntax
3339     set w .top.options.m.syntax
3340     irmenu $w
3341     foreach syntax $syntaxList {
3342         if {$syntax == "sep"} {
3343             $w add separator
3344         } else {
3345             $w add radiobutton -label $syntax -value $syntax -variable recordSyntax
3346         }
3347     }
3348 }
3349 initOptionsSyntax
3350
3351 # Init: Definition of the Options|Elements menu.
3352 irmenu .top.options.m.elements
3353 .top.options.m.elements add radiobutton -label Unspecified \
3354         -value None -variable elementSetNames
3355 .top.options.m.elements add radiobutton -label Full -value F -variable elementSetNames
3356 .top.options.m.elements add radiobutton -label Brief -value B -variable elementSetNames
3357
3358 # Init: Definition of Help menu.
3359 menubutton .top.help -text "Help" -menu .top.help.m -underline 0
3360 irmenu .top.help.m
3361
3362 #.top.help.m add command -label "Help on help" -command {tkerror "Help on help not available. Sorry"}
3363 .top.help.m add command -label "Help on help" -command {bgerror "Help on help not available. Sorry"}
3364 .top.help.m add command -label "About" -command {about-origin}
3365
3366 # Init: Pack menu bar items.
3367 pack .top.file .top.target .top.service .top.rset .top.options -side left
3368 pack .top.help -side right
3369 #.top configure -menu .top.file
3370
3371 # Init: Define query area buttons with icons.
3372 index-lines .lines 1 $queryButtonsFind [lindex [set \
3373     queryInfo$attributeTypeSelected] 0] activate-index
3374 image create photo scan -file [file join $libdir bitmaps a-z.gif]
3375 image create photo clear -file [file join $libdir bitmaps trash.gif]
3376 image create photo present -file [file join $libdir bitmaps page.gif]
3377 image create photo search -file [file join $libdir bitmaps search.gif]
3378 image create photo stop -file [file join $libdir bitmaps stop.gif]
3379 button .mid.search -image search -command {search-request 0} \
3380     -state disabled -relief flat
3381 button .mid.scan -image scan -command scan-request -state disabled -relief flat
3382 button .mid.present -image present -command [list present-more 10] \
3383     -state disabled -relief flat
3384 button .mid.clear -image clear -command index-clear -relief flat
3385 button .mid.stop -image stop -command cancel-operation -relief flat
3386 pack .mid.search .mid.scan .mid.present .mid.clear -side left -fill y -pady 1
3387 pack .mid.stop -side left -fill y -padx 20
3388
3389 # Init: Define record area in main window.
3390 text .data.record -font fixed -height 2 -width 20 -wrap none -borderwidth 0 \
3391     -relief flat -yscrollcommand [list .data.scroll set] -wrap $textWrap
3392 scrollbar .data.scroll -command [list .data.record yview]
3393 .data.record configure -takefocus 0
3394 .data.scroll configure -takefocus 0
3395
3396 pack .data.scroll -side right -fill y
3397 pack .data.record -expand yes -fill both
3398 initBindings
3399
3400 # Init: Define standards tags. These are used in the display
3401 # format procedures.
3402
3403 .data.record tag configure marc-tag -foreground blue
3404 .data.record tag configure marc-id -foreground red
3405 .data.record tag configure marc-data -foreground black
3406 .data.record tag configure marc-head -font $font(n,normal) \
3407         -foreground brown -relief raised -borderwidth 1
3408 .data.record tag configure marc-small-head -foreground brown
3409 .data.record tag configure marc-pref -font $font(n,normal) -foreground blue
3410 .data.record tag configure marc-text -font $font(n,normal) -foreground black
3411 .data.record tag configure marc-it -font $font(n,normal) -foreground black
3412
3413 # Init: Define logo.
3414 button .bot.logo -bitmap @[file join $libdir bitmaps book1] -command cancel-operation
3415 .bot.logo configure -takefocus 0
3416
3417 # Init: Define status information fields at the bottom.
3418 frame .bot.a
3419 pack .bot.a -side left -fill x
3420 pack .bot.logo -side right -padx 2 -pady 2 -ipadx 1
3421
3422 message .bot.a.target -text {} -aspect 2000 -border 1
3423
3424 label .bot.a.status -text "Not connected" -width 15 -relief sunken -anchor w -border 1
3425 label .bot.a.set -text "" -width 5 -relief sunken -anchor w -border 1
3426 label .bot.a.message -text "" -width 15 -relief sunken -anchor w -border 1
3427
3428 pack .bot.a.target -side top -anchor nw -padx 2 -pady 2
3429 pack .bot.a.status .bot.a.set .bot.a.message -side left -padx 2 -pady 2 -ipadx 1 -ipady 1
3430
3431 # Init: Determine if the IrTcl extension is already there. If
3432 #  not, then dynamically load the IrTcl extension.
3433 if {[catch {ir z39}]} {
3434     set e [info sharedlibextension]
3435     puts -nonewline "Loading irtcl$e ..."
3436     load [file join $libdir irtcl$e] irtcl
3437     ir z39
3438     puts "ok"
3439 }
3440
3441 if {[file exists [file join $libdir explain.tcl]]} {
3442     source [file join $libdir explain.tcl]
3443 }
3444
3445 #if {[file exists ${libdir}/setup.tcl]} 
3446     source [file join $libdir setup.tcl]
3447
3448
3449 # Init: Uncomment this line if you wan't to enable logging.
3450 ir-log-init all irtcl irtcl.log
3451
3452 # Init: If hostid is a valid target, a new connection will be established
3453 # immediately.
3454 if {[string compare $hostid Default]} {
3455     catch {open-target $hostid $hostbase}
3456 }
3457
3458 # Init: Enable the logo.
3459 show-logo 1
3460