# ts_template.tcl
# Handling of document templates

proc scan_templates {} {
  global params env

  set fdidx [open $env(HOME)/.ts/templates.idx w]
  set filelist \
    [concat [glob -nocomplain $params(template_dir)/*.tpl] \
            [glob -nocomplain $env(HOME)/.ts/*.tpl]]
  foreach f $filelist {
    set fd [open $f r]
    gets $fd desc
    regexp {%! *(.*)} $desc dummy desc
    puts $fdidx [list $desc $f]
    close $fd
  }
  close $fdidx
}

proc read_templatelist {} {
  global params env

  if {![file exists $params(template_index)]} {
    scan_templates
  }
  set fdidx [open $env(HOME)/.ts/templates.idx r]
  set params(template_list) [list [list {## blank ##} {}]]
  while {![eof $fdidx]} {
    gets $fdidx s
    if {$s != {}} {
      lappend params(template_list) $s
    }
  }
  close $fdidx
}

proc tpldlg_readlist {} {
  global params

  .tpldlg.lb delete 0 end
  foreach l $params(template_list) {
    debug $l
    .tpldlg.lb insert end [lindex $l 0]
  }
  .tpldlg.lb activate 0
  .tpldlg.lb select anchor 0
  .tpldlg.lb select set anchor 0
}

proc tpldlg_rescan {} {

  scan_templates
  read_templatelist
  tpldlg_readlist
}

proc templatedlg {} {
  global params tpldlg

  toplevel .tpldlg
  wm geometry .tpldlg $params(dlg_geom)
  wm title .tpldlg "Select template"

  label .tpldlg.l -text "template:" -anchor w
  frame .tpldlg.flist
  listbox .tpldlg.lb -width 50 -yscrollcommand {.tpldlg.sb set}
  scrollbar .tpldlg.sb -command {.tpldlg.lb yview}
  pack .tpldlg.sb -in .tpldlg.flist -side right -fill y
  pack .tpldlg.lb -in .tpldlg.flist -side left -fill both

  frame .tpldlg.fbot
  button .tpldlg.bok -text OK -command {set tpldlg(ok) 1}
  button .tpldlg.bcancel -text Cancel -command {set tpldlg(ok) 0}
  button .tpldlg.bscan -text "Rescan templates" -underline 2 \
    -command {tpldlg_rescan}
  pack .tpldlg.bok .tpldlg.bcancel .tpldlg.bscan -in .tpldlg.fbot -side left
  pack .tpldlg.l .tpldlg.flist .tpldlg.fbot -fill x
  bind .tpldlg.lb <Return> {set tpldlg(ok) 1}
  bind .tpldlg.lb <Escape> {set tpldlg(ok) 0}
  bind .tpldlg.lb <Alt-s>  {tpldlg_rescan}
  tpldlg_readlist
  set tpldlg(ok) ""
  set old_focus [focus]
  focus .tpldlg.lb
  grab .tpldlg
  tkwait variable tpldlg(ok)
  grab release .tpldlg
  if {$tpldlg(ok)} {
    set i [.tpldlg.lb index active]
    set file [lindex [lindex $params(template_list) $i] 1]
  } else {
    set file ""
  }
  focus $old_focus
  destroy .tpldlg
  return $file
}
