src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Sun Mar 30 20:23:26 2014 +0200 (2014-03-30 ago)
changeset 56325 ffbfc92e6508
parent 56197 416f7a00e4cb
child 56326 c3d7b3bb2708
permissions -rw-r--r--
special treatment for various kinds of selections: imitate normal flow of editing;
     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)
   235     {
   236       val view = text_area.getView
   237       val layered = view.getLayeredPane
   238       val buffer = text_area.getBuffer
   239       val painter = text_area.getPainter
   240 
   241       val history = PIDE.completion_history.value
   242       val decode = Isabelle_Encoding.is_active(buffer)
   243 
   244       def open_popup(result: Completion.Result)
   245       {
   246         val font =
   247           painter.getFont.deriveFont(
   248             Font_Info.main_size(PIDE.options.real("jedit_popup_font_scale")))
   249 
   250         val range = result.range
   251         def invalidate(): Unit = JEdit_Lib.invalidate_range(text_area, range)
   252 
   253         val loc1 = text_area.offsetToXY(range.start)
   254         if (loc1 != null) {
   255           val loc2 =
   256             SwingUtilities.convertPoint(painter,
   257               loc1.x, loc1.y + painter.getFontMetrics.getHeight, layered)
   258 
   259           val items = result.items.map(new Item(_))
   260           val completion =
   261             new Completion_Popup(Some(range), layered, loc2, font, items)
   262             {
   263               override def complete(item: Completion.Item) {
   264                 PIDE.completion_history.update(item)
   265                 insert(item)
   266               }
   267               override def propagate(evt: KeyEvent) {
   268                 if (view.getKeyEventInterceptor == inner_key_listener) {
   269                   try {
   270                     view.setKeyEventInterceptor(null)
   271                     JEdit_Lib.propagate_key(view, evt)
   272                   }
   273                   finally {
   274                     if (isDisplayable) view.setKeyEventInterceptor(inner_key_listener)
   275                   }
   276                 }
   277                 if (evt.getID == KeyEvent.KEY_TYPED) input(evt)
   278               }
   279               override def shutdown(focus: Boolean) {
   280                 if (view.getKeyEventInterceptor == inner_key_listener)
   281                   view.setKeyEventInterceptor(null)
   282                 if (focus) text_area.requestFocus
   283                 invalidate()
   284               }
   285             }
   286           completion_popup = Some(completion)
   287           view.setKeyEventInterceptor(completion.inner_key_listener)
   288           invalidate()
   289           completion.show_popup(false)
   290         }
   291       }
   292 
   293       if (buffer.isEditable) {
   294         val (no_completion, semantic_completion, opt_rendering) =
   295         {
   296           PIDE.document_view(text_area) match {
   297             case Some(doc_view) =>
   298               val rendering = doc_view.get_rendering()
   299               val (no_completion, result) =
   300                 rendering.semantic_completion(before_caret_range(rendering)) match {
   301                   case Some(Text.Info(_, Completion.No_Completion)) =>
   302                     (true, None)
   303                   case Some(Text.Info(range, names: Completion.Names)) =>
   304                     val result =
   305                       JEdit_Lib.try_get_text(buffer, range) match {
   306                         case Some(original) => names.complete(range, history, decode, original)
   307                         case None => None
   308                       }
   309                     (false, result)
   310                   case None =>
   311                     (false, None)
   312                 }
   313               (no_completion, result, Some(rendering))
   314             case None =>
   315               (false, None, None)
   316           }
   317         }
   318         if (!no_completion) {
   319           val result =
   320             Completion.Result.merge(history,
   321               semantic_completion, syntax_completion(history, explicit, opt_rendering))
   322 
   323           result match {
   324             case Some(result) =>
   325               result.items match {
   326                 case List(item) if result.unique && item.immediate && immediate =>
   327                   insert(item)
   328                 case _ :: _ =>
   329                   open_popup(result)
   330                 case _ =>
   331               }
   332             case None =>
   333           }
   334         }
   335       }
   336     }
   337 
   338 
   339     /* input key events */
   340 
   341     def input(evt: KeyEvent)
   342     {
   343       Swing_Thread.require()
   344 
   345       if (PIDE.options.bool("jedit_completion")) {
   346         if (!evt.isConsumed) {
   347           dismissed()
   348           if (evt.getKeyChar != '\b') {
   349             val special = JEdit_Lib.special_key(evt)
   350             if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   351               input_delay.revoke()
   352               action(immediate = PIDE.options.bool("jedit_completion_immediate"))
   353             }
   354             else input_delay.invoke()
   355           }
   356         }
   357       }
   358     }
   359 
   360     private val input_delay =
   361       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   362         action()
   363       }
   364 
   365 
   366     /* dismiss popup */
   367 
   368     def dismissed(): Boolean =
   369     {
   370       Swing_Thread.require()
   371 
   372       completion_popup match {
   373         case Some(completion) =>
   374           completion.hide_popup()
   375           completion_popup = None
   376           true
   377         case None =>
   378           false
   379       }
   380     }
   381 
   382 
   383     /* activation */
   384 
   385     private val outer_key_listener =
   386       JEdit_Lib.key_listener(key_typed = input _)
   387 
   388     private def activate()
   389     {
   390       text_area.addKeyListener(outer_key_listener)
   391     }
   392 
   393     private def deactivate()
   394     {
   395       dismissed()
   396       text_area.removeKeyListener(outer_key_listener)
   397     }
   398   }
   399 
   400 
   401 
   402   /** history text field **/
   403 
   404   class History_Text_Field(
   405     name: String = null,
   406     instant_popups: Boolean = false,
   407     enter_adds_to_history: Boolean = true,
   408     syntax: Outer_Syntax = Outer_Syntax.init) extends
   409     HistoryTextField(name, instant_popups, enter_adds_to_history)
   410   {
   411     text_field =>
   412 
   413     // see https://forums.oracle.com/thread/1361677
   414     if (GUI.is_macos_laf) text_field.setCaret(new DefaultCaret)
   415 
   416     // owned by Swing thread
   417     private var completion_popup: Option[Completion_Popup] = None
   418 
   419 
   420     /* dismiss */
   421 
   422     private def dismissed(): Boolean =
   423     {
   424       completion_popup match {
   425         case Some(completion) =>
   426           completion.hide_popup()
   427           completion_popup = None
   428           true
   429         case None =>
   430           false
   431       }
   432     }
   433 
   434 
   435     /* insert */
   436 
   437     private def insert(item: Completion.Item)
   438     {
   439       Swing_Thread.require()
   440 
   441       val range = item.range
   442       if (text_field.isEditable && range.length > 0) {
   443         val content = text_field.getText
   444         JEdit_Lib.try_get_text(content, range) match {
   445           case Some(text) if text == item.original =>
   446             text_field.setText(
   447               content.substring(0, range.start) +
   448               item.replacement +
   449               content.substring(range.stop))
   450             text_field.getCaret.setDot(range.start + item.replacement.length + item.move)
   451           case _ =>
   452         }
   453       }
   454     }
   455 
   456 
   457     /* completion action: text field */
   458 
   459     def action()
   460     {
   461       GUI.layered_pane(text_field) match {
   462         case Some(layered) if text_field.isEditable =>
   463           val history = PIDE.completion_history.value
   464 
   465           val caret = text_field.getCaret.getDot
   466           val text = text_field.getText
   467 
   468           val context = syntax.language_context
   469 
   470           syntax.completion.complete(history, true, false, 0, text, caret, false, context) match {
   471             case Some(result) =>
   472               val fm = text_field.getFontMetrics(text_field.getFont)
   473               val loc =
   474                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   475 
   476               val items = result.items.map(new Item(_))
   477               val completion =
   478                 new Completion_Popup(None, layered, loc, text_field.getFont, items)
   479                 {
   480                   override def complete(item: Completion.Item) {
   481                     PIDE.completion_history.update(item)
   482                     insert(item)
   483                   }
   484                   override def propagate(evt: KeyEvent) {
   485                     if (!evt.isConsumed) text_field.processKeyEvent(evt)
   486                   }
   487                   override def shutdown(focus: Boolean) { if (focus) text_field.requestFocus }
   488                 }
   489               completion_popup = Some(completion)
   490               completion.show_popup(true)
   491 
   492             case None =>
   493           }
   494         case _ =>
   495       }
   496     }
   497 
   498 
   499     /* process key event */
   500 
   501     private def process(evt: KeyEvent)
   502     {
   503       if (PIDE.options.bool("jedit_completion")) {
   504         dismissed()
   505         if (evt.getKeyChar != '\b') {
   506           val special = JEdit_Lib.special_key(evt)
   507           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   508             process_delay.revoke()
   509             action()
   510           }
   511           else process_delay.invoke()
   512         }
   513       }
   514     }
   515 
   516     private val process_delay =
   517       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   518         action()
   519       }
   520 
   521     override def processKeyEvent(evt0: KeyEvent)
   522     {
   523       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   524       if (evt != null) {
   525         evt.getID match {
   526           case KeyEvent.KEY_PRESSED =>
   527             val key_code = evt.getKeyCode
   528             if (key_code == KeyEvent.VK_ESCAPE) {
   529               if (dismissed()) evt.consume
   530             }
   531           case KeyEvent.KEY_TYPED =>
   532             super.processKeyEvent(evt)
   533             process(evt)
   534             evt.consume
   535           case _ =>
   536         }
   537         if (!evt.isConsumed) super.processKeyEvent(evt)
   538       }
   539     }
   540   }
   541 }
   542 
   543 
   544 class Completion_Popup private(
   545   val active_range: Option[Text.Range],
   546   layered: JLayeredPane,
   547   location: Point,
   548   font: Font,
   549   items: List[Completion_Popup.Item]) extends JPanel(new BorderLayout)
   550 {
   551   completion =>
   552 
   553   Swing_Thread.require()
   554 
   555   require(!items.isEmpty)
   556   val multi = items.length > 1
   557 
   558 
   559   /* actions */
   560 
   561   def complete(item: Completion.Item) { }
   562   def propagate(evt: KeyEvent) { }
   563   def shutdown(focus: Boolean) { }
   564 
   565 
   566   /* list view */
   567 
   568   private val list_view = new ListView(items)
   569   list_view.font = font
   570   list_view.selection.intervalMode = ListView.IntervalMode.Single
   571   list_view.peer.setFocusTraversalKeysEnabled(false)
   572   list_view.peer.setVisibleRowCount(items.length min 8)
   573   list_view.peer.setSelectedIndex(0)
   574 
   575   for (cond <-
   576     List(JComponent.WHEN_FOCUSED,
   577       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   578       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   579 
   580   private def complete_selected(): Boolean =
   581   {
   582     list_view.selection.items.toList match {
   583       case item :: _ => complete(item.item); true
   584       case _ => false
   585     }
   586   }
   587 
   588   private def move_items(n: Int)
   589   {
   590     val i = list_view.peer.getSelectedIndex
   591     val j = ((i + n) min (items.length - 1)) max 0
   592     if (i != j) {
   593       list_view.peer.setSelectedIndex(j)
   594       list_view.peer.ensureIndexIsVisible(j)
   595     }
   596   }
   597 
   598   private def move_pages(n: Int)
   599   {
   600     val page_size = list_view.peer.getVisibleRowCount - 1
   601     move_items(page_size * n)
   602   }
   603 
   604 
   605   /* event handling */
   606 
   607   val inner_key_listener =
   608     JEdit_Lib.key_listener(
   609       key_pressed = (e: KeyEvent) =>
   610         {
   611           if (!e.isConsumed) {
   612             e.getKeyCode match {
   613               case KeyEvent.VK_TAB =>
   614                 if (complete_selected()) e.consume
   615                 hide_popup()
   616               case KeyEvent.VK_ESCAPE =>
   617                 hide_popup()
   618                 e.consume
   619               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   620                 move_items(-1)
   621                 e.consume
   622               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   623                 move_items(1)
   624                 e.consume
   625               case KeyEvent.VK_PAGE_UP if multi =>
   626                 move_pages(-1)
   627                 e.consume
   628               case KeyEvent.VK_PAGE_DOWN if multi =>
   629                 move_pages(1)
   630                 e.consume
   631               case _ =>
   632                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   633                   hide_popup()
   634             }
   635           }
   636           propagate(e)
   637         },
   638       key_typed = propagate _
   639     )
   640 
   641   list_view.peer.addKeyListener(inner_key_listener)
   642 
   643   list_view.peer.addMouseListener(new MouseAdapter {
   644     override def mouseClicked(e: MouseEvent) {
   645       if (complete_selected()) e.consume
   646       hide_popup()
   647     }
   648   })
   649 
   650   list_view.peer.addFocusListener(new FocusAdapter {
   651     override def focusLost(e: FocusEvent) { hide_popup() }
   652   })
   653 
   654 
   655   /* main content */
   656 
   657   override def getFocusTraversalKeysEnabled = false
   658   completion.setBorder(new LineBorder(Color.BLACK))
   659   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   660 
   661 
   662   /* popup */
   663 
   664   private val popup =
   665   {
   666     val screen = JEdit_Lib.screen_location(layered, location)
   667     val size =
   668     {
   669       val geometry = JEdit_Lib.window_geometry(completion, completion)
   670       val bounds = Rendering.popup_bounds
   671       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   672       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   673       new Dimension(w, h)
   674     }
   675     new Popup(layered, completion, screen.relative(layered, size), size)
   676   }
   677 
   678   private def show_popup(focus: Boolean)
   679   {
   680     popup.show
   681     if (focus) list_view.requestFocus
   682   }
   683 
   684   private def hide_popup()
   685   {
   686     shutdown(list_view.peer.isFocusOwner)
   687     popup.hide
   688   }
   689 }
   690