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