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