1/*  Title:      Pure/System/isabelle_system.scala
2    Author:     Makarius
3
4Fundamental Isabelle system environment: quasi-static module with
5optional init operation.
6*/
7
8package isabelle
9
10
11import java.io.{File => JFile, IOException}
12import java.nio.file.{Path => JPath, Files, SimpleFileVisitor, FileVisitResult}
13import java.nio.file.attribute.BasicFileAttributes
14
15import scala.collection.mutable
16
17
18object Isabelle_System
19{
20  /** bootstrap information **/
21
22  def jdk_home(): String =
23  {
24    val java_home = System.getProperty("java.home", "")
25    val home = new JFile(java_home)
26    val parent = home.getParent
27    if (home.getName == "jre" && parent != null &&
28        (new JFile(new JFile(parent, "bin"), "javac")).exists) parent
29    else java_home
30  }
31
32  def bootstrap_directory(
33    preference: String, envar: String, property: String, description: String): String =
34  {
35    val value =
36      proper_string(preference) orElse  // explicit argument
37      proper_string(System.getenv(envar)) orElse  // e.g. inherited from running isabelle tool
38      proper_string(System.getProperty(property)) getOrElse  // e.g. via JVM application boot process
39      error("Unknown " + description + " directory")
40
41    if ((new JFile(value)).isDirectory) value
42    else error("Bad " + description + " directory " + quote(value))
43  }
44
45
46
47  /** implicit settings environment **/
48
49  @volatile private var _settings: Option[Map[String, String]] = None
50
51  def settings(): Map[String, String] =
52  {
53    if (_settings.isEmpty) init()  // unsynchronized check
54    _settings.get
55  }
56
57  def init(isabelle_root: String = "", cygwin_root: String = ""): Unit = synchronized {
58    if (_settings.isEmpty) {
59      import scala.collection.JavaConversions._
60
61      val isabelle_root1 =
62        bootstrap_directory(isabelle_root, "ISABELLE_ROOT", "isabelle.root", "Isabelle root")
63
64      val cygwin_root1 =
65        if (Platform.is_windows)
66          bootstrap_directory(cygwin_root, "CYGWIN_ROOT", "cygwin.root", "Cygwin root")
67        else ""
68
69      if (Platform.is_windows) Cygwin.init(isabelle_root1, cygwin_root1)
70
71      def set_cygwin_root()
72      {
73        if (Platform.is_windows)
74          _settings = Some(_settings.getOrElse(Map.empty) + ("CYGWIN_ROOT" -> cygwin_root1))
75      }
76
77      set_cygwin_root()
78
79      def default(env: Map[String, String], entry: (String, String)): Map[String, String] =
80        if (env.isDefinedAt(entry._1) || entry._2 == "") env
81        else env + entry
82
83      val env =
84      {
85        val temp_windows =
86        {
87          val temp = if (Platform.is_windows) System.getenv("TEMP") else null
88          if (temp != null && temp.contains('\\')) temp else ""
89        }
90        val user_home = System.getProperty("user.home", "")
91        val isabelle_app = System.getProperty("isabelle.app", "")
92
93        default(
94          default(
95            default(sys.env + ("ISABELLE_JDK_HOME" -> File.standard_path(jdk_home())),
96              "TEMP_WINDOWS" -> temp_windows),
97            "HOME" -> user_home),
98          "ISABELLE_APP" -> "true")
99      }
100
101      val settings =
102      {
103        val dump = JFile.createTempFile("settings", null)
104        dump.deleteOnExit
105        try {
106          val cmd1 =
107            if (Platform.is_windows)
108              List(cygwin_root1 + "\\bin\\bash", "-l",
109                File.standard_path(isabelle_root1 + "\\bin\\isabelle"))
110            else
111              List(isabelle_root1 + "/bin/isabelle")
112          val cmd = cmd1 ::: List("getenv", "-d", dump.toString)
113
114          val (output, rc) = process_output(process(cmd, env = env, redirect = true))
115          if (rc != 0) error(output)
116
117          val entries =
118            (for (entry <- File.read(dump).split("\u0000") if entry != "") yield {
119              val i = entry.indexOf('=')
120              if (i <= 0) entry -> ""
121              else entry.substring(0, i) -> entry.substring(i + 1)
122            }).toMap
123          entries + ("PATH" -> entries("PATH_JVM")) - "PATH_JVM"
124        }
125        finally { dump.delete }
126      }
127      _settings = Some(settings)
128      set_cygwin_root()
129    }
130  }
131
132
133  /* getenv */
134
135  def getenv(name: String, env: Map[String, String] = settings()): String =
136    env.getOrElse(name, "")
137
138  def getenv_strict(name: String, env: Map[String, String] = settings()): String =
139    proper_string(getenv(name, env)) getOrElse
140      error("Undefined Isabelle environment variable: " + quote(name))
141
142  def cygwin_root(): String = getenv_strict("CYGWIN_ROOT")
143
144  def isabelle_id(): String =
145    proper_string(getenv("ISABELLE_ID")) getOrElse
146      Mercurial.repository(Path.explode("~~")).parent()
147
148
149
150  /** file-system operations **/
151
152  /* directories */
153
154  def mkdirs(path: Path): Unit =
155    if (!path.is_dir) {
156      bash("perl -e \"use File::Path make_path; make_path('" + File.standard_path(path) + "');\"")
157      if (!path.is_dir) error("Failed to create directory: " + quote(File.platform_path(path)))
158    }
159
160  def copy_dir(dir1: Path, dir2: Path): Unit =
161    bash("cp -a " + File.bash_path(dir1) + " " + File.bash_path(dir2)).check
162
163
164  /* tmp files */
165
166  private def isabelle_tmp_prefix(): JFile =
167  {
168    val path = Path.explode("$ISABELLE_TMP_PREFIX")
169    path.file.mkdirs  // low-level mkdirs
170    File.platform_file(path)
171  }
172
173  def tmp_file(name: String, ext: String = "", base_dir: JFile = isabelle_tmp_prefix()): JFile =
174  {
175    val suffix = if (ext == "") "" else "." + ext
176    val file = Files.createTempFile(base_dir.toPath, name, suffix).toFile
177    file.deleteOnExit
178    file
179  }
180
181  def with_tmp_file[A](name: String, ext: String = "")(body: Path => A): A =
182  {
183    val file = tmp_file(name, ext)
184    try { body(File.path(file)) } finally { file.delete }
185  }
186
187
188  /* tmp dirs */
189
190  def rm_tree(root: Path): Unit = rm_tree(root.file)
191
192  def rm_tree(root: JFile)
193  {
194    root.delete
195    if (root.isDirectory) {
196      Files.walkFileTree(root.toPath,
197        new SimpleFileVisitor[JPath] {
198          override def visitFile(file: JPath, attrs: BasicFileAttributes): FileVisitResult =
199          {
200            Files.deleteIfExists(file)
201            FileVisitResult.CONTINUE
202          }
203
204          override def postVisitDirectory(dir: JPath, e: IOException): FileVisitResult =
205          {
206            if (e == null) {
207              Files.deleteIfExists(dir)
208              FileVisitResult.CONTINUE
209            }
210            else throw e
211          }
212        }
213      )
214    }
215  }
216
217  def tmp_dir(name: String, base_dir: JFile = isabelle_tmp_prefix()): JFile =
218  {
219    val dir = Files.createTempDirectory(base_dir.toPath, name).toFile
220    dir.deleteOnExit
221    dir
222  }
223
224  def with_tmp_dir[A](name: String)(body: Path => A): A =
225  {
226    val dir = tmp_dir(name)
227    try { body(File.path(dir)) } finally { rm_tree(dir) }
228  }
229
230
231  /* quasi-atomic update of directory */
232
233  def update_directory(dir: Path, f: Path => Unit)
234  {
235    val new_dir = dir.ext("new")
236    val old_dir = dir.ext("old")
237
238    rm_tree(new_dir)
239    rm_tree(old_dir)
240
241    f(new_dir)
242
243    if (dir.is_dir) File.move(dir, old_dir)
244    File.move(new_dir, dir)
245    rm_tree(old_dir)
246  }
247
248
249
250  /** external processes **/
251
252  /* raw process */
253
254  def process(command_line: List[String],
255    cwd: JFile = null,
256    env: Map[String, String] = settings(),
257    redirect: Boolean = false): Process =
258  {
259    val proc = new ProcessBuilder
260    proc.command(command_line:_*)  // fragile on Windows
261    if (cwd != null) proc.directory(cwd)
262    if (env != null) {
263      proc.environment.clear
264      for ((x, y) <- env) proc.environment.put(x, y)
265    }
266    proc.redirectErrorStream(redirect)
267    proc.start
268  }
269
270  def process_output(proc: Process): (String, Int) =
271  {
272    proc.getOutputStream.close
273
274    val output = File.read_stream(proc.getInputStream)
275    val rc =
276      try { proc.waitFor }
277      finally {
278        proc.getInputStream.close
279        proc.getErrorStream.close
280        proc.destroy
281        Thread.interrupted
282      }
283    (output, rc)
284  }
285
286  def kill(signal: String, group_pid: String): (String, Int) =
287  {
288    val bash =
289      if (Platform.is_windows) List(cygwin_root() + "\\bin\\bash.exe")
290      else List("/usr/bin/env", "bash")
291    process_output(process(bash ::: List("-c", "kill -" + signal + " -" + group_pid)))
292  }
293
294
295  /* GNU bash */
296
297  def bash(script: String,
298    cwd: JFile = null,
299    env: Map[String, String] = settings(),
300    redirect: Boolean = false,
301    progress_stdout: String => Unit = (_: String) => (),
302    progress_stderr: String => Unit = (_: String) => (),
303    progress_limit: Option[Long] = None,
304    strict: Boolean = true,
305    cleanup: () => Unit = () => ()): Process_Result =
306  {
307    Bash.process(script, cwd = cwd, env = env, redirect = redirect, cleanup = cleanup).
308      result(progress_stdout, progress_stderr, progress_limit, strict)
309  }
310
311  private lazy val gnutar_check: Boolean =
312    try { bash("tar --version").check.out.containsSlice("GNU tar") || error("") }
313    catch { case ERROR(_) => false }
314
315  def gnutar(args: String, cwd: JFile = null, redirect: Boolean = false): Process_Result =
316  {
317    if (gnutar_check) bash("tar " + args, cwd = cwd, redirect = redirect)
318    else error("Expected to find GNU tar executable")
319  }
320
321  def hostname(): String = bash("hostname -s").check.out
322
323  def open(arg: String): Unit =
324    bash("exec \"$ISABELLE_OPEN\" " + Bash.string(arg) + " >/dev/null 2>/dev/null &")
325
326  def pdf_viewer(arg: Path): Unit =
327    bash("exec \"$PDF_VIEWER\" " + File.bash_path(arg) + " >/dev/null 2>/dev/null &")
328
329  def export_isabelle_identifier(isabelle_identifier: String): String =
330    if (isabelle_identifier == "") ""
331    else "export ISABELLE_IDENTIFIER=" + Bash.string(isabelle_identifier) + "\n"
332
333
334
335  /** Isabelle resources **/
336
337  /* repository clone with Admin */
338
339  def admin(): Boolean = Path.explode("~~/Admin").is_dir
340
341
342  /* components */
343
344  def components(): List[Path] =
345    Path.split(getenv_strict("ISABELLE_COMPONENTS"))
346
347
348  /* fonts */
349
350  def fonts(html: Boolean = false): List[Path] =
351  {
352    val variables =
353      if (html) List("ISABELLE_FONTS", "ISABELLE_FONTS_HTML") else List("ISABELLE_FONTS")
354    for {
355      variable <- variables
356      path <- Path.split(Isabelle_System.getenv_strict(variable))
357    } yield path
358  }
359
360
361  /* default logic */
362
363  def default_logic(args: String*): String =
364  {
365    args.find(_ != "") match {
366      case Some(logic) => logic
367      case None => Isabelle_System.getenv_strict("ISABELLE_LOGIC")
368    }
369  }
370}
371