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