src/Tools/jEdit/src/pretty_text_area.scala
author wenzelm
Wed Jul 23 11:19:24 2014 +0200 (2014-07-23)
changeset 57612 990ffb84489b
parent 57042 5576d22abf3c
child 58766 5bab56d3dcd4
permissions -rw-r--r--
clarified module name: facilitate alternative GUI frameworks;
     1 /*  Title:      Tools/jEdit/src/pretty_text_area.scala
     2     Author:     Makarius
     3 
     4 GUI component for pretty-printed text with markup, rendered like jEdit
     5 text area.
     6 */
     7 
     8 package isabelle.jedit
     9 
    10 
    11 import isabelle._
    12 
    13 import java.awt.{Color, Font, FontMetrics, Toolkit, Window}
    14 import java.awt.event.KeyEvent
    15 import javax.swing.JTextField
    16 import javax.swing.event.{DocumentListener, DocumentEvent}
    17 
    18 import java.util.concurrent.{Future => JFuture}
    19 
    20 import scala.swing.{Label, Component}
    21 import scala.util.matching.Regex
    22 
    23 import org.gjt.sp.jedit.{jEdit, View, Registers}
    24 import org.gjt.sp.jedit.textarea.{AntiAlias, JEditEmbeddedTextArea}
    25 import org.gjt.sp.jedit.syntax.SyntaxStyle
    26 import org.gjt.sp.util.{SyntaxUtilities, Log}
    27 
    28 
    29 object Pretty_Text_Area
    30 {
    31   /* auxiliary */
    32 
    33   private def document_state(base_snapshot: Document.Snapshot, base_results: Command.Results,
    34     formatted_body: XML.Body): (String, Document.State) =
    35   {
    36     val command = Command.rich_text(Document_ID.make(), base_results, formatted_body)
    37     val node_name = command.node_name
    38     val edits: List[Document.Edit_Text] =
    39       List(node_name -> Document.Node.Edits(List(Text.Edit.insert(0, command.source))))
    40 
    41     val state0 = base_snapshot.state.define_command(command)
    42     val version0 = base_snapshot.version
    43     val nodes0 = version0.nodes
    44 
    45     val nodes1 = nodes0 + (node_name -> nodes0(node_name).update_commands(Linear_Set(command)))
    46     val version1 = Document.Version.make(version0.syntax, nodes1)
    47     val state1 =
    48       state0.continue_history(Future.value(version0), edits, Future.value(version1))
    49         .define_version(version1, state0.the_assignment(version0))
    50         .assign(version1.id, List(command.id -> List(Document_ID.make())))._2
    51 
    52     (command.source, state1)
    53   }
    54 
    55   private def text_rendering(base_snapshot: Document.Snapshot, base_results: Command.Results,
    56     formatted_body: XML.Body): (String, Rendering) =
    57   {
    58     val (text, state) = document_state(base_snapshot, base_results, formatted_body)
    59     val rendering = Rendering(state.snapshot(), PIDE.options.value)
    60     (text, rendering)
    61   }
    62 }
    63 
    64 class Pretty_Text_Area(
    65   view: View,
    66   close_action: () => Unit = () => (),
    67   propagate_keys: Boolean = false) extends JEditEmbeddedTextArea
    68 {
    69   text_area =>
    70 
    71   GUI_Thread.require {}
    72 
    73   private var current_font_info: Font_Info = Font_Info.main()
    74   private var current_body: XML.Body = Nil
    75   private var current_base_snapshot = Document.Snapshot.init
    76   private var current_base_results = Command.Results.empty
    77   private var current_rendering: Rendering =
    78     Pretty_Text_Area.text_rendering(current_base_snapshot, current_base_results, Nil)._2
    79   private var future_rendering: Option[JFuture[Unit]] = None
    80 
    81   private val rich_text_area =
    82     new Rich_Text_Area(view, text_area, () => current_rendering, close_action,
    83       get_search_pattern _, caret_visible = false, enable_hovering = true)
    84 
    85   private var current_search_pattern: Option[Regex] = None
    86   def get_search_pattern(): Option[Regex] = GUI_Thread.require { current_search_pattern }
    87 
    88   def get_background(): Option[Color] = None
    89 
    90   def refresh()
    91   {
    92     GUI_Thread.require {}
    93 
    94     val font = current_font_info.font
    95     getPainter.setFont(font)
    96     getPainter.setAntiAlias(new AntiAlias(jEdit.getProperty("view.antiAlias")))
    97     getPainter.setFractionalFontMetricsEnabled(jEdit.getBooleanProperty("view.fracFontMetrics"))
    98     getPainter.setStyles(
    99       SyntaxUtilities.loadStyles(current_font_info.family, current_font_info.size.round))
   100     getPainter.setLineExtraSpacing(jEdit.getIntegerProperty("options.textarea.lineSpacing", 0))
   101 
   102     val fold_line_style = new Array[SyntaxStyle](4)
   103     for (i <- 0 to 3) {
   104       fold_line_style(i) =
   105         SyntaxUtilities.parseStyle(
   106           jEdit.getProperty("view.style.foldLine." + i),
   107           current_font_info.family, current_font_info.size.round, true)
   108     }
   109     getPainter.setFoldLineStyle(fold_line_style)
   110 
   111     getGutter.setForeground(jEdit.getColorProperty("view.gutter.fgColor"))
   112     getGutter.setBackground(jEdit.getColorProperty("view.gutter.bgColor"))
   113     get_background().map(bg => { getPainter.setBackground(bg); getGutter.setBackground(bg) })
   114     getGutter.setHighlightedForeground(jEdit.getColorProperty("view.gutter.highlightColor"))
   115     getGutter.setFoldColor(jEdit.getColorProperty("view.gutter.foldColor"))
   116     getGutter.setFont(jEdit.getFontProperty("view.gutter.font"))
   117     getGutter.setBorder(0,
   118       jEdit.getColorProperty("view.gutter.focusBorderColor"),
   119       jEdit.getColorProperty("view.gutter.noFocusBorderColor"),
   120       getPainter.getBackground)
   121     getGutter.setFoldPainter(getFoldPainter)
   122     getGutter.setGutterEnabled(jEdit.getBooleanProperty("view.gutter.enabled"))
   123 
   124     if (getWidth > 0) {
   125       val metric = JEdit_Lib.pretty_metric(getPainter)
   126       val margin = (getPainter.getWidth.toDouble / metric.unit) max 20.0
   127 
   128       val base_snapshot = current_base_snapshot
   129       val base_results = current_base_results
   130       val formatted_body = Pretty.formatted(current_body, margin, metric)
   131 
   132       future_rendering.map(_.cancel(true))
   133       future_rendering =
   134         Some(Simple_Thread.submit_task {
   135           val (text, rendering) =
   136             try { Pretty_Text_Area.text_rendering(base_snapshot, base_results, formatted_body) }
   137             catch { case exn: Throwable => Log.log(Log.ERROR, this, exn); throw exn }
   138           Exn.Interrupt.expose()
   139 
   140           GUI_Thread.later {
   141             current_rendering = rendering
   142             JEdit_Lib.buffer_edit(getBuffer) {
   143               rich_text_area.active_reset()
   144               getBuffer.setReadOnly(false)
   145               getBuffer.setFoldHandler(new Fold_Handling.Document_Fold_Handler(rendering))
   146               setText(text)
   147               setCaretPosition(0)
   148               getBuffer.setReadOnly(true)
   149             }
   150           }
   151         })
   152     }
   153   }
   154 
   155   def resize(font_info: Font_Info)
   156   {
   157     GUI_Thread.require {}
   158 
   159     current_font_info = font_info
   160     refresh()
   161   }
   162 
   163   def update(base_snapshot: Document.Snapshot, base_results: Command.Results, body: XML.Body)
   164   {
   165     GUI_Thread.require {}
   166     require(!base_snapshot.is_outdated)
   167 
   168     current_base_snapshot = base_snapshot
   169     current_base_results = base_results
   170     current_body = body
   171     refresh()
   172   }
   173 
   174   def detach
   175   {
   176     GUI_Thread.require {}
   177     Info_Dockable(view, current_base_snapshot, current_base_results, current_body)
   178   }
   179 
   180   def detach_operation: Option[() => Unit] =
   181     if (current_body.isEmpty) None else Some(() => detach)
   182 
   183 
   184   /* common GUI components */
   185 
   186   val search_label: Component = new Label("Search:") {
   187     tooltip = "Search and highlight output via regular expression"
   188   }
   189 
   190   val search_field: Component =
   191     Component.wrap(new Completion_Popup.History_Text_Field("isabelle-search")
   192       {
   193         private val input_delay =
   194           GUI_Thread.delay_last(PIDE.options.seconds("editor_input_delay")) {
   195             search_action(this)
   196           }
   197         getDocument.addDocumentListener(new DocumentListener {
   198           def changedUpdate(e: DocumentEvent) { input_delay.invoke() }
   199           def insertUpdate(e: DocumentEvent) { input_delay.invoke() }
   200           def removeUpdate(e: DocumentEvent) { input_delay.invoke() }
   201         })
   202         setColumns(20)
   203         setToolTipText(search_label.tooltip)
   204         setFont(GUI.imitate_font(Font_Info.main_family(), getFont, 1.2))
   205       })
   206 
   207   private val search_field_foreground = search_field.foreground
   208 
   209   private def search_action(text_field: JTextField)
   210   {
   211     val (pattern, ok) =
   212       text_field.getText match {
   213         case null | "" => (None, true)
   214         case s =>
   215           try { (Some(new Regex(s)), true) }
   216           catch { case ERROR(_) => (None, false) }
   217       }
   218     if (current_search_pattern != pattern) {
   219       current_search_pattern = pattern
   220       text_area.getPainter.repaint()
   221     }
   222     text_field.setForeground(
   223       if (ok) search_field_foreground else current_rendering.error_color)
   224   }
   225 
   226 
   227   /* key handling */
   228 
   229   addKeyListener(JEdit_Lib.key_listener(
   230     key_pressed = (evt: KeyEvent) =>
   231       {
   232         evt.getKeyCode match {
   233           case KeyEvent.VK_C
   234           if (evt.getModifiers & Toolkit.getDefaultToolkit.getMenuShortcutKeyMask) != 0 &&
   235               text_area.getSelectionCount != 0 =>
   236             Registers.copy(text_area, '$')
   237             evt.consume
   238 
   239           case KeyEvent.VK_A
   240           if (evt.getModifiers & Toolkit.getDefaultToolkit.getMenuShortcutKeyMask) != 0 =>
   241             text_area.selectAll
   242             evt.consume
   243 
   244           case KeyEvent.VK_ESCAPE =>
   245             if (PIDE.dismissed_popups(view)) evt.consume
   246 
   247           case _ =>
   248         }
   249         if (propagate_keys) JEdit_Lib.propagate_key(view, evt)
   250       },
   251     key_typed = (evt: KeyEvent) =>
   252       {
   253         if (propagate_keys) JEdit_Lib.propagate_key(view, evt)
   254       }
   255     )
   256   )
   257 
   258 
   259   /* init */
   260 
   261   getPainter.setStructureHighlightEnabled(false)
   262   getPainter.setLineHighlightEnabled(false)
   263 
   264   getBuffer.setTokenMarker(Isabelle.token_marker("isabelle-output").get)
   265   getBuffer.setReadOnly(true)
   266   getBuffer.setStringProperty("noWordSep", "_'.?")
   267 
   268   rich_text_area.activate()
   269 }
   270