diff --git a/src/Pure/Admin/build_status.scala b/src/Pure/Admin/build_status.scala --- a/src/Pure/Admin/build_status.scala +++ b/src/Pure/Admin/build_status.scala @@ -1,621 +1,621 @@ /* Title: Pure/Admin/build_status.scala Author: Makarius Present recent build status information from database. */ package isabelle object Build_Status { /* defaults */ val default_target_dir = Path.explode("build_status") val default_image_size = (800, 600) val default_history = 30 def default_profiles: List[Profile] = Jenkins.build_status_profiles ::: Isabelle_Cronjob.build_status_profiles /* data profiles */ sealed case class Profile( description: String, history: Int = 0, afp: Boolean = false, bulky: Boolean = false, sql: String) { def days(options: Options): Int = options.int("build_log_history") max history def stretch(options: Options): Double = (days(options) max default_history min (default_history * 5)).toDouble / default_history def select(options: Options, columns: List[SQL.Column], only_sessions: Set[String]): SQL.Source = { Build_Log.Data.universal_table.select(columns, distinct = true, sql = "WHERE " + Build_Log.Data.pull_date(afp) + " > " + Build_Log.Data.recent_time(days(options)) + " AND " + SQL.member(Build_Log.Data.status.ident, List( Build_Log.Session_Status.finished.toString, Build_Log.Session_Status.failed.toString)) + (if (only_sessions.isEmpty) "" else " AND " + SQL.member(Build_Log.Data.session_name.ident, only_sessions)) + " AND " + SQL.enclose(sql)) } } /* build status */ def build_status(options: Options, progress: Progress = new Progress, profiles: List[Profile] = default_profiles, only_sessions: Set[String] = Set.empty, verbose: Boolean = false, target_dir: Path = default_target_dir, ml_statistics: Boolean = false, image_size: (Int, Int) = default_image_size): Unit = { val ml_statistics_domain = Iterator(ML_Statistics.heap_fields, ML_Statistics.program_fields, ML_Statistics.tasks_fields, ML_Statistics.workers_fields).flatMap(_._2).toSet val data = read_data(options, progress = progress, profiles = profiles, only_sessions = only_sessions, verbose = verbose, ml_statistics = ml_statistics, ml_statistics_domain = ml_statistics_domain) present_data(data, progress = progress, target_dir = target_dir, image_size = image_size) } /* read data */ sealed case class Data(date: Date, entries: List[Data_Entry]) sealed case class Data_Entry( name: String, hosts: List[String], stretch: Double, sessions: List[Session]) { def failed_sessions: List[Session] = sessions.filter(_.head.failed).sortBy(_.name) } sealed case class Session( name: String, threads: Int, entries: List[Entry], ml_statistics: ML_Statistics, ml_statistics_date: Long) { require(entries.nonEmpty, "no entries") lazy val sorted_entries: List[Entry] = entries.sortBy(entry => - entry.date) def head: Entry = sorted_entries.head def order: Long = - head.timing.elapsed.ms def finished_entries: List[Entry] = sorted_entries.filter(_.finished) def finished_entries_size: Int = finished_entries.map(_.date).toSet.size def check_timing: Boolean = finished_entries_size >= 3 def check_heap: Boolean = finished_entries_size >= 3 && finished_entries.forall(entry => entry.maximum_heap > 0 || entry.average_heap > 0 || entry.stored_heap > 0) def make_csv: CSV.File = { val header = List("session_name", "chapter", "pull_date", "afp_pull_date", "isabelle_version", "afp_version", "timing_elapsed", "timing_cpu", "timing_gc", "ml_timing_elapsed", "ml_timing_cpu", "ml_timing_gc", "maximum_code", "average_code", "maximum_stack", "average_stack", "maximum_heap", "average_heap", "stored_heap", "status") val date_format = Date.Format("uuuu-MM-dd HH:mm:ss") val records = for (entry <- sorted_entries) yield { CSV.Record(name, entry.chapter, date_format(entry.pull_date), entry.afp_pull_date match { case Some(date) => date_format(date) case None => "" }, entry.isabelle_version, entry.afp_version, entry.timing.elapsed.ms, entry.timing.cpu.ms, entry.timing.gc.ms, entry.ml_timing.elapsed.ms, entry.ml_timing.cpu.ms, entry.ml_timing.gc.ms, entry.maximum_code, entry.average_code, entry.maximum_stack, entry.average_stack, entry.maximum_heap, entry.average_heap, entry.stored_heap, entry.status) } CSV.File(name, header, records) } } sealed case class Entry( chapter: String, pull_date: Date, afp_pull_date: Option[Date], isabelle_version: String, afp_version: String, timing: Timing, ml_timing: Timing, maximum_code: Long, average_code: Long, maximum_stack: Long, average_stack: Long, maximum_heap: Long, average_heap: Long, stored_heap: Long, status: Build_Log.Session_Status.Value, errors: List[String]) { val date: Long = (afp_pull_date getOrElse pull_date).unix_epoch def finished: Boolean = status == Build_Log.Session_Status.finished def failed: Boolean = status == Build_Log.Session_Status.failed def present_errors(name: String): XML.Body = { if (errors.isEmpty) HTML.text(name + print_version(isabelle_version, afp_version, chapter)) else { HTML.tooltip_errors(HTML.text(name), errors.map(s => HTML.text(Symbol.decode(s)))) :: HTML.text(print_version(isabelle_version, afp_version, chapter)) } } } sealed case class Image(name: String, width: Int, height: Int) { def path: Path = Path.basic(name) } def print_version( isabelle_version: String, afp_version: String = "", chapter: String = AFP.chapter): String = { val body = proper_string(isabelle_version).map("Isabelle/" + _).toList ::: (if (chapter == AFP.chapter) proper_string(afp_version).map("AFP/" + _) else None).toList if (body.isEmpty) "" else body.mkString(" (", ", ", ")") } def read_data(options: Options, progress: Progress = new Progress, profiles: List[Profile] = default_profiles, only_sessions: Set[String] = Set.empty, ml_statistics: Boolean = false, ml_statistics_domain: String => Boolean = (key: String) => true, verbose: Boolean = false): Data = { val date = Date.now() var data_hosts = Map.empty[String, Set[String]] var data_stretch = Map.empty[String, Double] var data_entries = Map.empty[String, Map[String, Session]] def get_hosts(data_name: String): Set[String] = data_hosts.getOrElse(data_name, Set.empty) val store = Build_Log.store(options) using(store.open_database())(db => { for (profile <- profiles.sortBy(_.description)) { progress.echo("input " + quote(profile.description)) val afp = profile.afp val columns = List( Build_Log.Data.pull_date(afp = false), Build_Log.Data.pull_date(afp = true), Build_Log.Prop.build_host, Build_Log.Prop.isabelle_version, Build_Log.Prop.afp_version, Build_Log.Settings.ISABELLE_BUILD_OPTIONS, Build_Log.Settings.ML_PLATFORM, Build_Log.Data.session_name, Build_Log.Data.chapter, Build_Log.Data.groups, Build_Log.Data.threads, Build_Log.Data.timing_elapsed, Build_Log.Data.timing_cpu, Build_Log.Data.timing_gc, Build_Log.Data.ml_timing_elapsed, Build_Log.Data.ml_timing_cpu, Build_Log.Data.ml_timing_gc, Build_Log.Data.heap_size, Build_Log.Data.status, Build_Log.Data.errors) ::: (if (ml_statistics) List(Build_Log.Data.ml_statistics) else Nil) val Threads_Option = """threads\s*=\s*(\d+)""".r val sql = profile.select(options, columns, only_sessions) progress.echo_if(verbose, sql) db.using_statement(sql)(stmt => { val res = stmt.execute_query() while (res.next()) { val session_name = res.string(Build_Log.Data.session_name) val chapter = res.string(Build_Log.Data.chapter) val groups = split_lines(res.string(Build_Log.Data.groups)) val threads = { val threads1 = res.string(Build_Log.Settings.ISABELLE_BUILD_OPTIONS) match { case Threads_Option(Value.Int(i)) => i case _ => 1 } val threads2 = res.get_int(Build_Log.Data.threads).getOrElse(1) threads1 max threads2 } val ml_platform = res.string(Build_Log.Settings.ML_PLATFORM) val data_name = profile.description + (if (ml_platform.startsWith("x86_64-")) ", 64bit" else "") + (if (threads == 1) "" else ", " + threads + " threads") res.get_string(Build_Log.Prop.build_host).foreach(host => data_hosts += (data_name -> (get_hosts(data_name) + host))) data_stretch += (data_name -> profile.stretch(options)) val isabelle_version = res.string(Build_Log.Prop.isabelle_version) val afp_version = res.string(Build_Log.Prop.afp_version) val ml_stats = ML_Statistics( if (ml_statistics) { Properties.uncompress(res.bytes(Build_Log.Data.ml_statistics), cache = store.cache) } else Nil, domain = ml_statistics_domain, heading = session_name + print_version(isabelle_version, afp_version, chapter)) val entry = Entry( chapter = chapter, pull_date = res.date(Build_Log.Data.pull_date(afp = false)), afp_pull_date = if (afp) res.get_date(Build_Log.Data.pull_date(afp = true)) else None, isabelle_version = isabelle_version, afp_version = afp_version, timing = res.timing( Build_Log.Data.timing_elapsed, Build_Log.Data.timing_cpu, Build_Log.Data.timing_gc), ml_timing = res.timing( Build_Log.Data.ml_timing_elapsed, Build_Log.Data.ml_timing_cpu, Build_Log.Data.ml_timing_gc), maximum_code = ml_stats.maximum(ML_Statistics.CODE_SIZE).toLong, average_code = ml_stats.average(ML_Statistics.CODE_SIZE).toLong, maximum_stack = ml_stats.maximum(ML_Statistics.STACK_SIZE).toLong, average_stack = ml_stats.average(ML_Statistics.STACK_SIZE).toLong, maximum_heap = ml_stats.maximum(ML_Statistics.HEAP_SIZE).toLong, average_heap = ml_stats.average(ML_Statistics.HEAP_SIZE).toLong, stored_heap = ML_Statistics.mem_scale(res.long(Build_Log.Data.heap_size)), status = Build_Log.Session_Status.withName(res.string(Build_Log.Data.status)), errors = Build_Log.uncompress_errors( res.bytes(Build_Log.Data.errors), cache = store.cache)) val sessions = data_entries.getOrElse(data_name, Map.empty) val session = sessions.get(session_name) match { case None => Session(session_name, threads, List(entry), ml_stats, entry.date) case Some(old) => val (ml_stats1, ml_stats1_date) = if (entry.date > old.ml_statistics_date) (ml_stats, entry.date) else (old.ml_statistics, old.ml_statistics_date) Session(session_name, threads, entry :: old.entries, ml_stats1, ml_stats1_date) } if ((!afp || chapter == AFP.chapter) && (!profile.bulky || groups.exists(AFP.groups_bulky.toSet))) { data_entries += (data_name -> (sessions + (session_name -> session))) } } }) } }) val sorted_entries = (for { (name, sessions) <- data_entries.toList sorted_sessions <- proper_list(sessions.toList.map(_._2).sortBy(_.order)) } yield { val hosts = get_hosts(name).toList.sorted val stretch = data_stretch(name) Data_Entry(name, hosts, stretch, sorted_sessions) }).sortBy(_.name) Data(date, sorted_entries) } /* present data */ def present_data(data: Data, progress: Progress = new Progress, target_dir: Path = default_target_dir, image_size: (Int, Int) = default_image_size): Unit = { def clean_name(name: String): String = name.flatMap(c => if (c == ' ' || c == '/') "_" else if (c == ',') "" else c.toString) HTML.write_document(target_dir, "index.html", List(HTML.title("Isabelle build status")), List(HTML.chapter("Isabelle build status"), HTML.par( List(HTML.description( List(HTML.text("status date:") -> HTML.text(data.date.toString))))), HTML.par( List(HTML.itemize(data.entries.map({ case data_entry => List( HTML.link(clean_name(data_entry.name) + "/index.html", HTML.text(data_entry.name))) ::: (data_entry.failed_sessions match { case Nil => Nil case sessions => HTML.break ::: List(HTML.span(HTML.error_message, HTML.text("Failed sessions:"))) ::: List(HTML.itemize(sessions.map(s => s.head.present_errors(s.name)))) }) })))))) for (data_entry <- data.entries) { val data_name = data_entry.name val (image_width, image_height) = image_size val image_width_stretch = (image_width * data_entry.stretch).toInt progress.echo("output " + quote(data_name)) val dir = Isabelle_System.make_directory(target_dir + Path.basic(clean_name(data_name))) val data_files = (for (session <- data_entry.sessions) yield { val csv_file = session.make_csv csv_file.write(dir) session.name -> csv_file }).toMap val session_plots = Par_List.map((session: Session) => Isabelle_System.with_tmp_file(session.name, "data") { data_file => Isabelle_System.with_tmp_file(session.name, "gnuplot") { gnuplot_file => def plot_name(kind: String): String = session.name + "_" + kind + ".png" File.write(data_file, cat_lines( session.finished_entries.map(entry => - List(entry.date, - entry.timing.elapsed.minutes, - entry.timing.resources.minutes, - entry.ml_timing.elapsed.minutes, - entry.ml_timing.resources.minutes, - entry.maximum_code, - entry.maximum_code, - entry.average_stack, - entry.maximum_stack, - entry.average_heap, - entry.average_heap, - entry.stored_heap).mkString(" ")))) + List(entry.date.toString, + entry.timing.elapsed.minutes.toString, + entry.timing.resources.minutes.toString, + entry.ml_timing.elapsed.minutes.toString, + entry.ml_timing.resources.minutes.toString, + entry.maximum_code.toString, + entry.maximum_code.toString, + entry.average_stack.toString, + entry.maximum_stack.toString, + entry.average_heap.toString, + entry.average_heap.toString, + entry.stored_heap.toString).mkString(" ")))) val max_time = ((0.0 /: session.finished_entries){ case (m, entry) => m.max(entry.timing.elapsed.minutes). max(entry.timing.resources.minutes). max(entry.ml_timing.elapsed.minutes). max(entry.ml_timing.resources.minutes) } max 0.1) * 1.1 val timing_range = "[0:" + max_time + "]" def gnuplot(plot_name: String, plots: List[String], range: String): Image = { val image = Image(plot_name, image_width_stretch, image_height) File.write(gnuplot_file, """ set terminal png size """ + image.width + "," + image.height + """ set output """ + quote(File.standard_path(dir + image.path)) + """ set xdata time set timefmt "%s" set format x "%d-%b" set xlabel """ + quote(session.name) + """ noenhanced set key left bottom plot [] """ + range + " " + plots.map(s => quote(data_file.implode) + " " + s).mkString(", ") + "\n") val result = Isabelle_System.bash("\"$ISABELLE_GNUPLOT\" " + File.bash_path(gnuplot_file)) if (!result.ok) result.error("Gnuplot failed for " + data_name + "/" + plot_name).check image } val timing_plots = { val plots1 = List( """ using 1:2 smooth sbezier title "elapsed time (smooth)" """, """ using 1:2 smooth csplines title "elapsed time" """) val plots2 = List( """ using 1:3 smooth sbezier title "cpu time (smooth)" """, """ using 1:3 smooth csplines title "cpu time" """) if (session.threads == 1) plots1 else plots1 ::: plots2 } val ml_timing_plots = List( """ using 1:4 smooth sbezier title "ML elapsed time (smooth)" """, """ using 1:4 smooth csplines title "ML elapsed time" """, """ using 1:5 smooth sbezier title "ML cpu time (smooth)" """, """ using 1:5 smooth csplines title "ML cpu time" """) val heap_plots = List( """ using 1:10 smooth sbezier title "heap maximum (smooth)" """, """ using 1:10 smooth csplines title "heap maximum" """, """ using 1:11 smooth sbezier title "heap average (smooth)" """, """ using 1:11 smooth csplines title "heap average" """, """ using 1:12 smooth sbezier title "heap stored (smooth)" """, """ using 1:12 smooth csplines title "heap stored" """) def jfreechart(plot_name: String, fields: ML_Statistics.Fields): Image = { val image = Image(plot_name, image_width, image_height) val chart = session.ml_statistics.chart( fields._1 + ": " + session.ml_statistics.heading, fields._2) Graphics_File.write_chart_png( (dir + image.path).file, chart, image.width, image.height) image } val images = (if (session.check_timing) List( gnuplot(plot_name("timing"), timing_plots, timing_range), gnuplot(plot_name("ml_timing"), ml_timing_plots, timing_range)) else Nil) ::: (if (session.check_heap) List(gnuplot(plot_name("heap"), heap_plots, "[0:]")) else Nil) ::: (if (session.ml_statistics.content.nonEmpty) List(jfreechart(plot_name("heap_chart"), ML_Statistics.heap_fields), jfreechart(plot_name("program_chart"), ML_Statistics.program_fields)) ::: (if (session.threads > 1) List( jfreechart(plot_name("tasks_chart"), ML_Statistics.tasks_fields), jfreechart(plot_name("workers_chart"), ML_Statistics.workers_fields)) else Nil) else Nil) session.name -> images } }, data_entry.sessions).toMap HTML.write_document(dir, "index.html", List(HTML.title("Isabelle build status for " + data_name)), HTML.chapter("Isabelle build status for " + data_name) :: HTML.par( List(HTML.description( List( HTML.text("status date:") -> HTML.text(data.date.toString), HTML.text("build host:") -> HTML.text(commas(data_entry.hosts)))))) :: HTML.par( List(HTML.itemize( data_entry.sessions.map(session => HTML.link("#session_" + session.name, HTML.text(session.name)) :: HTML.text(" (" + session.head.timing.message_resources + ")"))))) :: data_entry.sessions.flatMap(session => List( HTML.section(HTML.id("session_" + session.name), session.name), HTML.par( HTML.description( List( HTML.text("data:") -> List(HTML.link(data_files(session.name).file_name, HTML.text("CSV"))), HTML.text("timing:") -> HTML.text(session.head.timing.message_resources), HTML.text("ML timing:") -> HTML.text(session.head.ml_timing.message_resources)) ::: ML_Statistics.mem_print(session.head.maximum_code).map(s => HTML.text("code maximum:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.average_code).map(s => HTML.text("code average:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.maximum_stack).map(s => HTML.text("stack maximum:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.average_stack).map(s => HTML.text("stack average:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.maximum_heap).map(s => HTML.text("heap maximum:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.average_heap).map(s => HTML.text("heap average:") -> HTML.text(s)).toList ::: ML_Statistics.mem_print(session.head.stored_heap).map(s => HTML.text("heap stored:") -> HTML.text(s)).toList ::: proper_string(session.head.isabelle_version).map(s => HTML.text("Isabelle version:") -> HTML.text(s)).toList ::: proper_string(session.head.afp_version).map(s => HTML.text("AFP version:") -> HTML.text(s)).toList) :: session_plots.getOrElse(session.name, Nil).map(image => HTML.size(image.width / 2, image.height / 2)(HTML.image(image.name))))))) } } /* Isabelle tool wrapper */ val isabelle_tool = Isabelle_Tool("build_status", "present recent build status information from database", Scala_Project.here, args => { var target_dir = default_target_dir var ml_statistics = false var only_sessions = Set.empty[String] var options = Options.init() var image_size = default_image_size var verbose = false val getopts = Getopts(""" Usage: isabelle build_status [OPTIONS] Options are: -D DIR target directory (default """ + default_target_dir + """) -M include full ML statistics -S SESSIONS only given SESSIONS (comma separated) -l DAYS length of relevant history (default """ + options.int("build_log_history") + """) -o OPTION override Isabelle system OPTION (via NAME=VAL or NAME) -s WxH size of PNG image (default """ + image_size._1 + "x" + image_size._2 + """) -v verbose Present performance statistics from build log database, which is specified via system options build_log_database_host, build_log_database_user, build_log_history etc. """, "D:" -> (arg => target_dir = Path.explode(arg)), "M" -> (_ => ml_statistics = true), "S:" -> (arg => only_sessions = space_explode(',', arg).toSet), "l:" -> (arg => options = options + ("build_log_history=" + arg)), "o:" -> (arg => options = options + arg), "s:" -> (arg => space_explode('x', arg).map(Value.Int.parse(_)) match { case List(w, h) if w > 0 && h > 0 => image_size = (w, h) case _ => error("Error bad PNG image size: " + quote(arg)) }), "v" -> (_ => verbose = true)) val more_args = getopts(args) if (more_args.nonEmpty) getopts.usage() val progress = new Console_Progress build_status(options, progress = progress, only_sessions = only_sessions, verbose = verbose, target_dir = target_dir, ml_statistics = ml_statistics, image_size = image_size) }) } diff --git a/src/Pure/General/graphics_file.scala b/src/Pure/General/graphics_file.scala --- a/src/Pure/General/graphics_file.scala +++ b/src/Pure/General/graphics_file.scala @@ -1,94 +1,94 @@ /* Title: Pure/General/graphics_file.scala Author: Makarius File system operations for Graphics2D output. */ package isabelle import java.io.{FileOutputStream, BufferedOutputStream, File => JFile} import java.awt.Graphics2D import java.awt.geom.Rectangle2D import java.awt.image.BufferedImage import javax.imageio.ImageIO import org.jfree.chart.JFreeChart import com.lowagie.text.pdf.{PdfWriter, BaseFont, FontMapper, DefaultFontMapper} object Graphics_File { /* PNG */ def write_png( file: JFile, paint: Graphics2D => Unit, width: Int, height: Int, dpi: Int = 72): Unit = { val scale = dpi / 72.0f val w = (width * scale).round val h = (height * scale).round val img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val gfx = img.createGraphics try { gfx.scale(scale, scale) paint(gfx) ImageIO.write(img, "png", file) } finally { gfx.dispose } } /* PDF */ private def font_mapper(): FontMapper = { val mapper = new DefaultFontMapper for (entry <- Isabelle_Fonts.fonts()) { val params = new DefaultFontMapper.BaseFontParameters(File.platform_path(entry.path)) params.encoding = BaseFont.IDENTITY_H params.embedded = true params.ttfAfm = entry.bytes.array mapper.putName(entry.name, params) } mapper } def write_pdf(file: JFile, paint: Graphics2D => Unit, width: Int, height: Int): Unit = { import com.lowagie.text.{Document, Rectangle} using(new BufferedOutputStream(new FileOutputStream(file)))(out => { val document = new Document() try { - document.setPageSize(new Rectangle(width, height)) + document.setPageSize(new Rectangle(width.toFloat, height.toFloat)) val writer = PdfWriter.getInstance(document, out) document.open() val cb = writer.getDirectContent() - val tp = cb.createTemplate(width, height) - val gfx = tp.createGraphics(width, height, font_mapper()) + val tp = cb.createTemplate(width.toFloat, height.toFloat) + val gfx = tp.createGraphics(width.toFloat, height.toFloat, font_mapper()) paint(gfx) gfx.dispose cb.addTemplate(tp, 1, 0, 0, 1, 0, 0) } finally { document.close() } }) } /* JFreeChart */ def paint_chart(gfx: Graphics2D, chart: JFreeChart, width: Int, height: Int): Unit = chart.draw(gfx, new Rectangle2D.Double(0, 0, width, height)) def write_chart_png(file: JFile, chart: JFreeChart, width: Int, height: Int): Unit = write_png(file, paint_chart(_, chart, width, height), width, height) def write_chart_pdf(file: JFile, chart: JFreeChart, width: Int, height: Int): Unit = write_pdf(file, paint_chart(_, chart, width, height), width, height) } diff --git a/src/Tools/jEdit/src/font_info.scala b/src/Tools/jEdit/src/font_info.scala --- a/src/Tools/jEdit/src/font_info.scala +++ b/src/Tools/jEdit/src/font_info.scala @@ -1,99 +1,99 @@ /* Title: Tools/jEdit/src/font_info.scala Author: Makarius Font information, derived from main jEdit view font. */ package isabelle.jedit import isabelle._ import java.awt.Font import org.gjt.sp.jedit.{jEdit, View} object Font_Info { /* size range */ val min_size = 5 val max_size = 250 - def restrict_size(size: Float): Float = size max min_size min max_size + def restrict_size(size: Float): Float = size max min_size.toFloat min max_size.toFloat /* main jEdit font */ def main_family(): String = jEdit.getProperty("view.font") def main_size(scale: Double = 1.0): Float = restrict_size(jEdit.getIntegerProperty("view.fontsize", 16).toFloat * scale.toFloat) def main(scale: Double = 1.0): Font_Info = Font_Info(main_family(), main_size(scale)) /* incremental size change */ object main_change { private def change_size(change: Float => Float): Unit = { GUI_Thread.require {} val size0 = main_size() val size = restrict_size(change(size0)).round if (size != size0) { jEdit.setIntegerProperty("view.fontsize", size) jEdit.propertiesChanged() jEdit.saveSettings() jEdit.getActiveView().getStatus.setMessageAndClear("Text font size: " + size) } } // owned by GUI thread private var steps = 0 private val delay = Delay.last(PIDE.options.seconds("editor_input_delay"), gui = true) { change_size(size => { var i = size.round while (steps != 0 && i > 0) { if (steps > 0) { i += (i / 10) max 1; steps -= 1 } else { i -= (i / 10) max 1; steps += 1 } } steps = 0 i.toFloat }) } def step(i: Int): Unit = { steps += i delay.invoke() } def reset(size: Float): Unit = { delay.revoke() steps = 0 change_size(_ => size) } } /* zoom box */ abstract class Zoom_Box extends GUI.Zoom_Box { tooltip = "Zoom factor for output font size" } } sealed case class Font_Info(family: String, size: Float) { def font: Font = new Font(family, Font.PLAIN, size.round) } diff --git a/src/Tools/jEdit/src/rich_text_area.scala b/src/Tools/jEdit/src/rich_text_area.scala --- a/src/Tools/jEdit/src/rich_text_area.scala +++ b/src/Tools/jEdit/src/rich_text_area.scala @@ -1,731 +1,732 @@ /* Title: Tools/jEdit/src/rich_text_area.scala Author: Makarius Enhanced version of jEdit text area, with rich text rendering, tooltips, hyperlinks etc. */ package isabelle.jedit import isabelle._ import java.awt.{Graphics2D, Shape, Color, Point, Cursor, MouseInfo} import java.awt.event.{MouseMotionAdapter, MouseAdapter, MouseEvent, FocusAdapter, FocusEvent, WindowEvent, WindowAdapter, KeyEvent} import java.awt.font.TextAttribute import javax.swing.SwingUtilities import java.text.AttributedString import scala.util.matching.Regex import org.gjt.sp.util.Log import org.gjt.sp.jedit.View import org.gjt.sp.jedit.syntax.Chunk import org.gjt.sp.jedit.textarea.{TextAreaExtension, TextAreaPainter, TextArea} class Rich_Text_Area( view: View, text_area: TextArea, get_rendering: () => JEdit_Rendering, close_action: () => Unit, get_search_pattern: () => Option[Regex], caret_update: () => Unit, caret_visible: Boolean, enable_hovering: Boolean) { private val buffer = text_area.getBuffer /* robust extension body */ def check_robust_body: Boolean = GUI_Thread.require { buffer == text_area.getBuffer } def robust_body[A](default: A)(body: => A): A = { try { if (check_robust_body) body else { Log.log(Log.ERROR, this, ERROR("Implicit change of text area buffer")) default } } catch { case exn: Throwable => Log.log(Log.ERROR, this, exn); default } } /* original painters */ private def pick_extension(name: String): TextAreaExtension = { text_area.getPainter.getExtensions.iterator.filter(x => x.getClass.getName == name).toList match { case List(x) => x case _ => error("Expected exactly one " + name) } } private val orig_text_painter = pick_extension("org.gjt.sp.jedit.textarea.TextAreaPainter$PaintText") /* caret focus modifier */ @volatile private var caret_focus_modifier = false def caret_focus_range: Text.Range = if (caret_focus_modifier) Text.Range.full else JEdit_Lib.visible_range(text_area) getOrElse Text.Range.offside private val key_listener = JEdit_Lib.key_listener( key_pressed = (evt: KeyEvent) => { val mod = PIDE.options.string("jedit_focus_modifier") val old = caret_focus_modifier caret_focus_modifier = (mod.nonEmpty && mod == JEdit_Lib.modifier_string(evt)) if (caret_focus_modifier != old) caret_update() }, key_released = _ => { if (caret_focus_modifier) { caret_focus_modifier = false caret_update() } }) /* common painter state */ @volatile private var painter_rendering: JEdit_Rendering = null @volatile private var painter_clip: Shape = null @volatile private var caret_focus = Rendering.Focus.empty private val set_state = new TextAreaExtension { override def paintScreenLineRange(gfx: Graphics2D, first_line: Int, last_line: Int, physical_lines: Array[Int], start: Array[Int], end: Array[Int], y: Int, line_height: Int): Unit = { painter_rendering = get_rendering() painter_clip = gfx.getClip caret_focus = if (caret_enabled && !painter_rendering.snapshot.is_outdated) { painter_rendering.caret_focus(JEdit_Lib.caret_range(text_area), caret_focus_range) } else Rendering.Focus.empty } } private val reset_state = new TextAreaExtension { override def paintScreenLineRange(gfx: Graphics2D, first_line: Int, last_line: Int, physical_lines: Array[Int], start: Array[Int], end: Array[Int], y: Int, line_height: Int): Unit = { painter_rendering = null painter_clip = null caret_focus = Rendering.Focus.empty } } def robust_rendering(body: JEdit_Rendering => Unit): Unit = { robust_body(()) { body(painter_rendering) } } /* active areas within the text */ private class Active_Area[A]( rendering: JEdit_Rendering => Text.Range => Option[Text.Info[A]], cursor: Option[Int]) { private var the_text_info: Option[(String, Text.Info[A])] = None def is_active: Boolean = the_text_info.isDefined def text_info: Option[(String, Text.Info[A])] = the_text_info def info: Option[Text.Info[A]] = the_text_info.map(_._2) def update(new_info: Option[Text.Info[A]]): Unit = { val old_text_info = the_text_info val new_text_info = new_info.map(info => (text_area.getText(info.range.start, info.range.length), info)) if (new_text_info != old_text_info) { caret_update() if (cursor.isDefined) { if (new_text_info.isDefined) text_area.getPainter.setCursor(Cursor.getPredefinedCursor(cursor.get)) else text_area.getPainter.resetCursor() } for { r0 <- JEdit_Lib.visible_range(text_area) opt <- List(old_text_info, new_text_info) (_, Text.Info(r1, _)) <- opt r2 <- r1.try_restrict(r0) // FIXME more precise?! } JEdit_Lib.invalidate_range(text_area, r2) the_text_info = new_text_info } } def update_rendering(r: JEdit_Rendering, range: Text.Range): Unit = update(rendering(r)(range)) def reset: Unit = update(None) } // owned by GUI thread private val highlight_area = new Active_Area[Color]( (rendering: JEdit_Rendering) => rendering.highlight, None) private val hyperlink_area = new Active_Area[PIDE.editor.Hyperlink]( (rendering: JEdit_Rendering) => rendering.hyperlink, Some(Cursor.HAND_CURSOR)) private val active_area = new Active_Area[XML.Elem]( (rendering: JEdit_Rendering) => rendering.active, Some(Cursor.DEFAULT_CURSOR)) private val active_areas = List((highlight_area, true), (hyperlink_area, true), (active_area, false)) def active_reset(): Unit = active_areas.foreach(_._1.reset) private def area_active(): Boolean = active_areas.exists({ case (area, _) => area.is_active }) private val focus_listener = new FocusAdapter { override def focusLost(e: FocusEvent): Unit = { robust_body(()) { active_reset() } } } private val window_listener = new WindowAdapter { override def windowIconified(e: WindowEvent): Unit = { robust_body(()) { active_reset() } } override def windowDeactivated(e: WindowEvent): Unit = { robust_body(()) { active_reset() } } } private val mouse_listener = new MouseAdapter { override def mouseClicked(e: MouseEvent): Unit = { robust_body(()) { hyperlink_area.info match { case Some(Text.Info(range, link)) => if (!link.external) { try { text_area.moveCaretPosition(range.start) } catch { case _: ArrayIndexOutOfBoundsException => case _: IllegalArgumentException => } text_area.requestFocus } link.follow(view) case None => } active_area.text_info match { case Some((text, Text.Info(_, markup))) => Active.action(view, text, markup) close_action() case None => } } } } private def mouse_inside_painter(): Boolean = MouseInfo.getPointerInfo match { case null => false case info => val point = info.getLocation val painter = text_area.getPainter SwingUtilities.convertPointFromScreen(point, painter) painter.contains(point) } private val mouse_motion_listener = new MouseMotionAdapter { override def mouseDragged(evt: MouseEvent): Unit = { robust_body(()) { active_reset() Completion_Popup.Text_Area.dismissed(text_area) Pretty_Tooltip.dismiss_descendant(text_area.getPainter) } } override def mouseMoved(evt: MouseEvent): Unit = { robust_body(()) { val x = evt.getX val y = evt.getY val control = JEdit_Lib.command_modifier(evt) if ((control || enable_hovering) && !buffer.isLoading) { JEdit_Lib.buffer_lock(buffer) { JEdit_Lib.pixel_range(text_area, x, y) match { case None => active_reset() case Some(range) => val rendering = get_rendering() for ((area, require_control) <- active_areas) { if (control == require_control && !rendering.snapshot.is_outdated) area.update_rendering(rendering, range) else area.reset } } } } else active_reset() if (evt.getSource == text_area.getPainter) { Pretty_Tooltip.invoke(() => robust_body(()) { if (mouse_inside_painter()) { val rendering = get_rendering() val snapshot = rendering.snapshot if (!snapshot.is_outdated) { JEdit_Lib.pixel_range(text_area, x, y) match { case None => case Some(range) => rendering.tooltip(range, control) match { case None => case Some(tip) => val painter = text_area.getPainter val loc = new Point(x, y + painter.getLineHeight / 2) val results = snapshot.command_results(tip.range) Pretty_Tooltip(view, painter, loc, rendering, results, tip) } } } } }) } } } } /* text background */ private val background_painter = new TextAreaExtension { override def paintScreenLineRange(gfx: Graphics2D, first_line: Int, last_line: Int, physical_lines: Array[Int], start: Array[Int], end: Array[Int], y: Int, line_height: Int): Unit = { robust_rendering { rendering => val fm = text_area.getPainter.getFontMetrics for (i <- physical_lines.indices) { if (physical_lines(i) != -1) { val line_range = Text.Range(start(i), end(i) min buffer.getLength) // line background color for { (c, separator) <- rendering.line_background(line_range) } { gfx.setColor(rendering.color(c)) val sep = if (separator) 2 min (line_height / 2) else 0 gfx.fillRect(0, y + i * line_height, text_area.getWidth, line_height - sep) } // background color for { Text.Info(range, c) <- rendering.background(Rendering.background_elements, line_range, caret_focus) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.color(c)) gfx.fillRect(r.x, y + i * line_height, r.length, line_height) } // active area -- potentially from other snapshot for { info <- active_area.info Text.Info(range, _) <- info.try_restrict(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.active_hover_color) gfx.fillRect(r.x, y + i * line_height, r.length, line_height) } // squiggly underline for { Text.Info(range, c) <- rendering.squiggly_underline(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.color(c)) val x0 = (r.x / 2) * 2 val y0 = r.y + fm.getAscent + 1 for (x1 <- Range(x0, x0 + r.length, 2)) { val y1 = if (x1 % 4 < 2) y0 else y0 + 1 gfx.drawLine(x1, y1, x1 + 1, y1) } } // spell checker for { spell_checker <- PIDE.plugin.spell_checker.get spell <- rendering.spell_checker(line_range) text <- JEdit_Lib.get_text(buffer, spell.range) info <- spell_checker.marked_words(spell.range.start, text) r <- JEdit_Lib.gfx_range(text_area, info.range) } { gfx.setColor(rendering.spell_checker_color) val y0 = r.y + ((fm.getAscent + 4) min (line_height - 2)) gfx.drawLine(r.x, y0, r.x + r.length, y0) } } } } } } /* text */ private def caret_enabled: Boolean = caret_visible && (!text_area.hasFocus || text_area.isCaretVisible) private def caret_color(rendering: JEdit_Rendering, offset: Text.Offset): Color = { if (text_area.isCaretVisible) text_area.getPainter.getCaretColor else { val debug_positions = (for { c <- PIDE.session.debugger.focus().iterator pos <- c.debug_position.iterator } yield pos).toList if (debug_positions.exists(PIDE.editor.is_hyperlink_position(rendering.snapshot, offset, _))) rendering.caret_debugger_color else rendering.caret_invisible_color } } private def paint_chunk_list(rendering: JEdit_Rendering, gfx: Graphics2D, line_start: Text.Offset, head: Chunk, x: Float, y: Float): Float = { val clip_rect = gfx.getClipBounds val painter = text_area.getPainter val font_context = painter.getFontRenderContext val caret_range = if (caret_enabled) JEdit_Lib.caret_range(text_area) else Text.Range.offside var w = 0.0f var chunk = head while (chunk != null) { val chunk_offset = line_start + chunk.offset if (x + w + chunk.width > clip_rect.x && x + w < clip_rect.x + clip_rect.width && chunk.length > 0) { val chunk_range = Text.Range(chunk_offset, chunk_offset + chunk.length) val chunk_str = if (chunk.chars == null) Symbol.spaces(chunk.length) else { if (chunk.str == null) { chunk.str = new String(chunk.chars) } chunk.str } val chunk_font = chunk.style.getFont val chunk_color = chunk.style.getForegroundColor def string_width(s: String): Float = if (s.isEmpty) 0.0f else chunk_font.getStringBounds(s, font_context).getWidth.toFloat val markup = for { r1 <- rendering.text_color(chunk_range, chunk_color) r2 <- r1.try_restrict(chunk_range) } yield r2 val padded_markup_iterator = if (markup.isEmpty) Iterator(Text.Info(chunk_range, chunk_color)) else Iterator( Text.Info(Text.Range(chunk_range.start, markup.head.range.start), chunk_color)) ++ markup.iterator ++ Iterator(Text.Info(Text.Range(markup.last.range.stop, chunk_range.stop), chunk_color)) var x1 = x + w gfx.setFont(chunk_font) for (Text.Info(range, color) <- padded_markup_iterator if !range.is_singularity) { val str = chunk_str.substring(range.start - chunk_offset, range.stop - chunk_offset) gfx.setColor(color) range.try_restrict(caret_range) match { case Some(r) if !r.is_singularity => val i = r.start - range.start val j = r.stop - range.start val s1 = str.substring(0, i) val s2 = str.substring(i, j) val s3 = str.substring(j) if (s1.nonEmpty) gfx.drawString(Word.bidi_override(s1), x1, y) val astr = new AttributedString(Word.bidi_override(s2)) astr.addAttribute(TextAttribute.FONT, chunk_font) astr.addAttribute(TextAttribute.FOREGROUND, caret_color(rendering, r.start)) astr.addAttribute(TextAttribute.SWAP_COLORS, TextAttribute.SWAP_COLORS_ON) gfx.drawString(astr.getIterator, x1 + string_width(s1), y) if (s3.nonEmpty) gfx.drawString(Word.bidi_override(s3), x1 + string_width(str.substring(0, j)), y) case _ => gfx.drawString(Word.bidi_override(str), x1, y) } x1 += string_width(str) } } w += chunk.width chunk = chunk.next.asInstanceOf[Chunk] } w } private val text_painter = new TextAreaExtension { override def paintScreenLineRange(gfx: Graphics2D, first_line: Int, last_line: Int, physical_lines: Array[Int], start: Array[Int], end: Array[Int], y: Int, line_height: Int): Unit = { robust_rendering { rendering => val painter = text_area.getPainter val fm = painter.getFontMetrics val lm = painter.getFont.getLineMetrics(" ", painter.getFontRenderContext) val clip = gfx.getClip val x0 = text_area.getHorizontalOffset var y0 = y + painter.getLineHeight - (fm.getLeading + 1) - fm.getDescent val (bullet_x, bullet_y, bullet_w, bullet_h) = { val w = fm.charWidth(' ') val b = (w / 2) max 1 val c = (lm.getAscent + lm.getStrikethroughOffset).round.toInt ((w - b + 1) / 2, c - b / 2, w - b, line_height - b) } for (i <- physical_lines.indices) { val line = physical_lines(i) if (line != -1) { val line_range = Text.Range(start(i), end(i) min buffer.getLength) // text chunks val screen_line = first_line + i val chunks = text_area.getChunksOfScreenLine(screen_line) if (chunks != null) { try { val line_start = buffer.getLineStartOffset(line) gfx.clipRect(x0, y + line_height * i, Integer.MAX_VALUE, line_height) - val w = paint_chunk_list(rendering, gfx, line_start, chunks, x0, y0).toInt + val w = + paint_chunk_list(rendering, gfx, line_start, chunks, x0.toFloat, y0.toFloat).toInt gfx.clipRect(x0 + w.toInt, 0, Integer.MAX_VALUE, Integer.MAX_VALUE) orig_text_painter.paintValidLine(gfx, screen_line, line, start(i), end(i), y + line_height * i) } finally { gfx.setClip(clip) } } // bullet bar for { Text.Info(range, color) <- rendering.bullet(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(color) gfx.fillRect(r.x + bullet_x, y + i * line_height + bullet_y, r.length - bullet_w, line_height - bullet_h) } } y0 += line_height } } } } /* foreground */ private val foreground_painter = new TextAreaExtension { override def paintScreenLineRange(gfx: Graphics2D, first_line: Int, last_line: Int, physical_lines: Array[Int], start: Array[Int], end: Array[Int], y: Int, line_height: Int): Unit = { robust_rendering { rendering => val search_pattern = get_search_pattern() for (i <- physical_lines.indices) { if (physical_lines(i) != -1) { val line_range = Text.Range(start(i), end(i) min buffer.getLength) // foreground color for { Text.Info(range, c) <- rendering.foreground(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.color(c)) gfx.fillRect(r.x, y + i * line_height, r.length, line_height) } // search pattern for { regex <- search_pattern text <- JEdit_Lib.get_text(buffer, line_range) m <- regex.findAllMatchIn(text) range = Text.Range(m.start, m.end) + line_range.start r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.search_color) gfx.fillRect(r.x, y + i * line_height, r.length, line_height) } // highlight range -- potentially from other snapshot for { info <- highlight_area.info Text.Info(range, color) <- info.try_restrict(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(color) gfx.fillRect(r.x, y + i * line_height, r.length, line_height) } // hyperlink range -- potentially from other snapshot for { info <- hyperlink_area.info Text.Info(range, _) <- info.try_restrict(line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(rendering.hyperlink_color) gfx.drawRect(r.x, y + i * line_height, r.length - 1, line_height - 1) } // entity def range if (!area_active() && caret_visible) { for { Text.Info(range, color) <- rendering.entity_ref(line_range, caret_focus) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(color) gfx.drawRect(r.x, y + i * line_height, r.length - 1, line_height - 1) } } // completion range if (!area_active() && caret_visible) { for { completion <- Completion_Popup.Text_Area(text_area) Text.Info(range, color) <- completion.rendering(rendering, line_range) r <- JEdit_Lib.gfx_range(text_area, range) } { gfx.setColor(color) gfx.drawRect(r.x, y + i * line_height, r.length - 1, line_height - 1) } } } } } } } /* caret -- outside of text range */ private class Caret_Painter(before: Boolean) extends TextAreaExtension { override def paintValidLine(gfx: Graphics2D, screen_line: Int, physical_line: Int, start: Int, end: Int, y: Int): Unit = { robust_rendering { _ => if (before) gfx.clipRect(0, 0, 0, 0) else gfx.setClip(painter_clip) } } } private val before_caret_painter1 = new Caret_Painter(true) private val after_caret_painter1 = new Caret_Painter(false) private val before_caret_painter2 = new Caret_Painter(true) private val after_caret_painter2 = new Caret_Painter(false) private val caret_painter = new TextAreaExtension { override def paintValidLine(gfx: Graphics2D, screen_line: Int, physical_line: Int, start: Int, end: Int, y: Int): Unit = { robust_rendering { rendering => if (caret_visible) { val caret = text_area.getCaretPosition if (caret_enabled && start <= caret && caret == end - 1) { val painter = text_area.getPainter val fm = painter.getFontMetrics val offset = caret - text_area.getLineStartOffset(physical_line) val x = text_area.offsetToXY(physical_line, offset).x val y1 = y + painter.getLineHeight - (fm.getLeading + 1) - fm.getDescent val astr = new AttributedString(" ") astr.addAttribute(TextAttribute.FONT, painter.getFont) astr.addAttribute(TextAttribute.FOREGROUND, caret_color(rendering, caret)) astr.addAttribute(TextAttribute.SWAP_COLORS, TextAttribute.SWAP_COLORS_ON) val clip = gfx.getClip try { gfx.clipRect(x, y, Integer.MAX_VALUE, painter.getLineHeight) gfx.drawString(astr.getIterator, x, y1) } finally { gfx.setClip(clip) } } } } } } /* activation */ def activate(): Unit = { val painter = text_area.getPainter painter.addExtension(TextAreaPainter.LOWEST_LAYER, set_state) painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, background_painter) painter.addExtension(TextAreaPainter.TEXT_LAYER, text_painter) painter.addExtension(TextAreaPainter.CARET_LAYER - 1, before_caret_painter1) painter.addExtension(TextAreaPainter.CARET_LAYER + 1, after_caret_painter1) painter.addExtension(TextAreaPainter.BLOCK_CARET_LAYER - 1, before_caret_painter2) painter.addExtension(TextAreaPainter.BLOCK_CARET_LAYER + 1, after_caret_painter2) painter.addExtension(TextAreaPainter.BLOCK_CARET_LAYER + 2, caret_painter) painter.addExtension(500, foreground_painter) painter.addExtension(TextAreaPainter.HIGHEST_LAYER, reset_state) painter.removeExtension(orig_text_painter) painter.addMouseListener(mouse_listener) painter.addMouseMotionListener(mouse_motion_listener) text_area.addKeyListener(key_listener) text_area.addFocusListener(focus_listener) view.addWindowListener(window_listener) } def deactivate(): Unit = { active_reset() val painter = text_area.getPainter view.removeWindowListener(window_listener) text_area.removeFocusListener(focus_listener) text_area.removeKeyListener(key_listener) painter.removeMouseMotionListener(mouse_motion_listener) painter.removeMouseListener(mouse_listener) painter.addExtension(TextAreaPainter.TEXT_LAYER, orig_text_painter) painter.removeExtension(reset_state) painter.removeExtension(foreground_painter) painter.removeExtension(caret_painter) painter.removeExtension(after_caret_painter2) painter.removeExtension(before_caret_painter2) painter.removeExtension(after_caret_painter1) painter.removeExtension(before_caret_painter1) painter.removeExtension(text_painter) painter.removeExtension(background_painter) painter.removeExtension(set_state) } }