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