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