# ts_exec.tcl

proc ExecCmd {cmd} {
  global params gparams

  if {$params(pid) > 0} {
    Warning $params(dlg_geom) \
      "Foreground process is still running.\nWait or kill it."
    return
  }
  if {!$gparams(showout)} {
    catch {grid forget .term}
    grid .term -row 2 -column 0 -sticky ew
  }
  set params(pipe) [open "|/bin/sh -c \"$cmd\" 2>@stdout" r+]
  debug "Pipe: $params(pipe)"
  set params(pid) [pid $params(pipe)]
  lappend params(processlist) [list $params(pid) $cmd]
  fconfigure $params(pipe) -buffering none -blocking 0
  fileevent $params(pipe) readable "CmdOut"
}

proc ExecBg {cmd} {
  global params

  set pipe [open "|/bin/sh -c \"$cmd\" 2>@stdout" r]
  set pid [pid $pipe]
  lappend params(processlist) [list $pid $cmd]
  fconfigure $pipe -buffering none -blocking 0
  fileevent $pipe readable "BgOut $pipe $pid"
  
}

proc ExecTerm {cmd} {
  global params

  eval exec xterm -geometry $params(dlg_geom) -e $cmd 
}

proc ExecTermBg {cmd} {
  global params

  eval exec xterm -geometry $params(dlg_geom) -e $cmd &
}

proc CmdOut {} {
  global params gparams sigchld

  if [eof $params(pipe)] {
    debug "End of $params(pipe)"
    catch {close $params(pipe)} err
    set sigchld 1
    debug "Close pipe: $err"
    set i [lsearch $params(processlist) "$params(pid) *"]
    if {$i >= 0} {
      set params(processlist) [lreplace $params(processlist) $i $i]
    }
    set params(pid) -1
    if {!$gparams(showout)} {
      grid forget .term
    }
    return
  }
  set line [read $params(pipe)]
  .term insert end $line
  .term mark set insert end
  .term see end
}

proc BgOut {pipe pid} {
  global params

  if [eof $pipe] {
    debug "End of $pid $pipe"
    catch {close $pipe} err
    set i [lsearch $params(processlist) "$pid *"]
    if {$i >= 0} {
      set params(processlist) [lreplace $params(processlist) $i $i]
    }
    debug $err
    return
  }
  set line [read $pipe]
  .term insert end $line
  .term mark set insert end
  .term see end
}

proc Out {w line} {
  $w insert end $line\n
  $w mark set insert end
  $w see end
}

proc CreateTerm {} {
  global termline

  set termline ""
  bind .term <Return> {
    catch {
      puts $params(pipe) $termline
    }
    set termline ""
  }
  bind .term <BackSpace> {
    set termline [string range $termline 0 \
      [expr [string length $termline]-2]]
  }
  bind .term <Any-Key> {
    append termline %A
  }
}

proc Kill {} {
  global params
 
  set procs {}
  foreach l $params(processlist) {
    lappend procs [format "%5d %s" [lindex $l 0] [lindex $l 1]]
  }
  if {[set i [ListDlg .ldlg $params(dlg_geom) "Kill Process:" $procs]] \
    >= 0} {
    set pid [lindex [lindex $params(processlist) $i] 0]
    catch {exec kill $pid} err
    OutMsg "Process $pid killed: $err"
    set params(processlist) [lreplace $params(processlist) $i $i]
    set params(pid) 0
  }
}
