summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/support/tlcockpit/src/main/scala/TeXLive/TlmgrProcess.scala
blob: 8984ab7a1affd87770aa5c3d9f810f4eab816591 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package TeXLive

import java.io._

import OsInfo._

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.SyncVar
import scala.sys.process.{Process, ProcessBuilder, ProcessIO}

class TlmgrProcess(updout: Array[String] => Unit, upderr: String => Unit) {
  val inputString = new SyncVar[String]                 // used for the tlmgr process input
  val outputString = new SyncVar[String]                // used for the tlmgr process output
  val errorBuffer: StringBuffer = new StringBuffer()    // buffer used for both tmgr process error console AND logging

  // set in only one place, in the main thread
  var process: Process = _
  var lastInput: String = ""
  var lastOk: Boolean = false

  def send_command(input: String): Array[String] = {

    lastInput = input

    try {
      // pass the input and wait for the output
      assert(!inputString.isSet)
      assert(!outputString.isSet)
      errorBuffer.setLength(0)
      inputString.put(input)
      var ret = if (input != "quit") {
        get_output_till_prompt()
      } else {
        new Array[String](0)
      }
      // updout(ret.mkString("\n"))
      updout(ret)
      upderr(errorBuffer.toString)
      ret
    } catch {
      case exc: Throwable =>
        errorBuffer.append("  Main thread: " +
          (if (exc.isInstanceOf[NoSuchElementException]) "Timeout" else "Exception: " + exc))
        null
    }
  }

  def start_process(): Unit = {
    // process creation
    if (process == null) {
      val procIO = new ProcessIO(inputFn(_), outputFn(_), errorFn(_))
      val processBuilder: ProcessBuilder = Seq({if (isWindows) "tlmgr.bat" else "tlmgr"}, "--machine-readable", "shell")
      process = processBuilder.run(procIO)
    }
  }

  def get_output_till_prompt(): Array[String] = {
    var ret = ArrayBuffer[String]()
    var result = ""
    var found = false
    while (!found) {
      result = outputString.take()
      if (result == "tlmgr> ") {
        found = true
      } else if (result == "OK") {
        lastOk = true
        // do nothing, we found a good ok
      } else if (result == "ERROR") {
        lastOk = false
      } else {
        ret += result
      }
    }
    ret.toArray
  }

  def cleanup(): Unit = {
    if (process != null) {
      send_command("quit")
      process.destroy()
      // we'll need to unblock the input again
      // TODO what is that needed for???
      // if (!inputString.isSet) inputString.put("")
      // if (outputString.isSet) outputString.take()
    }
  }

  /* The standard input passing function */
  private[this] def inputFn(stdin: OutputStream): Unit = {
    val writer = new BufferedWriter(new OutputStreamWriter(stdin))
    try {
      var input = ""
      while (true) {
        input = inputString.take()
        if (input == "quit") {
          stdin.close()
          return
        } else {
          writer.write(input + "\n")
          // println("writing " + input + " to process")
          writer.flush()
        }
      }
      stdin.close()
    } catch {
      case exc: Throwable =>
        stdin.close()
        errorBuffer.append("  Input thread: Exception: " + exc + "\n")
    }
  }

  private[this] def outputFn(stdOut: InputStream): Unit = {
    val reader = new BufferedReader(new InputStreamReader(stdOut))
    val buffer: StringBuilder = new StringBuilder()
    try {
      var line: String = ""
      while (true) {
        line = reader.readLine
        if (line == null) {
          // println("Did read NULL from stdin giving up")
          // error = true
        } else {
          // println("did read " + line + " from process")
          outputString.put(line)
        }
      }
      stdOut.close()
    } catch {
      case exc: Throwable =>
        stdOut.close()
        errorBuffer.append("  Output thread: Exception: " + exc + "\n")
    }
  }

  private[this] def errorFn(stdErr: InputStream): Unit = {
    val reader = new BufferedReader(new InputStreamReader(stdErr))
    try {
      var line = reader.readLine
      while (line != null) {
        errorBuffer.append(line + "\n")
        line = reader.readLine
      }
      stdErr.close()
    } catch {
      case exc: Throwable =>
        stdErr.close()
        errorBuffer.append("  Error thread: Exception: " + exc + "\n")
    }
  }
}