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