src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Sun Sep 29 18:51:01 2013 +0200 (2013-09-29 ago)
changeset 53987 16a0cd5293d9
parent 53851 86c8f15afd88
child 54376 3eb84b6b0353
permissions -rw-r--r--
explicit caret position after replacement;
     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
    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: JEditTextArea): Option[Completion_Popup.Text_Area] =
    35       text_area.getClientProperty(key) match {
    36         case text_area_completion: Completion_Popup.Text_Area => Some(text_area_completion)
    37         case _ => None
    38       }
    39 
    40     def exit(text_area: JEditTextArea)
    41     {
    42       Swing_Thread.require()
    43       apply(text_area) match {
    44         case None =>
    45         case Some(text_area_completion) =>
    46           text_area_completion.deactivate()
    47           text_area.putClientProperty(key, null)
    48       }
    49     }
    50 
    51     def init(text_area: JEditTextArea): Completion_Popup.Text_Area =
    52     {
    53       exit(text_area)
    54       val text_area_completion = new Text_Area(text_area)
    55       text_area.putClientProperty(key, text_area_completion)
    56       text_area_completion.activate()
    57       text_area_completion
    58     }
    59 
    60     def dismissed(text_area: JEditTextArea): Boolean =
    61     {
    62       Swing_Thread.require()
    63       apply(text_area) match {
    64         case Some(text_area_completion) => text_area_completion.dismissed()
    65         case None => false
    66       }
    67     }
    68   }
    69 
    70   class Text_Area private(text_area: JEditTextArea)
    71   {
    72     private var completion_popup: Option[Completion_Popup] = None
    73 
    74 
    75     /* completion action */
    76 
    77     private def insert(item: Completion.Item)
    78     {
    79       Swing_Thread.require()
    80 
    81       val buffer = text_area.getBuffer
    82       val len = item.original.length
    83       if (buffer.isEditable && len > 0) {
    84         JEdit_Lib.buffer_edit(buffer) {
    85           val caret = text_area.getCaretPosition
    86           JEdit_Lib.try_get_text(buffer, Text.Range(caret - len, caret)) match {
    87             case Some(text) if text == item.original =>
    88               buffer.remove(caret - len, len)
    89               buffer.insert(caret - len, item.replacement)
    90             case _ =>
    91           }
    92         }
    93       }
    94     }
    95 
    96     def action(immediate: Boolean = false, explicit: Boolean = false)
    97     {
    98       val view = text_area.getView
    99       val layered = view.getLayeredPane
   100       val buffer = text_area.getBuffer
   101       val painter = text_area.getPainter
   102 
   103       if (buffer.isEditable) {
   104         Isabelle.mode_syntax(JEdit_Lib.buffer_mode(buffer)) match {
   105           case Some(syntax) =>
   106             val caret = text_area.getCaretPosition
   107             val line = buffer.getLineOfOffset(caret)
   108             val start = buffer.getLineStartOffset(line)
   109             val text = buffer.getSegment(start, caret - start)
   110 
   111             val history = PIDE.completion_history.value
   112             val decode = Isabelle_Encoding.is_active(buffer)
   113             syntax.completion.complete(history, decode, explicit, text) match {
   114               case Some(result) =>
   115                 if (result.unique && result.items.head.immediate && immediate)
   116                   insert(result.items.head)
   117                 else {
   118                   val font =
   119                     painter.getFont.deriveFont(Rendering.font_size("jedit_popup_font_scale"))
   120 
   121                   val loc1 = text_area.offsetToXY(caret - result.original.length)
   122                   if (loc1 != null) {
   123                     val loc2 =
   124                       SwingUtilities.convertPoint(painter,
   125                         loc1.x, loc1.y + painter.getFontMetrics.getHeight, layered)
   126 
   127                     val completion =
   128                       new Completion_Popup(layered, loc2, font, result.items) {
   129                         override def complete(item: Completion.Item) {
   130                           PIDE.completion_history.update(item)
   131                           insert(item)
   132                         }
   133                         override def propagate(evt: KeyEvent) {
   134                           JEdit_Lib.propagate_key(view, evt)
   135                           input(evt)
   136                         }
   137                         override def refocus() { text_area.requestFocus }
   138                       }
   139                     completion_popup = Some(completion)
   140                     completion.show_popup()
   141                   }
   142                 }
   143               case None =>
   144             }
   145           case None =>
   146         }
   147       }
   148     }
   149 
   150 
   151     /* input key events */
   152 
   153     def input(evt: KeyEvent)
   154     {
   155       Swing_Thread.require()
   156 
   157       if (PIDE.options.bool("jedit_completion")) {
   158         if (!evt.isConsumed) {
   159           dismissed()
   160           if (evt.getKeyChar != '\b') {
   161             val special = JEdit_Lib.special_key(evt)
   162             if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   163               input_delay.revoke()
   164               action(immediate = PIDE.options.bool("jedit_completion_immediate"))
   165             }
   166             else input_delay.invoke()
   167           }
   168         }
   169       }
   170     }
   171 
   172     private val input_delay =
   173       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   174         action()
   175       }
   176 
   177 
   178     /* dismiss popup */
   179 
   180     def dismissed(): Boolean =
   181     {
   182       Swing_Thread.require()
   183 
   184       completion_popup match {
   185         case Some(completion) =>
   186           completion.hide_popup()
   187           completion_popup = None
   188           true
   189         case None =>
   190           false
   191       }
   192     }
   193 
   194 
   195     /* activation */
   196 
   197     private val outer_key_listener =
   198       JEdit_Lib.key_listener(key_typed = input _)
   199 
   200     private def activate()
   201     {
   202       text_area.addKeyListener(outer_key_listener)
   203     }
   204 
   205     private def deactivate()
   206     {
   207       dismissed()
   208       text_area.removeKeyListener(outer_key_listener)
   209     }
   210   }
   211 
   212 
   213 
   214   /** history text field **/
   215 
   216   class History_Text_Field(
   217     name: String = null,
   218     instant_popups: Boolean = false,
   219     enter_adds_to_history: Boolean = true,
   220     syntax: Outer_Syntax = Outer_Syntax.init) extends
   221     HistoryTextField(name, instant_popups, enter_adds_to_history)
   222   {
   223     text_field =>
   224 
   225     // see https://forums.oracle.com/thread/1361677
   226     if (GUI.is_macos_laf) text_field.setCaret(new DefaultCaret)
   227 
   228     private var completion_popup: Option[Completion_Popup] = None
   229 
   230 
   231     /* dismiss */
   232 
   233     private def dismissed(): Boolean =
   234     {
   235       completion_popup match {
   236         case Some(completion) =>
   237           completion.hide_popup()
   238           completion_popup = None
   239           true
   240         case None =>
   241           false
   242       }
   243     }
   244 
   245 
   246     /* insert */
   247 
   248     private def insert(item: Completion.Item)
   249     {
   250       Swing_Thread.require()
   251 
   252       val len = item.original.length
   253       if (text_field.isEditable && len > 0) {
   254         val caret = text_field.getCaret.getDot
   255         val content = text_field.getText
   256         JEdit_Lib.try_get_text(content, Text.Range(caret - len, caret)) match {
   257           case Some(text) if text == item.original =>
   258             text_field.setText(
   259               content.substring(0, caret - len) +
   260               item.replacement +
   261               content.substring(caret))
   262             text_field.getCaret.setDot(caret - len + item.replacement.length)
   263           case _ =>
   264         }
   265       }
   266     }
   267 
   268 
   269     /* completion action */
   270 
   271     def action()
   272     {
   273       GUI.layered_pane(text_field) match {
   274         case Some(layered) if text_field.isEditable =>
   275           val history = PIDE.completion_history.value
   276 
   277           val caret = text_field.getCaret.getDot
   278           val text = text_field.getText.substring(0, caret)
   279 
   280           syntax.completion.complete(history, decode = true, explicit = false, text) match {
   281             case Some(result) =>
   282               val fm = text_field.getFontMetrics(text_field.getFont)
   283               val loc =
   284                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   285 
   286               val completion = new Completion_Popup(layered, loc, text_field.getFont, result.items)
   287               {
   288                 override def complete(item: Completion.Item) {
   289                   PIDE.completion_history.update(item)
   290                   insert(item)
   291                 }
   292                 override def propagate(evt: KeyEvent) {
   293                   if (!evt.isConsumed) text_field.processKeyEvent(evt)
   294                 }
   295                 override def refocus() { text_field.requestFocus }
   296               }
   297               completion_popup = Some(completion)
   298               completion.show_popup()
   299 
   300             case None =>
   301           }
   302         case _ =>
   303       }
   304     }
   305 
   306 
   307     /* process key event */
   308 
   309     private def process(evt: KeyEvent)
   310     {
   311       if (PIDE.options.bool("jedit_completion")) {
   312         dismissed()
   313         if (evt.getKeyChar != '\b') {
   314           val special = JEdit_Lib.special_key(evt)
   315           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   316             process_delay.revoke()
   317             action()
   318           }
   319           else process_delay.invoke()
   320         }
   321       }
   322     }
   323 
   324     private val process_delay =
   325       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   326         action()
   327       }
   328 
   329     override def processKeyEvent(evt0: KeyEvent)
   330     {
   331       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   332       if (evt != null) {
   333         evt.getID match {
   334           case KeyEvent.KEY_PRESSED =>
   335             val key_code = evt.getKeyCode
   336             if (key_code == KeyEvent.VK_ESCAPE) {
   337               if (dismissed()) evt.consume
   338             }
   339           case KeyEvent.KEY_TYPED =>
   340             super.processKeyEvent(evt)
   341             process(evt)
   342             evt.consume
   343           case _ =>
   344         }
   345         if (!evt.isConsumed) super.processKeyEvent(evt)
   346       }
   347     }
   348   }
   349 }
   350 
   351 
   352 class Completion_Popup private(
   353   layered: JLayeredPane,
   354   location: Point,
   355   font: Font,
   356   items: List[Completion.Item]) extends JPanel(new BorderLayout)
   357 {
   358   completion =>
   359 
   360   Swing_Thread.require()
   361 
   362   require(!items.isEmpty)
   363   val multi = items.length > 1
   364 
   365 
   366   /* actions */
   367 
   368   def complete(item: Completion.Item) { }
   369   def propagate(evt: KeyEvent) { }
   370   def refocus() { }
   371 
   372 
   373   /* list view */
   374 
   375   private val list_view = new ListView(items)
   376   list_view.font = font
   377   list_view.selection.intervalMode = ListView.IntervalMode.Single
   378   list_view.peer.setFocusTraversalKeysEnabled(false)
   379   list_view.peer.setVisibleRowCount(items.length min 8)
   380   list_view.peer.setSelectedIndex(0)
   381 
   382   for (cond <-
   383     List(JComponent.WHEN_FOCUSED,
   384       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   385       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   386 
   387   private def complete_selected(): Boolean =
   388   {
   389     list_view.selection.items.toList match {
   390       case item :: _ => complete(item); true
   391       case _ => false
   392     }
   393   }
   394 
   395   private def move_items(n: Int)
   396   {
   397     val i = list_view.peer.getSelectedIndex
   398     val j = ((i + n) min (items.length - 1)) max 0
   399     if (i != j) {
   400       list_view.peer.setSelectedIndex(j)
   401       list_view.peer.ensureIndexIsVisible(j)
   402     }
   403   }
   404 
   405   private def move_pages(n: Int)
   406   {
   407     val page_size = list_view.peer.getVisibleRowCount - 1
   408     move_items(page_size * n)
   409   }
   410 
   411 
   412   /* event handling */
   413 
   414   private val inner_key_listener =
   415     JEdit_Lib.key_listener(
   416       key_pressed = (e: KeyEvent) =>
   417         {
   418           if (!e.isConsumed) {
   419             e.getKeyCode match {
   420               case KeyEvent.VK_TAB =>
   421                 if (complete_selected()) e.consume
   422                 hide_popup()
   423               case KeyEvent.VK_ESCAPE =>
   424                 hide_popup()
   425                 e.consume
   426               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   427                 move_items(-1)
   428                 e.consume
   429               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   430                 move_items(1)
   431                 e.consume
   432               case KeyEvent.VK_PAGE_UP if multi =>
   433                 move_pages(-1)
   434                 e.consume
   435               case KeyEvent.VK_PAGE_DOWN if multi =>
   436                 move_pages(1)
   437                 e.consume
   438               case _ =>
   439                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   440                   hide_popup()
   441             }
   442           }
   443           propagate(e)
   444         },
   445       key_typed = propagate _
   446     )
   447 
   448   list_view.peer.addKeyListener(inner_key_listener)
   449 
   450   list_view.peer.addMouseListener(new MouseAdapter {
   451     override def mouseClicked(e: MouseEvent) {
   452       if (complete_selected()) e.consume
   453       hide_popup()
   454     }
   455   })
   456 
   457   list_view.peer.addFocusListener(new FocusAdapter {
   458     override def focusLost(e: FocusEvent) { hide_popup() }
   459   })
   460 
   461 
   462   /* main content */
   463 
   464   override def getFocusTraversalKeysEnabled = false
   465   completion.setBorder(new LineBorder(Color.BLACK))
   466   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   467 
   468 
   469   /* popup */
   470 
   471   private val popup =
   472   {
   473     val screen = JEdit_Lib.screen_location(layered, location)
   474     val size =
   475     {
   476       val geometry = JEdit_Lib.window_geometry(completion, completion)
   477       val bounds = Rendering.popup_bounds
   478       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   479       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   480       new Dimension(w, h)
   481     }
   482     new Popup(layered, completion, screen.relative(layered, size), size)
   483   }
   484 
   485   private def show_popup()
   486   {
   487     popup.show
   488     list_view.requestFocus
   489   }
   490 
   491   private def hide_popup()
   492   {
   493     val had_focus = list_view.peer.isFocusOwner
   494     popup.hide
   495     if (had_focus) refocus()
   496   }
   497 }
   498