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