src/Tools/jEdit/src/completion_popup.scala
author wenzelm
Tue Sep 24 19:41:14 2013 +0200 (2013-09-24 ago)
changeset 53848 8d7029eb0c31
parent 53784 322a3ff42b33
child 53851 86c8f15afd88
permissions -rw-r--r--
disable standard behaviour of Mac OS X text field (i.e. select-all after focus gain) in order to make completion work more smoothly;
     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           case _ =>
   263         }
   264       }
   265     }
   266 
   267 
   268     /* completion action */
   269 
   270     def action()
   271     {
   272       GUI.layered_pane(text_field) match {
   273         case Some(layered) if text_field.isEditable =>
   274           val history = PIDE.completion_history.value
   275 
   276           val caret = text_field.getCaret.getDot
   277           val text = text_field.getText.substring(0, caret)
   278 
   279           syntax.completion.complete(history, decode = true, explicit = false, text) match {
   280             case Some(result) =>
   281               val fm = text_field.getFontMetrics(text_field.getFont)
   282               val loc =
   283                 SwingUtilities.convertPoint(text_field, fm.stringWidth(text), fm.getHeight, layered)
   284               val font =
   285                 text_field.getFont.deriveFont(Rendering.font_size("jedit_popup_font_scale"))
   286 
   287               val completion = new Completion_Popup(layered, loc, font, result.items)
   288               {
   289                 override def complete(item: Completion.Item) {
   290                   PIDE.completion_history.update(item)
   291                   insert(item)
   292                 }
   293                 override def propagate(evt: KeyEvent) {
   294                   if (!evt.isConsumed) text_field.processKeyEvent(evt)
   295                 }
   296                 override def refocus() { text_field.requestFocus }
   297               }
   298               completion_popup = Some(completion)
   299               completion.show_popup()
   300 
   301             case None =>
   302           }
   303         case _ =>
   304       }
   305     }
   306 
   307 
   308     /* process key event */
   309 
   310     private def process(evt: KeyEvent)
   311     {
   312       if (PIDE.options.bool("jedit_completion")) {
   313         dismissed()
   314         if (evt.getKeyChar != '\b') {
   315           val special = JEdit_Lib.special_key(evt)
   316           if (PIDE.options.seconds("jedit_completion_delay").is_zero && !special) {
   317             process_delay.revoke()
   318             action()
   319           }
   320           else process_delay.invoke()
   321         }
   322       }
   323     }
   324 
   325     private val process_delay =
   326       Swing_Thread.delay_last(PIDE.options.seconds("jedit_completion_delay")) {
   327         action()
   328       }
   329 
   330     override def processKeyEvent(evt0: KeyEvent)
   331     {
   332       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   333       if (evt != null) {
   334         evt.getID match {
   335           case KeyEvent.KEY_PRESSED =>
   336             val key_code = evt.getKeyCode
   337             if (key_code == KeyEvent.VK_ESCAPE) {
   338               if (dismissed()) evt.consume
   339             }
   340           case KeyEvent.KEY_TYPED =>
   341             super.processKeyEvent(evt)
   342             process(evt)
   343             evt.consume
   344           case _ =>
   345         }
   346         if (!evt.isConsumed) super.processKeyEvent(evt)
   347       }
   348     }
   349   }
   350 }
   351 
   352 
   353 class Completion_Popup private(
   354   layered: JLayeredPane,
   355   location: Point,
   356   font: Font,
   357   items: List[Completion.Item]) extends JPanel(new BorderLayout)
   358 {
   359   completion =>
   360 
   361   Swing_Thread.require()
   362 
   363   require(!items.isEmpty)
   364   val multi = items.length > 1
   365 
   366 
   367   /* actions */
   368 
   369   def complete(item: Completion.Item) { }
   370   def propagate(evt: KeyEvent) { }
   371   def refocus() { }
   372 
   373 
   374   /* list view */
   375 
   376   private val list_view = new ListView(items)
   377   list_view.font = font
   378   list_view.selection.intervalMode = ListView.IntervalMode.Single
   379   list_view.peer.setFocusTraversalKeysEnabled(false)
   380   list_view.peer.setVisibleRowCount(items.length min 8)
   381   list_view.peer.setSelectedIndex(0)
   382 
   383   for (cond <-
   384     List(JComponent.WHEN_FOCUSED,
   385       JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
   386       JComponent.WHEN_IN_FOCUSED_WINDOW)) list_view.peer.setInputMap(cond, null)
   387 
   388   private def complete_selected(): Boolean =
   389   {
   390     list_view.selection.items.toList match {
   391       case item :: _ => complete(item); true
   392       case _ => false
   393     }
   394   }
   395 
   396   private def move_items(n: Int)
   397   {
   398     val i = list_view.peer.getSelectedIndex
   399     val j = ((i + n) min (items.length - 1)) max 0
   400     if (i != j) {
   401       list_view.peer.setSelectedIndex(j)
   402       list_view.peer.ensureIndexIsVisible(j)
   403     }
   404   }
   405 
   406   private def move_pages(n: Int)
   407   {
   408     val page_size = list_view.peer.getVisibleRowCount - 1
   409     move_items(page_size * n)
   410   }
   411 
   412 
   413   /* event handling */
   414 
   415   private val inner_key_listener =
   416     JEdit_Lib.key_listener(
   417       key_pressed = (e: KeyEvent) =>
   418         {
   419           if (!e.isConsumed) {
   420             e.getKeyCode match {
   421               case KeyEvent.VK_TAB =>
   422                 if (complete_selected()) e.consume
   423                 hide_popup()
   424               case KeyEvent.VK_ESCAPE =>
   425                 hide_popup()
   426                 e.consume
   427               case KeyEvent.VK_UP | KeyEvent.VK_KP_UP if multi =>
   428                 move_items(-1)
   429                 e.consume
   430               case KeyEvent.VK_DOWN | KeyEvent.VK_KP_DOWN if multi =>
   431                 move_items(1)
   432                 e.consume
   433               case KeyEvent.VK_PAGE_UP if multi =>
   434                 move_pages(-1)
   435                 e.consume
   436               case KeyEvent.VK_PAGE_DOWN if multi =>
   437                 move_pages(1)
   438                 e.consume
   439               case _ =>
   440                 if (e.isActionKey || e.isAltDown || e.isMetaDown || e.isControlDown)
   441                   hide_popup()
   442             }
   443           }
   444           propagate(e)
   445         },
   446       key_typed = propagate _
   447     )
   448 
   449   list_view.peer.addKeyListener(inner_key_listener)
   450 
   451   list_view.peer.addMouseListener(new MouseAdapter {
   452     override def mouseClicked(e: MouseEvent) {
   453       if (complete_selected()) e.consume
   454       hide_popup()
   455     }
   456   })
   457 
   458   list_view.peer.addFocusListener(new FocusAdapter {
   459     override def focusLost(e: FocusEvent) { hide_popup() }
   460   })
   461 
   462 
   463   /* main content */
   464 
   465   override def getFocusTraversalKeysEnabled = false
   466   completion.setBorder(new LineBorder(Color.BLACK))
   467   completion.add((new ScrollPane(list_view)).peer.asInstanceOf[JComponent])
   468 
   469 
   470   /* popup */
   471 
   472   private val popup =
   473   {
   474     val screen = JEdit_Lib.screen_location(layered, location)
   475     val size =
   476     {
   477       val geometry = JEdit_Lib.window_geometry(completion, completion)
   478       val bounds = Rendering.popup_bounds
   479       val w = geometry.width min (screen.bounds.width * bounds).toInt min layered.getWidth
   480       val h = geometry.height min (screen.bounds.height * bounds).toInt min layered.getHeight
   481       new Dimension(w, h)
   482     }
   483     new Popup(layered, completion, screen.relative(layered, size), size)
   484   }
   485 
   486   private def show_popup()
   487   {
   488     popup.show
   489     list_view.requestFocus
   490   }
   491 
   492   private def hide_popup()
   493   {
   494     val had_focus = list_view.peer.isFocusOwner
   495     popup.hide
   496     if (had_focus) refocus()
   497   }
   498 }
   499