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