src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Mon Mar 17 10:45:29 2014 +0100 (2014-03-17 ago)
changeset 56170 638b29331549
parent 55978 56645c447ee9
child 56171 15351577da10
permissions -rw-r--r--
allow implicit semantic completion, notably after delay that exceeds usual round-trip time;
clarified isabelle.completion action: already open popup is re-opened and thus updated;
     1 /*  Title:      Tools/jEdit/src/completion_popup.scala
     2     Author:     Makarius
     3 
     4 Completion popup.
     5 */
     6 
     7 package isabelle.jedit
     8 
     9 
    10 import isabelle._
    11 
    12 import java.awt.{Color, Font, Point, BorderLayout, Dimension}
    13 import java.awt.event.{KeyEvent, MouseEvent, MouseAdapter, FocusAdapter, FocusEvent}
    14 import javax.swing.{JPanel, JComponent, JLayeredPane, SwingUtilities}
    15 import javax.swing.border.LineBorder
    16 import javax.swing.text.DefaultCaret
    17 
    18 import scala.swing.{ListView, ScrollPane}
    19 import scala.swing.event.MouseClicked
    20 
    21 import org.gjt.sp.jedit.View
    22 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea}
    23 import org.gjt.sp.jedit.gui.{HistoryTextField, KeyEventWorkaround}
    24 
    25 
    26 object Completion_Popup
    27 {
    28   /** items with HTML rendering **/
    29 
    30   private class Item(val item: Completion.Item)
    31   {
    32     private val html =
    33       item.description match {
    34         case a :: bs =>
    35           "<html><b>" + HTML.encode(a) + "</b>" +
    36             HTML.encode(bs.map(" " + _).mkString) + "</html>"
    37         case Nil => ""
    38       }
    39     override def toString: String = html
    40   }
    41 
    42 
    43 
    44   /** jEdit text area **/
    45 
    46   object Text_Area
    47   {
    48     private val key = new Object
    49 
    50     def apply(text_area: TextArea): Option[Completion_Popup.Text_Area] =
    51     {
    52       Swing_Thread.require()
    53       text_area.getClientProperty(key) match {
    54         case text_area_completion: Completion_Popup.Text_Area => Some(text_area_completion)
    55         case _ => None
    56       }
    57     }
    58 
    59     def active_range(text_area: TextArea): Option[Text.Range] =
    60       apply(text_area) match {
    61         case Some(text_area_completion) => text_area_completion.active_range
    62         case None => None
    63       }
    64 
    65     def action(text_area: TextArea): Boolean =
    66       apply(text_area) match {
    67         case Some(text_area_completion) =>
    68           if (text_area_completion.active_range.isDefined)
    69             text_area_completion.action(immediate = true, explicit = true)
    70           else text_area_completion.action()
    71           true
    72         case None => false
    73       }
    74 
    75     def exit(text_area: JEditTextArea)
    76     {
    77       Swing_Thread.require()
    78       apply(text_area) match {
    79         case None =>
    80         case Some(text_area_completion) =>
    81           text_area_completion.deactivate()
    82           text_area.putClientProperty(key, null)
    83       }
    84     }
    85 
    86     def init(text_area: JEditTextArea): Completion_Popup.Text_Area =
    87     {
    88       exit(text_area)
    89       val text_area_completion = new Text_Area(text_area)
    90       text_area.putClientProperty(key, text_area_completion)
    91       text_area_completion.activate()
    92       text_area_completion
    93     }
    94 
    95     def dismissed(text_area: TextArea): Boolean =
    96     {
    97       Swing_Thread.require()
    98       apply(text_area) match {
    99         case Some(text_area_completion) => text_area_completion.dismissed()
   100         case None => false
   101       }
   102     }
   103   }
   104 
   105   class Text_Area private(text_area: JEditTextArea)
   106   {
   107     // owned by Swing thread
   108     private var completion_popup: Option[Completion_Popup] = None
   109 
   110     def active_range: Option[Text.Range] =
   111       completion_popup match {
   112         case Some(completion) =>
   113           completion.active_range match {
   114             case Some((range, _)) if completion.isDisplayable => Some(range)
   115             case _ => None
   116           }
   117         case None => None
   118       }
   119 
   120 
   121     /* caret */
   122 
   123     def before_caret_range(rendering: Rendering): Text.Range =
   124     {
   125       val snapshot = rendering.snapshot
   126       val former_caret = snapshot.revert(text_area.getCaretPosition)
   127       snapshot.convert(Text.Range(former_caret - 1, former_caret))
   128     }
   129 
   130 
   131     /* rendering */
   132 
   133     def rendering(rendering: Rendering, line_range: Text.Range): Option[Text.Info[Color]] =
   134     {
   135       active_range match {
   136         case Some(range) => range.try_restrict(line_range)
   137         case None =>
   138           val buffer = text_area.getBuffer
   139           if (line_range.contains(text_area.getCaretPosition)) {
   140             before_caret_range(rendering).try_restrict(line_range) match {
   141               case Some(range) if !range.is_singularity =>
   142                 rendering.completion_names(range) match {
   143                   case Some(names) =>
   144                     if (names.no_completion) None
   145                     else Some(names.range)
   146                   case None =>
   147                     syntax_completion(false, Some(rendering)) match {
   148                       case Some(result) => Some(result.range)
   149                       case None => None
   150                     }
   151                 }
   152               case _ => None
   153             }
   154           }
   155           else None
   156       }
   157     }.map(range => Text.Info(range, rendering.completion_color))
   158 
   159 
   160     /* syntax completion */
   161 
   162     def syntax_completion(
   163       explicit: Boolean, opt_rendering: Option[Rendering] = None): Option[Completion.Result] =
   164     {
   165       val buffer = text_area.getBuffer
   166       val history = PIDE.completion_history.value
   167       val decode = Isabelle_Encoding.is_active(buffer)
   168 
   169       Isabelle.mode_syntax(JEdit_Lib.buffer_mode(buffer)) match {
   170         case Some(syntax) =>
   171           val caret = text_area.getCaretPosition
   172 
   173           val line = buffer.getLineOfOffset(caret)
   174           val line_start = buffer.getLineStartOffset(line)
   175           val line_length = (buffer.getLineEndOffset(line) min buffer.getLength) - line_start
   176           val line_text = buffer.getSegment(line_start, line_length)
   177 
   178           val context =
   179             (opt_rendering orElse PIDE.document_view(text_area).map(_.get_rendering()) match {
   180               case Some(rendering) =>
   181                 rendering.completion_language(before_caret_range(rendering))
   182               case None => None
   183             }) getOrElse syntax.language_context
   184 
   185           syntax.completion.complete(
   186             history, decode, explicit, line_start, line_text, caret - line_start, false, context)
   187 
   188         case None => None
   189       }
   190     }
   191 
   192 
   193     /* completion action: text area */
   194 
   195     private def insert(item: Completion.Item)
   196     {
   197       Swing_Thread.require()
   198 
   199       val buffer = text_area.getBuffer
   200       val range = item.range
   201       if (buffer.isEditable && range.length > 0) {
   202         JEdit_Lib.buffer_edit(buffer) {
   203           JEdit_Lib.try_get_text(buffer, range) match {
   204             case Some(text) if text == item.original =>
   205               buffer.remove(range.start, range.length)
   206               buffer.insert(range.start, item.replacement)
   207               text_area.moveCaretPosition(range.start + item.replacement.length + item.move)
   208             case _ =>
   209           }
   210         }
   211       }
   212     }
   213 
   214     def action(immediate: Boolean = false, explicit: Boolean = false)
   215     {
   216       val view = text_area.getView
   217       val layered = view.getLayeredPane
   218       val buffer = text_area.getBuffer
   219       val painter = text_area.getPainter
   220 
   221       val history = PIDE.completion_history.value
   222       val decode = Isabelle_Encoding.is_active(buffer)
   223 
   224       def open_popup(result: Completion.Result)
   225       {
   226         val font =
   227           painter.getFont.deriveFont(
   228             Font_Info.main_size(PIDE.options.real("jedit_popup_font_scale")))
   229 
   230         val range = result.range
   231         def invalidate(): Unit = JEdit_Lib.invalidate_range(text_area, range)
   232 
   233         val loc1 = text_area.offsetToXY(range.start)
   234         if (loc1 != null) {
   235           val loc2 =
   236             SwingUtilities.convertPoint(painter,
   237               loc1.x, loc1.y + painter.getFontMetrics.getHeight, layered)
   238 
   239           val items = result.items.map(new Item(_))
   240           val completion =
   241             new Completion_Popup(Some((range, invalidate _)), layered, loc2, font, items)
   242             {
   243               override def complete(item: Completion.Item) {
   244                 PIDE.completion_history.update(item)
   245                 insert(item)
   246               }
   247               override def propagate(evt: KeyEvent) {
   248                 JEdit_Lib.propagate_key(view, evt)
   249                 input(evt)
   250               }
   251               override def refocus() { text_area.requestFocus }
   252             }
   253           completion_popup = Some(completion)
   254           invalidate()
   255           completion.show_popup()
   256         }
   257       }
   258 
   259       def semantic_completion(): Option[Completion.Result] =
   260         PIDE.document_view(text_area) match {
   261           case Some(doc_view) =>
   262             val rendering = doc_view.get_rendering()
   263             rendering.completion_names(before_caret_range(rendering)) match {
   264               case Some(names) =>
   265                 if (names.no_completion)
   266                   Some(Completion.Result.empty(names.range))
   267                 else
   268                   JEdit_Lib.try_get_text(buffer, names.range) match {
   269                     case Some(original) => names.complete(history, decode, original)
   270                     case None => None
   271                   }
   272               case None => None
   273             }
   274           case None => None
   275         }
   276 
   277       if (buffer.isEditable) {
   278         semantic_completion() orElse syntax_completion(explicit) match {
   279           case Some(result) =>
   280             result.items match {
   281               case List(item) if result.unique && item.immediate && immediate =>
   282                 insert(item)
   283               case _ :: _ =>
   284                 open_popup(result)
   285               case _ =>
   286             }
   287           case None =>
   288         }
   289       }
   290     }
   291 
   292 
   293     /* input key events */
   294 
   295     def input(evt: KeyEvent)
   296     {
   297       Swing_Thread.require()
   298 
   299       if (PIDE.options.bool("jedit_completion")) {
   300         if (!evt.isConsumed) {
   301           dismissed()
   302           if (evt.getKeyChar != '\b') {
   303             val special = JEdit_Lib.special_key(evt)
   304             if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   305               input_delay.revoke()
   306               action(immediate = PIDE.options.bool("jedit_completion_immediate"))
   307             }
   308             else input_delay.invoke()
   309           }
   310         }
   311       }
   312     }
   313 
   314     private val input_delay =
   315       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   316         action()
   317       }
   318 
   319 
   320     /* dismiss popup */
   321 
   322     def dismissed(): Boolean =
   323     {
   324       Swing_Thread.require()
   325 
   326       completion_popup match {
   327         case Some(completion) =>
   328           completion.hide_popup()
   329           completion_popup = None
   330           true
   331         case None =>
   332           false
   333       }
   334     }
   335 
   336 
   337     /* activation */
   338 
   339     private val outer_key_listener =
   340       JEdit_Lib.key_listener(key_typed = input _)
   341 
   342     private def activate()
   343     {
   344       text_area.addKeyListener(outer_key_listener)
   345     }
   346 
   347     private def deactivate()
   348     {
   349       dismissed()
   350       text_area.removeKeyListener(outer_key_listener)
   351     }
   352   }
   353 
   354 
   355 
   356   /** history text field **/
   357 
   358   class History_Text_Field(
   359     name: String = null,
   360     instant_popups: Boolean = false,
   361     enter_adds_to_history: Boolean = true,
   362     syntax: Outer_Syntax = Outer_Syntax.init) extends
   363     HistoryTextField(name, instant_popups, enter_adds_to_history)
   364   {
   365     text_field =>
   366 
   367     // see https://forums.oracle.com/thread/1361677
   368     if (GUI.is_macos_laf) text_field.setCaret(new DefaultCaret)
   369 
   370     // owned by Swing thread
   371     private var completion_popup: Option[Completion_Popup] = None
   372 
   373 
   374     /* dismiss */
   375 
   376     private def dismissed(): Boolean =
   377     {
   378       completion_popup match {
   379         case Some(completion) =>
   380           completion.hide_popup()
   381           completion_popup = None
   382           true
   383         case None =>
   384           false
   385       }
   386     }
   387 
   388 
   389     /* insert */
   390 
   391     private def insert(item: Completion.Item)
   392     {
   393       Swing_Thread.require()
   394 
   395       val range = item.range
   396       if (text_field.isEditable && range.length > 0) {
   397         val content = text_field.getText
   398         JEdit_Lib.try_get_text(content, range) match {
   399           case Some(text) if text == item.original =>
   400             text_field.setText(
   401               content.substring(0, range.start) +
   402               item.replacement +
   403               content.substring(range.stop))
   404             text_field.getCaret.setDot(range.start + item.replacement.length + item.move)
   405           case _ =>
   406         }
   407       }
   408     }
   409 
   410 
   411     /* completion action: text field */
   412 
   413     def action()
   414     {
   415       GUI.layered_pane(text_field) match {
   416         case Some(layered) if text_field.isEditable =>
   417           val history = PIDE.completion_history.value
   418 
   419           val caret = text_field.getCaret.getDot
   420           val text = text_field.getText
   421 
   422           val context = syntax.language_context
   423 
   424           syntax.completion.complete(history, true, false, 0, text, caret, false, context) match {
   425             case Some(result) =>
   426               val fm = text_field.getFontMetrics(text_field.getFont)
   427               val loc =
   428                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   429 
   430               val items = result.items.map(new Item(_))
   431               val completion =
   432                 new Completion_Popup(None, layered, loc, text_field.getFont, items)
   433                 {
   434                   override def complete(item: Completion.Item) {
   435                     PIDE.completion_history.update(item)
   436                     insert(item)
   437                   }
   438                   override def propagate(evt: KeyEvent) {
   439                     if (!evt.isConsumed) text_field.processKeyEvent(evt)
   440                   }
   441                   override def refocus() { text_field.requestFocus }
   442                 }
   443               completion_popup = Some(completion)
   444               completion.show_popup()
   445 
   446             case None =>
   447           }
   448         case _ =>
   449       }
   450     }
   451 
   452 
   453     /* process key event */
   454 
   455     private def process(evt: KeyEvent)
   456     {
   457       if (PIDE.options.bool("jedit_completion")) {
   458         dismissed()
   459         if (evt.getKeyChar != '\b') {
   460           val special = JEdit_Lib.special_key(evt)
   461           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   462             process_delay.revoke()
   463             action()
   464           }
   465           else process_delay.invoke()
   466         }
   467       }
   468     }
   469 
   470     private val process_delay =
   471       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   472         action()
   473       }
   474 
   475     override def processKeyEvent(evt0: KeyEvent)
   476     {
   477       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   478       if (evt != null) {
   479         evt.getID match {
   480           case KeyEvent.KEY_PRESSED =>
   481             val key_code = evt.getKeyCode
   482             if (key_code == KeyEvent.VK_ESCAPE) {
   483               if (dismissed()) evt.consume
   484             }
   485           case KeyEvent.KEY_TYPED =>
   486             super.processKeyEvent(evt)
   487             process(evt)
   488             evt.consume
   489           case _ =>
   490         }
   491         if (!evt.isConsumed) super.processKeyEvent(evt)
   492       }
   493     }
   494   }
   495 }
   496 
   497 
   498 class Completion_Popup private(
   499   val active_range: Option[(Text.Range, () => Unit)],
   500   layered: JLayeredPane,
   501   location: Point,
   502   font: Font,
   503   items: List[Completion_Popup.Item]) extends JPanel(new BorderLayout)
   504 {
   505   completion =>
   506 
   507   Swing_Thread.require()
   508 
   509   require(!items.isEmpty)
   510   val multi = items.length > 1
   511 
   512 
   513   /* actions */
   514 
   515   def complete(item: Completion.Item) { }
   516   def propagate(evt: KeyEvent) { }
   517   def refocus() { }
   518 
   519 
   520   /* list view */
   521 
   522   private val list_view = new ListView(items)
   523   list_view.font = font
   524   list_view.selection.intervalMode = ListView.IntervalMode.Single
   525   list_view.peer.setFocusTraversalKeysEnabled(false)
   526   list_view.peer.setVisibleRowCount(items.length min 8)
   527   list_view.peer.setSelectedIndex(0)
   528 
   529   for (cond <-
   530     List(JComponent.WHEN_FOCUSED,
   531       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   532       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   533 
   534   private def complete_selected(): Boolean =
   535   {
   536     list_view.selection.items.toList match {
   537       case item :: _ => complete(item.item); true
   538       case _ => false
   539     }
   540   }
   541 
   542   private def move_items(n: Int)
   543   {
   544     val i = list_view.peer.getSelectedIndex
   545     val j = ((i + n) min (items.length - 1)) max 0
   546     if (i != j) {
   547       list_view.peer.setSelectedIndex(j)
   548       list_view.peer.ensureIndexIsVisible(j)
   549     }
   550   }
   551 
   552   private def move_pages(n: Int)
   553   {
   554     val page_size = list_view.peer.getVisibleRowCount - 1
   555     move_items(page_size * n)
   556   }
   557 
   558 
   559   /* event handling */
   560 
   561   private val inner_key_listener =
   562     JEdit_Lib.key_listener(
   563       key_pressed = (e: KeyEvent) =>
   564         {
   565           if (!e.isConsumed) {
   566             e.getKeyCode match {
   567               case KeyEvent.VK_TAB =>
   568                 if (complete_selected()) e.consume
   569                 hide_popup()
   570               case KeyEvent.VK_ESCAPE =>
   571                 hide_popup()
   572                 e.consume
   573               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   574                 move_items(-1)
   575                 e.consume
   576               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   577                 move_items(1)
   578                 e.consume
   579               case KeyEvent.VK_PAGE_UP if multi =>
   580                 move_pages(-1)
   581                 e.consume
   582               case KeyEvent.VK_PAGE_DOWN if multi =>
   583                 move_pages(1)
   584                 e.consume
   585               case _ =>
   586                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   587                   hide_popup()
   588             }
   589           }
   590           propagate(e)
   591         },
   592       key_typed = propagate _
   593     )
   594 
   595   list_view.peer.addKeyListener(inner_key_listener)
   596 
   597   list_view.peer.addMouseListener(new MouseAdapter {
   598     override def mouseClicked(e: MouseEvent) {
   599       if (complete_selected()) e.consume
   600       hide_popup()
   601     }
   602   })
   603 
   604   list_view.peer.addFocusListener(new FocusAdapter {
   605     override def focusLost(e: FocusEvent) { hide_popup() }
   606   })
   607 
   608 
   609   /* main content */
   610 
   611   override def getFocusTraversalKeysEnabled = false
   612   completion.setBorder(new LineBorder(Color.BLACK))
   613   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   614 
   615 
   616   /* popup */
   617 
   618   private val popup =
   619   {
   620     val screen = JEdit_Lib.screen_location(layered, location)
   621     val size =
   622     {
   623       val geometry = JEdit_Lib.window_geometry(completion, completion)
   624       val bounds = Rendering.popup_bounds
   625       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   626       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   627       new Dimension(w, h)
   628     }
   629     new Popup(layered, completion, screen.relative(layered, size), size)
   630   }
   631 
   632   private def show_popup()
   633   {
   634     popup.show
   635     list_view.requestFocus
   636   }
   637 
   638   private val hide_popup_delay =
   639     Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_dismiss_delay")) {
   640       active_range match { case Some((_, invalidate)) => invalidate() case _ => }
   641       popup.hide
   642     }
   643 
   644   private def hide_popup()
   645   {
   646     if (list_view.peer.isFocusOwner) refocus()
   647 
   648     if (PIDE.options.seconds("jedit_completion_dismiss_delay").is_zero) {
   649       active_range match { case Some((_, invalidate)) => invalidate() case _ => }
   650       popup.hide
   651     }
   652     else hide_popup_delay.invoke()
   653   }
   654 }
   655