src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Thu Feb 20 12:53:12 2014 +0100 (2014-02-20 ago)
changeset 55615 bf4bbe72f740
parent 54377 750561986828
child 55616 25a7a998852a
permissions -rw-r--r--
completion of keywords and symbols based on language context;
     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
    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: JEditTextArea): Option[Completion_Popup.Text_Area] =
    35       text_area.getClientProperty(key) match {
    36         case text_area_completion: Completion_Popup.Text_Area => Some(text_area_completion)
    37         case _ => None
    38       }
    39 
    40     def exit(text_area: JEditTextArea)
    41     {
    42       Swing_Thread.require()
    43       apply(text_area) match {
    44         case None =>
    45         case Some(text_area_completion) =>
    46           text_area_completion.deactivate()
    47           text_area.putClientProperty(key, null)
    48       }
    49     }
    50 
    51     def init(text_area: JEditTextArea): Completion_Popup.Text_Area =
    52     {
    53       exit(text_area)
    54       val text_area_completion = new Text_Area(text_area)
    55       text_area.putClientProperty(key, text_area_completion)
    56       text_area_completion.activate()
    57       text_area_completion
    58     }
    59 
    60     def dismissed(text_area: JEditTextArea): Boolean =
    61     {
    62       Swing_Thread.require()
    63       apply(text_area) match {
    64         case Some(text_area_completion) => text_area_completion.dismissed()
    65         case None => false
    66       }
    67     }
    68   }
    69 
    70   class Text_Area private(text_area: JEditTextArea)
    71   {
    72     private var completion_popup: Option[Completion_Popup] = None
    73 
    74 
    75     /* completion action */
    76 
    77     private def insert(item: Completion.Item)
    78     {
    79       Swing_Thread.require()
    80 
    81       val buffer = text_area.getBuffer
    82       val len = item.original.length
    83       if (buffer.isEditable && len > 0) {
    84         JEdit_Lib.buffer_edit(buffer) {
    85           val caret = text_area.getCaretPosition
    86           JEdit_Lib.try_get_text(buffer, Text.Range(caret - len, caret)) match {
    87             case Some(text) if text == item.original =>
    88               buffer.remove(caret - len, len)
    89               buffer.insert(caret - len, item.replacement)
    90             case _ =>
    91           }
    92         }
    93       }
    94     }
    95 
    96     def action(immediate: Boolean = false, explicit: Boolean = false)
    97     {
    98       val view = text_area.getView
    99       val layered = view.getLayeredPane
   100       val buffer = text_area.getBuffer
   101       val painter = text_area.getPainter
   102 
   103       if (buffer.isEditable) {
   104         Isabelle.mode_syntax(JEdit_Lib.buffer_mode(buffer)) match {
   105           case Some(syntax) =>
   106             val caret = text_area.getCaretPosition
   107             val line = buffer.getLineOfOffset(caret)
   108             val start = buffer.getLineStartOffset(line)
   109             val text = buffer.getSegment(start, caret - start)
   110 
   111             val history = PIDE.completion_history.value
   112             val decode = Isabelle_Encoding.is_active(buffer)
   113             val context =
   114               PIDE.document_view(text_area) match {
   115                 case None => Completion.Context.default
   116                 case Some(doc_view) => doc_view.get_rendering().completion_context(caret)
   117               }
   118             syntax.completion.complete(history, decode, explicit, text, context) match {
   119               case Some(result) =>
   120                 if (result.unique && result.items.head.immediate && immediate)
   121                   insert(result.items.head)
   122                 else {
   123                   val font =
   124                     painter.getFont.deriveFont(Rendering.font_size("jedit_popup_font_scale"))
   125 
   126                   val loc1 = text_area.offsetToXY(caret - result.original.length)
   127                   if (loc1 != null) {
   128                     val loc2 =
   129                       SwingUtilities.convertPoint(painter,
   130                         loc1.x, loc1.y + painter.getFontMetrics.getHeight, layered)
   131 
   132                     val completion =
   133                       new Completion_Popup(layered, loc2, font, result.items) {
   134                         override def complete(item: Completion.Item) {
   135                           PIDE.completion_history.update(item)
   136                           insert(item)
   137                         }
   138                         override def propagate(evt: KeyEvent) {
   139                           JEdit_Lib.propagate_key(view, evt)
   140                           input(evt)
   141                         }
   142                         override def refocus() { text_area.requestFocus }
   143                       }
   144                     completion_popup = Some(completion)
   145                     completion.show_popup()
   146                   }
   147                 }
   148               case None =>
   149             }
   150           case None =>
   151         }
   152       }
   153     }
   154 
   155 
   156     /* input key events */
   157 
   158     def input(evt: KeyEvent)
   159     {
   160       Swing_Thread.require()
   161 
   162       if (PIDE.options.bool("jedit_completion")) {
   163         if (!evt.isConsumed) {
   164           dismissed()
   165           if (evt.getKeyChar != '\b') {
   166             val special = JEdit_Lib.special_key(evt)
   167             if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   168               input_delay.revoke()
   169               action(immediate = PIDE.options.bool("jedit_completion_immediate"))
   170             }
   171             else input_delay.invoke()
   172           }
   173         }
   174       }
   175     }
   176 
   177     private val input_delay =
   178       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   179         action()
   180       }
   181 
   182 
   183     /* dismiss popup */
   184 
   185     def dismissed(): Boolean =
   186     {
   187       Swing_Thread.require()
   188 
   189       completion_popup match {
   190         case Some(completion) =>
   191           completion.hide_popup()
   192           completion_popup = None
   193           true
   194         case None =>
   195           false
   196       }
   197     }
   198 
   199 
   200     /* activation */
   201 
   202     private val outer_key_listener =
   203       JEdit_Lib.key_listener(key_typed = input _)
   204 
   205     private def activate()
   206     {
   207       text_area.addKeyListener(outer_key_listener)
   208     }
   209 
   210     private def deactivate()
   211     {
   212       dismissed()
   213       text_area.removeKeyListener(outer_key_listener)
   214     }
   215   }
   216 
   217 
   218 
   219   /** history text field **/
   220 
   221   class History_Text_Field(
   222     name: String = null,
   223     instant_popups: Boolean = false,
   224     enter_adds_to_history: Boolean = true,
   225     syntax: Outer_Syntax = Outer_Syntax.init) extends
   226     HistoryTextField(name, instant_popups, enter_adds_to_history)
   227   {
   228     text_field =>
   229 
   230     // see https://forums.oracle.com/thread/1361677
   231     if (GUI.is_macos_laf) text_field.setCaret(new DefaultCaret)
   232 
   233     private var completion_popup: Option[Completion_Popup] = None
   234 
   235 
   236     /* dismiss */
   237 
   238     private def dismissed(): Boolean =
   239     {
   240       completion_popup match {
   241         case Some(completion) =>
   242           completion.hide_popup()
   243           completion_popup = None
   244           true
   245         case None =>
   246           false
   247       }
   248     }
   249 
   250 
   251     /* insert */
   252 
   253     private def insert(item: Completion.Item)
   254     {
   255       Swing_Thread.require()
   256 
   257       val len = item.original.length
   258       if (text_field.isEditable && len > 0) {
   259         val caret = text_field.getCaret.getDot
   260         val content = text_field.getText
   261         JEdit_Lib.try_get_text(content, Text.Range(caret - len, caret)) match {
   262           case Some(text) if text == item.original =>
   263             text_field.setText(
   264               content.substring(0, caret - len) +
   265               item.replacement +
   266               content.substring(caret))
   267             text_field.getCaret.setDot(caret - len + item.replacement.length)
   268           case _ =>
   269         }
   270       }
   271     }
   272 
   273 
   274     /* completion action */
   275 
   276     def action()
   277     {
   278       GUI.layered_pane(text_field) match {
   279         case Some(layered) if text_field.isEditable =>
   280           val history = PIDE.completion_history.value
   281 
   282           val caret = text_field.getCaret.getDot
   283           val text = text_field.getText.substring(0, caret)
   284 
   285           syntax.completion.complete(
   286               history, decode = true, explicit = false, text, Completion.Context.default) match {
   287             case Some(result) =>
   288               val fm = text_field.getFontMetrics(text_field.getFont)
   289               val loc =
   290                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   291 
   292               val completion = new Completion_Popup(layered, loc, text_field.getFont, result.items)
   293               {
   294                 override def complete(item: Completion.Item) {
   295                   PIDE.completion_history.update(item)
   296                   insert(item)
   297                 }
   298                 override def propagate(evt: KeyEvent) {
   299                   if (!evt.isConsumed) text_field.processKeyEvent(evt)
   300                 }
   301                 override def refocus() { text_field.requestFocus }
   302               }
   303               completion_popup = Some(completion)
   304               completion.show_popup()
   305 
   306             case None =>
   307           }
   308         case _ =>
   309       }
   310     }
   311 
   312 
   313     /* process key event */
   314 
   315     private def process(evt: KeyEvent)
   316     {
   317       if (PIDE.options.bool("jedit_completion")) {
   318         dismissed()
   319         if (evt.getKeyChar != '\b') {
   320           val special = JEdit_Lib.special_key(evt)
   321           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   322             process_delay.revoke()
   323             action()
   324           }
   325           else process_delay.invoke()
   326         }
   327       }
   328     }
   329 
   330     private val process_delay =
   331       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   332         action()
   333       }
   334 
   335     override def processKeyEvent(evt0: KeyEvent)
   336     {
   337       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   338       if (evt != null) {
   339         evt.getID match {
   340           case KeyEvent.KEY_PRESSED =>
   341             val key_code = evt.getKeyCode
   342             if (key_code == KeyEvent.VK_ESCAPE) {
   343               if (dismissed()) evt.consume
   344             }
   345           case KeyEvent.KEY_TYPED =>
   346             super.processKeyEvent(evt)
   347             process(evt)
   348             evt.consume
   349           case _ =>
   350         }
   351         if (!evt.isConsumed) super.processKeyEvent(evt)
   352       }
   353     }
   354   }
   355 }
   356 
   357 
   358 class Completion_Popup private(
   359   layered: JLayeredPane,
   360   location: Point,
   361   font: Font,
   362   items: List[Completion.Item]) extends JPanel(new BorderLayout)
   363 {
   364   completion =>
   365 
   366   Swing_Thread.require()
   367 
   368   require(!items.isEmpty)
   369   val multi = items.length > 1
   370 
   371 
   372   /* actions */
   373 
   374   def complete(item: Completion.Item) { }
   375   def propagate(evt: KeyEvent) { }
   376   def refocus() { }
   377 
   378 
   379   /* list view */
   380 
   381   private val list_view = new ListView(items)
   382   list_view.font = font
   383   list_view.selection.intervalMode = ListView.IntervalMode.Single
   384   list_view.peer.setFocusTraversalKeysEnabled(false)
   385   list_view.peer.setVisibleRowCount(items.length min 8)
   386   list_view.peer.setSelectedIndex(0)
   387 
   388   for (cond <-
   389     List(JComponent.WHEN_FOCUSED,
   390       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   391       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   392 
   393   private def complete_selected(): Boolean =
   394   {
   395     list_view.selection.items.toList match {
   396       case item :: _ => complete(item); true
   397       case _ => false
   398     }
   399   }
   400 
   401   private def move_items(n: Int)
   402   {
   403     val i = list_view.peer.getSelectedIndex
   404     val j = ((i + n) min (items.length - 1)) max 0
   405     if (i != j) {
   406       list_view.peer.setSelectedIndex(j)
   407       list_view.peer.ensureIndexIsVisible(j)
   408     }
   409   }
   410 
   411   private def move_pages(n: Int)
   412   {
   413     val page_size = list_view.peer.getVisibleRowCount - 1
   414     move_items(page_size * n)
   415   }
   416 
   417 
   418   /* event handling */
   419 
   420   private val inner_key_listener =
   421     JEdit_Lib.key_listener(
   422       key_pressed = (e: KeyEvent) =>
   423         {
   424           if (!e.isConsumed) {
   425             e.getKeyCode match {
   426               case KeyEvent.VK_TAB =>
   427                 if (complete_selected()) e.consume
   428                 hide_popup()
   429               case KeyEvent.VK_ESCAPE =>
   430                 hide_popup()
   431                 e.consume
   432               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   433                 move_items(-1)
   434                 e.consume
   435               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   436                 move_items(1)
   437                 e.consume
   438               case KeyEvent.VK_PAGE_UP if multi =>
   439                 move_pages(-1)
   440                 e.consume
   441               case KeyEvent.VK_PAGE_DOWN if multi =>
   442                 move_pages(1)
   443                 e.consume
   444               case _ =>
   445                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   446                   hide_popup()
   447             }
   448           }
   449           propagate(e)
   450         },
   451       key_typed = propagate _
   452     )
   453 
   454   list_view.peer.addKeyListener(inner_key_listener)
   455 
   456   list_view.peer.addMouseListener(new MouseAdapter {
   457     override def mouseClicked(e: MouseEvent) {
   458       if (complete_selected()) e.consume
   459       hide_popup()
   460     }
   461   })
   462 
   463   list_view.peer.addFocusListener(new FocusAdapter {
   464     override def focusLost(e: FocusEvent) { hide_popup() }
   465   })
   466 
   467 
   468   /* main content */
   469 
   470   override def getFocusTraversalKeysEnabled = false
   471   completion.setBorder(new LineBorder(Color.BLACK))
   472   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   473 
   474 
   475   /* popup */
   476 
   477   private val popup =
   478   {
   479     val screen = JEdit_Lib.screen_location(layered, location)
   480     val size =
   481     {
   482       val geometry = JEdit_Lib.window_geometry(completion, completion)
   483       val bounds = Rendering.popup_bounds
   484       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   485       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   486       new Dimension(w, h)
   487     }
   488     new Popup(layered, completion, screen.relative(layered, size), size)
   489   }
   490 
   491   private def show_popup()
   492   {
   493     popup.show
   494     list_view.requestFocus
   495   }
   496 
   497   private val hide_popup_delay =
   498     Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_dismiss_delay")) {
   499       popup.hide
   500     }
   501 
   502   private def hide_popup()
   503   {
   504     if (list_view.peer.isFocusOwner) refocus()
   505 
   506     if (PIDE.options.seconds("jedit_completion_dismiss_delay").is_zero)
   507       popup.hide
   508     else hide_popup_delay.invoke()
   509   }
   510 }
   511