2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2019 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import jexer
.bits
.CellAttributes
;
32 import jexer
.bits
.GraphicsChars
;
33 import jexer
.bits
.StringUtils
;
34 import jexer
.event
.TCommandEvent
;
35 import jexer
.event
.TKeypressEvent
;
36 import jexer
.event
.TMouseEvent
;
37 import static jexer
.TCommand
.*;
38 import static jexer
.TKeypress
.*;
41 * TField implements an editable text field.
43 public class TField
extends TWidget
implements EditMenuUser
{
45 // ------------------------------------------------------------------------
46 // Variables --------------------------------------------------------------
47 // ------------------------------------------------------------------------
50 * Background character for unfilled-in text.
52 protected int backgroundChar
= GraphicsChars
.HATCH
;
57 protected String text
= "";
60 * If true, only allow enough characters that will fit in the width. If
61 * false, allow the field to scroll to the right.
63 protected boolean fixed
= false;
66 * Current editing position within text.
68 protected int position
= 0;
71 * Current editing position screen column number.
73 protected int screenPosition
= 0;
76 * Beginning of visible portion.
78 protected int windowStart
= 0;
81 * If true, new characters are inserted at position.
83 protected boolean insertMode
= true;
86 * Remember mouse state.
88 protected TMouseEvent mouse
;
91 * The action to perform when the user presses enter.
93 protected TAction enterAction
;
96 * The action to perform when the text is updated.
98 protected TAction updateAction
;
101 * The color to use when this field is active.
103 private String activeColorKey
= "tfield.active";
106 * The color to use when this field is not active.
108 private String inactiveColorKey
= "tfield.inactive";
110 // ------------------------------------------------------------------------
111 // Constructors -----------------------------------------------------------
112 // ------------------------------------------------------------------------
115 * Public constructor.
117 * @param parent parent widget
118 * @param x column relative to parent
119 * @param y row relative to parent
120 * @param width visible text width
121 * @param fixed if true, the text cannot exceed the display width
123 public TField(final TWidget parent
, final int x
, final int y
,
124 final int width
, final boolean fixed
) {
126 this(parent
, x
, y
, width
, fixed
, "", null, null);
130 * Public constructor.
132 * @param parent parent widget
133 * @param x column relative to parent
134 * @param y row relative to parent
135 * @param width visible text width
136 * @param fixed if true, the text cannot exceed the display width
137 * @param text initial text, default is empty string
139 public TField(final TWidget parent
, final int x
, final int y
,
140 final int width
, final boolean fixed
, final String text
) {
142 this(parent
, x
, y
, width
, fixed
, text
, null, null);
146 * Public constructor.
148 * @param parent parent widget
149 * @param x column relative to parent
150 * @param y row relative to parent
151 * @param width visible text width
152 * @param fixed if true, the text cannot exceed the display width
153 * @param text initial text, default is empty string
154 * @param enterAction function to call when enter key is pressed
155 * @param updateAction function to call when the text is updated
157 public TField(final TWidget parent
, final int x
, final int y
,
158 final int width
, final boolean fixed
, final String text
,
159 final TAction enterAction
, final TAction updateAction
) {
161 // Set parent and window
162 super(parent
, x
, y
, width
, 1);
164 setCursorVisible(true);
167 this.enterAction
= enterAction
;
168 this.updateAction
= updateAction
;
171 // ------------------------------------------------------------------------
172 // Event handlers ---------------------------------------------------------
173 // ------------------------------------------------------------------------
176 * Returns true if the mouse is currently on the field.
178 * @return if true the mouse is currently on the field
180 protected boolean mouseOnField() {
181 int rightEdge
= getWidth() - 1;
183 && (mouse
.getY() == 0)
184 && (mouse
.getX() >= 0)
185 && (mouse
.getX() <= rightEdge
)
193 * Handle mouse button presses.
195 * @param mouse mouse button event
198 public void onMouseDown(final TMouseEvent mouse
) {
201 if ((mouseOnField()) && (mouse
.isMouse1())) {
203 int deltaX
= mouse
.getX() - getCursorX();
204 screenPosition
+= deltaX
;
205 if (screenPosition
> StringUtils
.width(text
)) {
206 screenPosition
= StringUtils
.width(text
);
208 position
= screenToTextPosition(screenPosition
);
217 * @param keypress keystroke event
220 public void onKeypress(final TKeypressEvent keypress
) {
222 if (keypress
.equals(kbLeft
)) {
224 screenPosition
-= StringUtils
.width(text
.codePointBefore(position
));
225 position
-= Character
.charCount(text
.codePointBefore(position
));
227 if (fixed
== false) {
228 if ((screenPosition
== windowStart
) && (windowStart
> 0)) {
229 windowStart
-= StringUtils
.width(text
.codePointAt(
230 screenToTextPosition(windowStart
)));
233 normalizeWindowStart();
237 if (keypress
.equals(kbRight
)) {
238 if (position
< text
.length()) {
239 int lastPosition
= position
;
240 screenPosition
+= StringUtils
.width(text
.codePointAt(position
));
241 position
+= Character
.charCount(text
.codePointAt(position
));
243 if (screenPosition
== getWidth()) {
245 position
-= Character
.charCount(text
.codePointAt(lastPosition
));
248 while ((screenPosition
- windowStart
+
249 StringUtils
.width(text
.codePointAt(text
.length() - 1)))
252 windowStart
+= StringUtils
.width(text
.codePointAt(
253 screenToTextPosition(windowStart
)));
257 assert (position
<= text
.length());
261 if (keypress
.equals(kbEnter
)) {
266 if (keypress
.equals(kbIns
)) {
267 insertMode
= !insertMode
;
270 if (keypress
.equals(kbHome
)) {
275 if (keypress
.equals(kbEnd
)) {
280 if (keypress
.equals(kbDel
)) {
281 if ((text
.length() > 0) && (position
< text
.length())) {
282 text
= text
.substring(0, position
)
283 + text
.substring(position
+ 1);
284 screenPosition
= StringUtils
.width(text
.substring(0, position
));
290 if (keypress
.equals(kbBackspace
) || keypress
.equals(kbBackspaceDel
)) {
292 position
-= Character
.charCount(text
.codePointBefore(position
));
293 text
= text
.substring(0, position
)
294 + text
.substring(position
+ 1);
295 screenPosition
= StringUtils
.width(text
.substring(0, position
));
297 if (fixed
== false) {
298 if ((screenPosition
>= windowStart
)
301 windowStart
-= StringUtils
.width(text
.codePointAt(
302 screenToTextPosition(windowStart
)));
306 normalizeWindowStart();
310 if (!keypress
.getKey().isFnKey()
311 && !keypress
.getKey().isAlt()
312 && !keypress
.getKey().isCtrl()
314 // Plain old keystroke, process it
315 if ((position
== text
.length())
316 && (StringUtils
.width(text
) < getWidth())) {
319 appendChar(keypress
.getKey().getChar());
320 } else if ((position
< text
.length())
321 && (StringUtils
.width(text
) < getWidth())) {
323 // Overwrite or insert a character
324 if (insertMode
== false) {
326 text
= text
.substring(0, position
)
327 + codePointString(keypress
.getKey().getChar())
328 + text
.substring(position
+ 1);
329 screenPosition
+= StringUtils
.width(text
.codePointAt(position
));
330 position
+= Character
.charCount(keypress
.getKey().getChar());
333 insertChar(keypress
.getKey().getChar());
335 } else if ((position
< text
.length())
336 && (StringUtils
.width(text
) >= getWidth())) {
338 // Multiple cases here
339 if ((fixed
== true) && (insertMode
== true)) {
340 // Buffer is full, do nothing
341 } else if ((fixed
== true) && (insertMode
== false)) {
342 // Overwrite the last character, maybe move position
343 text
= text
.substring(0, position
)
344 + codePointString(keypress
.getKey().getChar())
345 + text
.substring(position
+ 1);
346 if (screenPosition
< getWidth() - 1) {
347 screenPosition
+= StringUtils
.width(text
.codePointAt(position
));
348 position
+= Character
.charCount(keypress
.getKey().getChar());
350 } else if ((fixed
== false) && (insertMode
== false)) {
351 // Overwrite the last character, definitely move position
352 text
= text
.substring(0, position
)
353 + codePointString(keypress
.getKey().getChar())
354 + text
.substring(position
+ 1);
355 screenPosition
+= StringUtils
.width(text
.codePointAt(position
));
356 position
+= Character
.charCount(keypress
.getKey().getChar());
358 if (position
== text
.length()) {
359 // Append this character
360 appendChar(keypress
.getKey().getChar());
362 // Insert this character
363 insertChar(keypress
.getKey().getChar());
369 // Append this character
370 appendChar(keypress
.getKey().getChar());
376 // Pass to parent for the things we don't care about.
377 super.onKeypress(keypress
);
381 * Handle posted command events.
383 * @param command command event
386 public void onCommand(final TCommandEvent command
) {
387 if (command
.equals(cmCut
)) {
388 // Copy text to clipboard, and then remove it.
389 getClipboard().copyText(text
);
394 if (command
.equals(cmCopy
)) {
395 // Copy text to clipboard.
396 getClipboard().copyText(text
);
400 if (command
.equals(cmPaste
)) {
401 // Paste text from clipboard.
402 String newText
= getClipboard().pasteText();
403 if (newText
!= null) {
409 if (command
.equals(cmClear
)) {
417 // ------------------------------------------------------------------------
418 // TWidget ----------------------------------------------------------------
419 // ------------------------------------------------------------------------
422 * Override TWidget's height: we can only set height at construction
425 * @param height new widget height (ignored)
428 public void setHeight(final int height
) {
433 * Draw the text field.
437 CellAttributes fieldColor
;
439 if (isAbsoluteActive()) {
440 fieldColor
= getTheme().getColor(activeColorKey
);
442 fieldColor
= getTheme().getColor(inactiveColorKey
);
445 int end
= windowStart
+ getWidth();
446 if (end
> StringUtils
.width(text
)) {
447 end
= StringUtils
.width(text
);
449 hLineXY(0, 0, getWidth(), backgroundChar
, fieldColor
);
450 putStringXY(0, 0, text
.substring(screenToTextPosition(windowStart
),
451 screenToTextPosition(end
)), fieldColor
);
453 // Fix the cursor, it will be rendered by TApplication.drawAll().
457 // ------------------------------------------------------------------------
458 // TField -----------------------------------------------------------------
459 // ------------------------------------------------------------------------
462 * Convert a char (codepoint) to a string.
467 private String
codePointString(final int ch
) {
468 StringBuilder sb
= new StringBuilder(1);
469 sb
.append(Character
.toChars(ch
));
470 assert (Character
.charCount(ch
) == sb
.length());
471 return sb
.toString();
475 * Get field background character.
477 * @return background character
479 public final int getBackgroundChar() {
480 return backgroundChar
;
484 * Set field background character.
486 * @param backgroundChar the background character
488 public void setBackgroundChar(final int backgroundChar
) {
489 this.backgroundChar
= backgroundChar
;
497 public final String
getText() {
504 * @param text the new field text
506 public void setText(final String text
) {
507 assert (text
!= null);
512 if ((fixed
== true) && (this.text
.length() > getWidth())) {
513 this.text
= this.text
.substring(0, getWidth());
518 * Dispatch to the action function.
520 * @param enter if true, the user pressed Enter, else this was an update
523 protected void dispatch(final boolean enter
) {
525 if (enterAction
!= null) {
526 enterAction
.DO(this);
529 if (updateAction
!= null) {
530 updateAction
.DO(this);
536 * Determine string position from screen position.
538 * @param screenPosition the position on screen
539 * @return the equivalent position in text
541 protected int screenToTextPosition(final int screenPosition
) {
542 if (screenPosition
== 0) {
547 for (int i
= 0; i
< text
.length(); i
++) {
548 n
+= StringUtils
.width(text
.codePointAt(i
));
549 if (n
>= screenPosition
) {
553 // screenPosition exceeds the available text length.
554 throw new IndexOutOfBoundsException("screenPosition " + screenPosition
+
555 " exceeds available text length " + text
.length());
559 * Update the visible cursor position to match the location of position
562 protected void updateCursor() {
563 if ((screenPosition
> getWidth()) && fixed
) {
564 setCursorX(getWidth());
565 } else if ((screenPosition
- windowStart
>= getWidth()) && !fixed
) {
566 setCursorX(getWidth() - 1);
568 setCursorX(screenPosition
- windowStart
);
573 * Normalize windowStart such that most of the field data if visible.
575 protected void normalizeWindowStart() {
577 // windowStart had better be zero, there is nothing to do here.
578 assert (windowStart
== 0);
581 windowStart
= screenPosition
- (getWidth() - 1);
582 if (windowStart
< 0) {
590 * Append char to the end of the field.
592 * @param ch char to append
594 protected void appendChar(final int ch
) {
595 // Append the LAST character
596 text
+= codePointString(ch
);
597 position
+= Character
.charCount(ch
);
598 screenPosition
+= StringUtils
.width(ch
);
600 assert (position
== text
.length());
603 if (screenPosition
>= getWidth()) {
604 position
-= Character
.charCount(ch
);
605 screenPosition
-= StringUtils
.width(ch
);
608 if ((screenPosition
- windowStart
) >= getWidth()) {
615 * Insert char somewhere in the middle of the field.
617 * @param ch char to append
619 protected void insertChar(final int ch
) {
620 text
= text
.substring(0, position
) + codePointString(ch
)
621 + text
.substring(position
);
622 position
+= Character
.charCount(ch
);
623 screenPosition
+= StringUtils
.width(ch
);
624 if ((screenPosition
- windowStart
) == getWidth()) {
631 * Position the cursor at the first column. The field may adjust the
632 * window start to show as much of the field as possible.
641 * Set the editing position to the last filled character. The field may
642 * adjust the window start to show as much of the field as possible.
645 position
= text
.length();
646 screenPosition
= StringUtils
.width(text
);
648 if (screenPosition
>= getWidth()) {
649 position
-= Character
.charCount(text
.codePointBefore(position
));
650 screenPosition
= StringUtils
.width(text
) - 1;
653 windowStart
= StringUtils
.width(text
) - getWidth() + 1;
654 if (windowStart
< 0) {
661 * Set the editing position. The field may adjust the window start to
662 * show as much of the field as possible.
664 * @param position the new position
665 * @throws IndexOutOfBoundsException if position is outside the range of
668 public void setPosition(final int position
) {
669 if ((position
< 0) || (position
>= text
.length())) {
670 throw new IndexOutOfBoundsException("Max length is " +
671 text
.length() + ", requested position " + position
);
673 this.position
= position
;
674 normalizeWindowStart();
678 * Set the active color key.
680 * @param activeColorKey ColorTheme key color to use when this field is
683 public void setActiveColorKey(final String activeColorKey
) {
684 this.activeColorKey
= activeColorKey
;
688 * Set the inactive color key.
690 * @param inactiveColorKey ColorTheme key color to use when this field is
693 public void setInactiveColorKey(final String inactiveColorKey
) {
694 this.inactiveColorKey
= inactiveColorKey
;
698 * Set the action to perform when the user presses enter.
700 * @param action the action to perform when the user presses enter
702 public void setEnterAction(final TAction action
) {
703 enterAction
= action
;
707 * Set the action to perform when the field is updated.
709 * @param action the action to perform when the field is updated
711 public void setUpdateAction(final TAction action
) {
712 updateAction
= action
;
715 // ------------------------------------------------------------------------
716 // EditMenuUser -----------------------------------------------------------
717 // ------------------------------------------------------------------------
720 * Check if the cut menu item should be enabled.
722 * @return true if the cut menu item should be enabled
724 public boolean isEditMenuCut() {
729 * Check if the copy menu item should be enabled.
731 * @return true if the copy menu item should be enabled
733 public boolean isEditMenuCopy() {
738 * Check if the paste menu item should be enabled.
740 * @return true if the paste menu item should be enabled
742 public boolean isEditMenuPaste() {
747 * Check if the clear menu item should be enabled.
749 * @return true if the clear menu item should be enabled
751 public boolean isEditMenuClear() {