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