src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Tue Feb 25 20:46:09 2014 +0100 (2014-02-25 ago)
changeset 55748 2e1398b484aa
parent 55747 bef19c929ba5
child 55749 75a48dc4383e
permissions -rw-r--r--
no word completion within word 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, 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(Some(rendering), false) 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       opt_rendering: Option[Rendering], explicit: Boolean): 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.completion_context(JEdit_Lib.stretch_point_range(buffer, caret))
   148               case None => None
   149             }) getOrElse syntax.completion_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(): Boolean =
   223         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 => false
   229                 case Some(names) =>
   230                   JEdit_Lib.try_get_text(buffer, names.range) match {
   231                     case Some(original) =>
   232                       names.complete(history, decode, original) match {
   233                         case Some(result) if !result.items.isEmpty =>
   234                           open_popup(result)
   235                           true
   236                         case _ => false
   237                       }
   238                     case None => false
   239                   }
   240               }
   241             case _ => false
   242           }
   243         }
   244 
   245       def syntactic_completion(): Boolean =
   246         syntax_completion(None, explicit) match {
   247           case Some(result) =>
   248             result.items match {
   249               case List(item) if result.unique && item.immediate && immediate =>
   250                 insert(item); true
   251               case _ :: _ => open_popup(result); true
   252               case _ => false
   253             }
   254           case None => false
   255         }
   256 
   257       if (buffer.isEditable)
   258         semantic_completion() || syntactic_completion()
   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.substring(0, caret)
   390 
   391           val word_context =
   392             Completion.word_context(JEdit_Lib.try_get_text(text_field.getText,
   393               Text.Range(caret, caret + 1)))  // FIXME proper point range!?
   394 
   395           val context = syntax.completion_context
   396 
   397           syntax.completion.complete(history, true, false, 0, text, word_context, context) match {
   398             case Some(result) =>
   399               val fm = text_field.getFontMetrics(text_field.getFont)
   400               val loc =
   401                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   402 
   403               val completion =
   404                 new Completion_Popup(None, layered, loc, text_field.getFont, result.items)
   405               {
   406                 override def complete(item: Completion.Item) {
   407                   PIDE.completion_history.update(item)
   408                   insert(item)
   409                 }
   410                 override def propagate(evt: KeyEvent) {
   411                   if (!evt.isConsumed) text_field.processKeyEvent(evt)
   412                 }
   413                 override def refocus() { text_field.requestFocus }
   414               }
   415               completion_popup = Some(completion)
   416               completion.show_popup()
   417 
   418             case None =>
   419           }
   420         case _ =>
   421       }
   422     }
   423 
   424 
   425     /* process key event */
   426 
   427     private def process(evt: KeyEvent)
   428     {
   429       if (PIDE.options.bool("jedit_completion")) {
   430         dismissed()
   431         if (evt.getKeyChar != '\b') {
   432           val special = JEdit_Lib.special_key(evt)
   433           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   434             process_delay.revoke()
   435             action()
   436           }
   437           else process_delay.invoke()
   438         }
   439       }
   440     }
   441 
   442     private val process_delay =
   443       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   444         action()
   445       }
   446 
   447     override def processKeyEvent(evt0: KeyEvent)
   448     {
   449       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   450       if (evt != null) {
   451         evt.getID match {
   452           case KeyEvent.KEY_PRESSED =>
   453             val key_code = evt.getKeyCode
   454             if (key_code == KeyEvent.VK_ESCAPE) {
   455               if (dismissed()) evt.consume
   456             }
   457           case KeyEvent.KEY_TYPED =>
   458             super.processKeyEvent(evt)
   459             process(evt)
   460             evt.consume
   461           case _ =>
   462         }
   463         if (!evt.isConsumed) super.processKeyEvent(evt)
   464       }
   465     }
   466   }
   467 }
   468 
   469 
   470 class Completion_Popup private(
   471   val active_range: Option[(Text.Range, () => Unit)],
   472   layered: JLayeredPane,
   473   location: Point,
   474   font: Font,
   475   items: List[Completion.Item]) extends JPanel(new BorderLayout)
   476 {
   477   completion =>
   478 
   479   Swing_Thread.require()
   480 
   481   require(!items.isEmpty)
   482   val multi = items.length > 1
   483 
   484 
   485   /* actions */
   486 
   487   def complete(item: Completion.Item) { }
   488   def propagate(evt: KeyEvent) { }
   489   def refocus() { }
   490 
   491 
   492   /* list view */
   493 
   494   private val list_view = new ListView(items)
   495   list_view.font = font
   496   list_view.selection.intervalMode = ListView.IntervalMode.Single
   497   list_view.peer.setFocusTraversalKeysEnabled(false)
   498   list_view.peer.setVisibleRowCount(items.length min 8)
   499   list_view.peer.setSelectedIndex(0)
   500 
   501   for (cond <-
   502     List(JComponent.WHEN_FOCUSED,
   503       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   504       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   505 
   506   private def complete_selected(): Boolean =
   507   {
   508     list_view.selection.items.toList match {
   509       case item :: _ => complete(item); true
   510       case _ => false
   511     }
   512   }
   513 
   514   private def move_items(n: Int)
   515   {
   516     val i = list_view.peer.getSelectedIndex
   517     val j = ((i + n) min (items.length - 1)) max 0
   518     if (i != j) {
   519       list_view.peer.setSelectedIndex(j)
   520       list_view.peer.ensureIndexIsVisible(j)
   521     }
   522   }
   523 
   524   private def move_pages(n: Int)
   525   {
   526     val page_size = list_view.peer.getVisibleRowCount - 1
   527     move_items(page_size * n)
   528   }
   529 
   530 
   531   /* event handling */
   532 
   533   private val inner_key_listener =
   534     JEdit_Lib.key_listener(
   535       key_pressed = (e: KeyEvent) =>
   536         {
   537           if (!e.isConsumed) {
   538             e.getKeyCode match {
   539               case KeyEvent.VK_TAB =>
   540                 if (complete_selected()) e.consume
   541                 hide_popup()
   542               case KeyEvent.VK_ESCAPE =>
   543                 hide_popup()
   544                 e.consume
   545               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   546                 move_items(-1)
   547                 e.consume
   548               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   549                 move_items(1)
   550                 e.consume
   551               case KeyEvent.VK_PAGE_UP if multi =>
   552                 move_pages(-1)
   553                 e.consume
   554               case KeyEvent.VK_PAGE_DOWN if multi =>
   555                 move_pages(1)
   556                 e.consume
   557               case _ =>
   558                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   559                   hide_popup()
   560             }
   561           }
   562           propagate(e)
   563         },
   564       key_typed = propagate _
   565     )
   566 
   567   list_view.peer.addKeyListener(inner_key_listener)
   568 
   569   list_view.peer.addMouseListener(new MouseAdapter {
   570     override def mouseClicked(e: MouseEvent) {
   571       if (complete_selected()) e.consume
   572       hide_popup()
   573     }
   574   })
   575 
   576   list_view.peer.addFocusListener(new FocusAdapter {
   577     override def focusLost(e: FocusEvent) { hide_popup() }
   578   })
   579 
   580 
   581   /* main content */
   582 
   583   override def getFocusTraversalKeysEnabled = false
   584   completion.setBorder(new LineBorder(Color.BLACK))
   585   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   586 
   587 
   588   /* popup */
   589 
   590   private val popup =
   591   {
   592     val screen = JEdit_Lib.screen_location(layered, location)
   593     val size =
   594     {
   595       val geometry = JEdit_Lib.window_geometry(completion, completion)
   596       val bounds = Rendering.popup_bounds
   597       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   598       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   599       new Dimension(w, h)
   600     }
   601     new Popup(layered, completion, screen.relative(layered, size), size)
   602   }
   603 
   604   private def show_popup()
   605   {
   606     popup.show
   607     list_view.requestFocus
   608   }
   609 
   610   private val hide_popup_delay =
   611     Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_dismiss_delay")) {
   612       active_range match { case Some((_, invalidate)) => invalidate() case _ => }
   613       popup.hide
   614     }
   615 
   616   private def hide_popup()
   617   {
   618     if (list_view.peer.isFocusOwner) refocus()
   619 
   620     if (PIDE.options.seconds("jedit_completion_dismiss_delay").is_zero) {
   621       active_range match { case Some((_, invalidate)) => invalidate() case _ => }
   622       popup.hide
   623     }
   624     else hide_popup_delay.invoke()
   625   }
   626 }
   627