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