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