TField cut/paste working
[fanfix.git] / src / jexer / TField.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 Kevin Lamonte
7 *
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:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
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.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer;
30
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.*;
39
40 /**
41 * TField implements an editable text field.
42 */
43 public class TField extends TWidget implements EditMenuUser {
44
45 // ------------------------------------------------------------------------
46 // Variables --------------------------------------------------------------
47 // ------------------------------------------------------------------------
48
49 /**
50 * Background character for unfilled-in text.
51 */
52 protected int backgroundChar = GraphicsChars.HATCH;
53
54 /**
55 * Field text.
56 */
57 protected String text = "";
58
59 /**
60 * If true, only allow enough characters that will fit in the width. If
61 * false, allow the field to scroll to the right.
62 */
63 protected boolean fixed = false;
64
65 /**
66 * Current editing position within text.
67 */
68 protected int position = 0;
69
70 /**
71 * Current editing position screen column number.
72 */
73 protected int screenPosition = 0;
74
75 /**
76 * Beginning of visible portion.
77 */
78 protected int windowStart = 0;
79
80 /**
81 * If true, new characters are inserted at position.
82 */
83 protected boolean insertMode = true;
84
85 /**
86 * Remember mouse state.
87 */
88 protected TMouseEvent mouse;
89
90 /**
91 * The action to perform when the user presses enter.
92 */
93 protected TAction enterAction;
94
95 /**
96 * The action to perform when the text is updated.
97 */
98 protected TAction updateAction;
99
100 /**
101 * The color to use when this field is active.
102 */
103 private String activeColorKey = "tfield.active";
104
105 /**
106 * The color to use when this field is not active.
107 */
108 private String inactiveColorKey = "tfield.inactive";
109
110 // ------------------------------------------------------------------------
111 // Constructors -----------------------------------------------------------
112 // ------------------------------------------------------------------------
113
114 /**
115 * Public constructor.
116 *
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
122 */
123 public TField(final TWidget parent, final int x, final int y,
124 final int width, final boolean fixed) {
125
126 this(parent, x, y, width, fixed, "", null, null);
127 }
128
129 /**
130 * Public constructor.
131 *
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
138 */
139 public TField(final TWidget parent, final int x, final int y,
140 final int width, final boolean fixed, final String text) {
141
142 this(parent, x, y, width, fixed, text, null, null);
143 }
144
145 /**
146 * Public constructor.
147 *
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
156 */
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) {
160
161 // Set parent and window
162 super(parent, x, y, width, 1);
163
164 setCursorVisible(true);
165 this.fixed = fixed;
166 this.text = text;
167 this.enterAction = enterAction;
168 this.updateAction = updateAction;
169 }
170
171 // ------------------------------------------------------------------------
172 // Event handlers ---------------------------------------------------------
173 // ------------------------------------------------------------------------
174
175 /**
176 * Returns true if the mouse is currently on the field.
177 *
178 * @return if true the mouse is currently on the field
179 */
180 protected boolean mouseOnField() {
181 int rightEdge = getWidth() - 1;
182 if ((mouse != null)
183 && (mouse.getY() == 0)
184 && (mouse.getX() >= 0)
185 && (mouse.getX() <= rightEdge)
186 ) {
187 return true;
188 }
189 return false;
190 }
191
192 /**
193 * Handle mouse button presses.
194 *
195 * @param mouse mouse button event
196 */
197 @Override
198 public void onMouseDown(final TMouseEvent mouse) {
199 this.mouse = mouse;
200
201 if ((mouseOnField()) && (mouse.isMouse1())) {
202 // Move cursor
203 int deltaX = mouse.getX() - getCursorX();
204 screenPosition += deltaX;
205 if (screenPosition > StringUtils.width(text)) {
206 screenPosition = StringUtils.width(text);
207 }
208 position = screenToTextPosition(screenPosition);
209 updateCursor();
210 return;
211 }
212 }
213
214 /**
215 * Handle keystrokes.
216 *
217 * @param keypress keystroke event
218 */
219 @Override
220 public void onKeypress(final TKeypressEvent keypress) {
221
222 if (keypress.equals(kbLeft)) {
223 if (position > 0) {
224 screenPosition -= StringUtils.width(text.codePointBefore(position));
225 position -= Character.charCount(text.codePointBefore(position));
226 }
227 if (fixed == false) {
228 if ((screenPosition == windowStart) && (windowStart > 0)) {
229 windowStart -= StringUtils.width(text.codePointAt(
230 screenToTextPosition(windowStart)));
231 }
232 }
233 normalizeWindowStart();
234 return;
235 }
236
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));
242 if (fixed == true) {
243 if (screenPosition == getWidth()) {
244 screenPosition--;
245 position -= Character.charCount(text.codePointAt(lastPosition));
246 }
247 } else {
248 while ((screenPosition - windowStart +
249 StringUtils.width(text.codePointAt(text.length() - 1)))
250 > getWidth()
251 ) {
252 windowStart += StringUtils.width(text.codePointAt(
253 screenToTextPosition(windowStart)));
254 }
255 }
256 }
257 assert (position <= text.length());
258 return;
259 }
260
261 if (keypress.equals(kbEnter)) {
262 dispatch(true);
263 return;
264 }
265
266 if (keypress.equals(kbIns)) {
267 insertMode = !insertMode;
268 return;
269 }
270 if (keypress.equals(kbHome)) {
271 home();
272 return;
273 }
274
275 if (keypress.equals(kbEnd)) {
276 end();
277 return;
278 }
279
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));
285 }
286 dispatch(false);
287 return;
288 }
289
290 if (keypress.equals(kbBackspace) || keypress.equals(kbBackspaceDel)) {
291 if (position > 0) {
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));
296 }
297 if (fixed == false) {
298 if ((screenPosition >= windowStart)
299 && (windowStart > 0)
300 ) {
301 windowStart -= StringUtils.width(text.codePointAt(
302 screenToTextPosition(windowStart)));
303 }
304 }
305 dispatch(false);
306 normalizeWindowStart();
307 return;
308 }
309
310 if (!keypress.getKey().isFnKey()
311 && !keypress.getKey().isAlt()
312 && !keypress.getKey().isCtrl()
313 ) {
314 // Plain old keystroke, process it
315 if ((position == text.length())
316 && (StringUtils.width(text) < getWidth())) {
317
318 // Append case
319 appendChar(keypress.getKey().getChar());
320 } else if ((position < text.length())
321 && (StringUtils.width(text) < getWidth())) {
322
323 // Overwrite or insert a character
324 if (insertMode == false) {
325 // Replace character
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());
331 } else {
332 // Insert character
333 insertChar(keypress.getKey().getChar());
334 }
335 } else if ((position < text.length())
336 && (StringUtils.width(text) >= getWidth())) {
337
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());
349 }
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());
357 } else {
358 if (position == text.length()) {
359 // Append this character
360 appendChar(keypress.getKey().getChar());
361 } else {
362 // Insert this character
363 insertChar(keypress.getKey().getChar());
364 }
365 }
366 } else {
367 assert (!fixed);
368
369 // Append this character
370 appendChar(keypress.getKey().getChar());
371 }
372 dispatch(false);
373 return;
374 }
375
376 // Pass to parent for the things we don't care about.
377 super.onKeypress(keypress);
378 }
379 /**
380 * Handle posted command events.
381 *
382 * @param command command event
383 */
384 @Override
385 public void onCommand(final TCommandEvent command) {
386 if (command.equals(cmCut)) {
387 // Copy text to clipboard, and then remove it.
388 getClipboard().copyText(text);
389 setText("");
390 return;
391 }
392
393 if (command.equals(cmCopy)) {
394 // Copy text to clipboard.
395 getClipboard().copyText(text);
396 return;
397 }
398
399 if (command.equals(cmPaste)) {
400 // Paste text from clipboard.
401 String newText = getClipboard().pasteText();
402 if (newText != null) {
403 setText(newText);
404 }
405 return;
406 }
407
408 if (command.equals(cmClear)) {
409 // Remove text.
410 setText("");
411 return;
412 }
413
414 }
415
416 // ------------------------------------------------------------------------
417 // TWidget ----------------------------------------------------------------
418 // ------------------------------------------------------------------------
419
420 /**
421 * Override TWidget's height: we can only set height at construction
422 * time.
423 *
424 * @param height new widget height (ignored)
425 */
426 @Override
427 public void setHeight(final int height) {
428 // Do nothing
429 }
430
431 /**
432 * Draw the text field.
433 */
434 @Override
435 public void draw() {
436 CellAttributes fieldColor;
437
438 if (isAbsoluteActive()) {
439 fieldColor = getTheme().getColor(activeColorKey);
440 } else {
441 fieldColor = getTheme().getColor(inactiveColorKey);
442 }
443
444 int end = windowStart + getWidth();
445 if (end > StringUtils.width(text)) {
446 end = StringUtils.width(text);
447 }
448 hLineXY(0, 0, getWidth(), backgroundChar, fieldColor);
449 putStringXY(0, 0, text.substring(screenToTextPosition(windowStart),
450 screenToTextPosition(end)), fieldColor);
451
452 // Fix the cursor, it will be rendered by TApplication.drawAll().
453 updateCursor();
454 }
455
456 // ------------------------------------------------------------------------
457 // TField -----------------------------------------------------------------
458 // ------------------------------------------------------------------------
459
460 /**
461 * Convert a char (codepoint) to a string.
462 *
463 * @param ch the char
464 * @return the string
465 */
466 private String codePointString(final int ch) {
467 StringBuilder sb = new StringBuilder(1);
468 sb.append(Character.toChars(ch));
469 assert (Character.charCount(ch) == sb.length());
470 return sb.toString();
471 }
472
473 /**
474 * Get field background character.
475 *
476 * @return background character
477 */
478 public final int getBackgroundChar() {
479 return backgroundChar;
480 }
481
482 /**
483 * Set field background character.
484 *
485 * @param backgroundChar the background character
486 */
487 public void setBackgroundChar(final int backgroundChar) {
488 this.backgroundChar = backgroundChar;
489 }
490
491 /**
492 * Get field text.
493 *
494 * @return field text
495 */
496 public final String getText() {
497 return text;
498 }
499
500 /**
501 * Set field text.
502 *
503 * @param text the new field text
504 */
505 public void setText(final String text) {
506 assert (text != null);
507 this.text = text;
508 position = 0;
509 screenPosition = 0;
510 windowStart = 0;
511 if ((fixed == true) && (this.text.length() > getWidth())) {
512 this.text = this.text.substring(0, getWidth());
513 }
514 }
515
516 /**
517 * Dispatch to the action function.
518 *
519 * @param enter if true, the user pressed Enter, else this was an update
520 * to the text.
521 */
522 protected void dispatch(final boolean enter) {
523 if (enter) {
524 if (enterAction != null) {
525 enterAction.DO(this);
526 }
527 } else {
528 if (updateAction != null) {
529 updateAction.DO(this);
530 }
531 }
532 }
533
534 /**
535 * Determine string position from screen position.
536 *
537 * @param screenPosition the position on screen
538 * @return the equivalent position in text
539 */
540 protected int screenToTextPosition(final int screenPosition) {
541 if (screenPosition == 0) {
542 return 0;
543 }
544
545 int n = 0;
546 for (int i = 0; i < text.length(); i++) {
547 n += StringUtils.width(text.codePointAt(i));
548 if (n >= screenPosition) {
549 return i + 1;
550 }
551 }
552 // screenPosition exceeds the available text length.
553 throw new IndexOutOfBoundsException("screenPosition " + screenPosition +
554 " exceeds available text length " + text.length());
555 }
556
557 /**
558 * Update the visible cursor position to match the location of position
559 * and windowStart.
560 */
561 protected void updateCursor() {
562 if ((screenPosition > getWidth()) && fixed) {
563 setCursorX(getWidth());
564 } else if ((screenPosition - windowStart >= getWidth()) && !fixed) {
565 setCursorX(getWidth() - 1);
566 } else {
567 setCursorX(screenPosition - windowStart);
568 }
569 }
570
571 /**
572 * Normalize windowStart such that most of the field data if visible.
573 */
574 protected void normalizeWindowStart() {
575 if (fixed) {
576 // windowStart had better be zero, there is nothing to do here.
577 assert (windowStart == 0);
578 return;
579 }
580 windowStart = screenPosition - (getWidth() - 1);
581 if (windowStart < 0) {
582 windowStart = 0;
583 }
584
585 updateCursor();
586 }
587
588 /**
589 * Append char to the end of the field.
590 *
591 * @param ch char to append
592 */
593 protected void appendChar(final int ch) {
594 // Append the LAST character
595 text += codePointString(ch);
596 position += Character.charCount(ch);
597 screenPosition += StringUtils.width(ch);
598
599 assert (position == text.length());
600
601 if (fixed) {
602 if (screenPosition >= getWidth()) {
603 position -= Character.charCount(ch);
604 screenPosition -= StringUtils.width(ch);
605 }
606 } else {
607 if ((screenPosition - windowStart) >= getWidth()) {
608 windowStart++;
609 }
610 }
611 }
612
613 /**
614 * Insert char somewhere in the middle of the field.
615 *
616 * @param ch char to append
617 */
618 protected void insertChar(final int ch) {
619 text = text.substring(0, position) + codePointString(ch)
620 + text.substring(position);
621 position += Character.charCount(ch);
622 screenPosition += StringUtils.width(ch);
623 if ((screenPosition - windowStart) == getWidth()) {
624 assert (!fixed);
625 windowStart++;
626 }
627 }
628
629 /**
630 * Position the cursor at the first column. The field may adjust the
631 * window start to show as much of the field as possible.
632 */
633 public void home() {
634 position = 0;
635 screenPosition = 0;
636 windowStart = 0;
637 }
638
639 /**
640 * Set the editing position to the last filled character. The field may
641 * adjust the window start to show as much of the field as possible.
642 */
643 public void end() {
644 position = text.length();
645 screenPosition = StringUtils.width(text);
646 if (fixed == true) {
647 if (screenPosition >= getWidth()) {
648 position -= Character.charCount(text.codePointBefore(position));
649 screenPosition = StringUtils.width(text) - 1;
650 }
651 } else {
652 windowStart = StringUtils.width(text) - getWidth() + 1;
653 if (windowStart < 0) {
654 windowStart = 0;
655 }
656 }
657 }
658
659 /**
660 * Set the editing position. The field may adjust the window start to
661 * show as much of the field as possible.
662 *
663 * @param position the new position
664 * @throws IndexOutOfBoundsException if position is outside the range of
665 * the available text
666 */
667 public void setPosition(final int position) {
668 if ((position < 0) || (position >= text.length())) {
669 throw new IndexOutOfBoundsException("Max length is " +
670 text.length() + ", requested position " + position);
671 }
672 this.position = position;
673 normalizeWindowStart();
674 }
675
676 /**
677 * Set the active color key.
678 *
679 * @param activeColorKey ColorTheme key color to use when this field is
680 * active
681 */
682 public void setActiveColorKey(final String activeColorKey) {
683 this.activeColorKey = activeColorKey;
684 }
685
686 /**
687 * Set the inactive color key.
688 *
689 * @param inactiveColorKey ColorTheme key color to use when this field is
690 * inactive
691 */
692 public void setInactiveColorKey(final String inactiveColorKey) {
693 this.inactiveColorKey = inactiveColorKey;
694 }
695
696 /**
697 * Set the action to perform when the user presses enter.
698 *
699 * @param action the action to perform when the user presses enter
700 */
701 public void setEnterAction(final TAction action) {
702 enterAction = action;
703 }
704
705 /**
706 * Set the action to perform when the field is updated.
707 *
708 * @param action the action to perform when the field is updated
709 */
710 public void setUpdateAction(final TAction action) {
711 updateAction = action;
712 }
713
714 // ------------------------------------------------------------------------
715 // EditMenuUser -----------------------------------------------------------
716 // ------------------------------------------------------------------------
717
718 /**
719 * Check if the cut menu item should be enabled.
720 *
721 * @return true if the cut menu item should be enabled
722 */
723 public boolean isEditMenuCut() {
724 return true;
725 }
726
727 /**
728 * Check if the copy menu item should be enabled.
729 *
730 * @return true if the copy menu item should be enabled
731 */
732 public boolean isEditMenuCopy() {
733 return true;
734 }
735
736 /**
737 * Check if the paste menu item should be enabled.
738 *
739 * @return true if the paste menu item should be enabled
740 */
741 public boolean isEditMenuPaste() {
742 return true;
743 }
744
745 /**
746 * Check if the clear menu item should be enabled.
747 *
748 * @return true if the clear menu item should be enabled
749 */
750 public boolean isEditMenuClear() {
751 return true;
752 }
753
754 }