#35 fix crash
[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.TKeypressEvent;
35 import jexer.event.TMouseEvent;
36 import static jexer.TKeypress.*;
37
38 /**
39 * TField implements an editable text field.
40 */
41 public class TField extends TWidget {
42
43 // ------------------------------------------------------------------------
44 // Variables --------------------------------------------------------------
45 // ------------------------------------------------------------------------
46
47 /**
48 * Background character for unfilled-in text.
49 */
50 protected int backgroundChar = GraphicsChars.HATCH;
51
52 /**
53 * Field text.
54 */
55 protected String text = "";
56
57 /**
58 * If true, only allow enough characters that will fit in the width. If
59 * false, allow the field to scroll to the right.
60 */
61 protected boolean fixed = false;
62
63 /**
64 * Current editing position within text.
65 */
66 protected int position = 0;
67
68 /**
69 * Current editing position screen column number.
70 */
71 protected int screenPosition = 0;
72
73 /**
74 * Beginning of visible portion.
75 */
76 protected int windowStart = 0;
77
78 /**
79 * If true, new characters are inserted at position.
80 */
81 protected boolean insertMode = true;
82
83 /**
84 * Remember mouse state.
85 */
86 protected TMouseEvent mouse;
87
88 /**
89 * The action to perform when the user presses enter.
90 */
91 protected TAction enterAction;
92
93 /**
94 * The action to perform when the text is updated.
95 */
96 protected TAction updateAction;
97
98 /**
99 * The color to use when this field is active.
100 */
101 private String activeColorKey = "tfield.active";
102
103 /**
104 * The color to use when this field is not active.
105 */
106 private String inactiveColorKey = "tfield.inactive";
107
108 // ------------------------------------------------------------------------
109 // Constructors -----------------------------------------------------------
110 // ------------------------------------------------------------------------
111
112 /**
113 * Public constructor.
114 *
115 * @param parent parent widget
116 * @param x column relative to parent
117 * @param y row relative to parent
118 * @param width visible text width
119 * @param fixed if true, the text cannot exceed the display width
120 */
121 public TField(final TWidget parent, final int x, final int y,
122 final int width, final boolean fixed) {
123
124 this(parent, x, y, width, fixed, "", null, null);
125 }
126
127 /**
128 * Public constructor.
129 *
130 * @param parent parent widget
131 * @param x column relative to parent
132 * @param y row relative to parent
133 * @param width visible text width
134 * @param fixed if true, the text cannot exceed the display width
135 * @param text initial text, default is empty string
136 */
137 public TField(final TWidget parent, final int x, final int y,
138 final int width, final boolean fixed, final String text) {
139
140 this(parent, x, y, width, fixed, text, null, null);
141 }
142
143 /**
144 * Public constructor.
145 *
146 * @param parent parent widget
147 * @param x column relative to parent
148 * @param y row relative to parent
149 * @param width visible text width
150 * @param fixed if true, the text cannot exceed the display width
151 * @param text initial text, default is empty string
152 * @param enterAction function to call when enter key is pressed
153 * @param updateAction function to call when the text is updated
154 */
155 public TField(final TWidget parent, final int x, final int y,
156 final int width, final boolean fixed, final String text,
157 final TAction enterAction, final TAction updateAction) {
158
159 // Set parent and window
160 super(parent, x, y, width, 1);
161
162 setCursorVisible(true);
163 this.fixed = fixed;
164 this.text = text;
165 this.enterAction = enterAction;
166 this.updateAction = updateAction;
167 }
168
169 // ------------------------------------------------------------------------
170 // Event handlers ---------------------------------------------------------
171 // ------------------------------------------------------------------------
172
173 /**
174 * Returns true if the mouse is currently on the field.
175 *
176 * @return if true the mouse is currently on the field
177 */
178 protected boolean mouseOnField() {
179 int rightEdge = getWidth() - 1;
180 if ((mouse != null)
181 && (mouse.getY() == 0)
182 && (mouse.getX() >= 0)
183 && (mouse.getX() <= rightEdge)
184 ) {
185 return true;
186 }
187 return false;
188 }
189
190 /**
191 * Handle mouse button presses.
192 *
193 * @param mouse mouse button event
194 */
195 @Override
196 public void onMouseDown(final TMouseEvent mouse) {
197 this.mouse = mouse;
198
199 if ((mouseOnField()) && (mouse.isMouse1())) {
200 // Move cursor
201 int deltaX = mouse.getX() - getCursorX();
202 screenPosition += deltaX;
203 if (screenPosition > StringUtils.width(text)) {
204 screenPosition = StringUtils.width(text);
205 }
206 position = screenToTextPosition(screenPosition);
207 updateCursor();
208 return;
209 }
210 }
211
212 /**
213 * Handle keystrokes.
214 *
215 * @param keypress keystroke event
216 */
217 @Override
218 public void onKeypress(final TKeypressEvent keypress) {
219
220 if (keypress.equals(kbLeft)) {
221 if (position > 0) {
222 if (position < text.length()) {
223 screenPosition -= StringUtils.width(text.codePointAt(position));
224 } else {
225 screenPosition--;
226 }
227 position--;
228 }
229 if (fixed == false) {
230 if ((screenPosition == windowStart) && (windowStart > 0)) {
231 windowStart -= StringUtils.width(text.codePointAt(
232 screenToTextPosition(windowStart)));
233 }
234 }
235 normalizeWindowStart();
236 return;
237 }
238
239 if (keypress.equals(kbRight)) {
240 if (position < text.length()) {
241 screenPosition += StringUtils.width(text.codePointAt(position));
242 position++;
243 if (fixed == true) {
244 if (screenPosition == getWidth()) {
245 screenPosition--;
246 position--;
247 }
248 } else {
249 if ((screenPosition - windowStart) >= getWidth()) {
250 windowStart += StringUtils.width(text.codePointAt(
251 screenToTextPosition(windowStart)));
252 }
253 }
254 }
255 return;
256 }
257
258 if (keypress.equals(kbEnter)) {
259 dispatch(true);
260 return;
261 }
262
263 if (keypress.equals(kbIns)) {
264 insertMode = !insertMode;
265 return;
266 }
267 if (keypress.equals(kbHome)) {
268 home();
269 return;
270 }
271
272 if (keypress.equals(kbEnd)) {
273 end();
274 return;
275 }
276
277 if (keypress.equals(kbDel)) {
278 if ((text.length() > 0) && (position < text.length())) {
279 text = text.substring(0, position)
280 + text.substring(position + 1);
281 screenPosition = StringUtils.width(text.substring(0, position));
282 }
283 dispatch(false);
284 return;
285 }
286
287 if (keypress.equals(kbBackspace) || keypress.equals(kbBackspaceDel)) {
288 if (position > 0) {
289 position--;
290 text = text.substring(0, position)
291 + text.substring(position + 1);
292 screenPosition = StringUtils.width(text.substring(0, position));
293 }
294 if (fixed == false) {
295 if ((screenPosition >= windowStart)
296 && (windowStart > 0)
297 ) {
298 windowStart -= StringUtils.width(text.codePointAt(
299 screenToTextPosition(windowStart)));
300 }
301 }
302 dispatch(false);
303 normalizeWindowStart();
304 return;
305 }
306
307 if (!keypress.getKey().isFnKey()
308 && !keypress.getKey().isAlt()
309 && !keypress.getKey().isCtrl()
310 ) {
311 // Plain old keystroke, process it
312 if ((position == text.length())
313 && (StringUtils.width(text) < getWidth())) {
314
315 // Append case
316 appendChar(keypress.getKey().getChar());
317 } else if ((position < text.length())
318 && (StringUtils.width(text) < getWidth())) {
319
320 // Overwrite or insert a character
321 if (insertMode == false) {
322 // Replace character
323 text = text.substring(0, position)
324 + codePointString(keypress.getKey().getChar())
325 + text.substring(position + 1);
326 screenPosition += StringUtils.width(text.codePointAt(position));
327 position += Character.charCount(keypress.getKey().getChar());
328 } else {
329 // Insert character
330 insertChar(keypress.getKey().getChar());
331 }
332 } else if ((position < text.length())
333 && (StringUtils.width(text) >= getWidth())) {
334
335 // Multiple cases here
336 if ((fixed == true) && (insertMode == true)) {
337 // Buffer is full, do nothing
338 } else if ((fixed == true) && (insertMode == false)) {
339 // Overwrite the last character, maybe move position
340 text = text.substring(0, position)
341 + codePointString(keypress.getKey().getChar())
342 + text.substring(position + 1);
343 if (screenPosition < getWidth() - 1) {
344 screenPosition += StringUtils.width(text.codePointAt(position));
345 position += Character.charCount(keypress.getKey().getChar());
346 }
347 } else if ((fixed == false) && (insertMode == false)) {
348 // Overwrite the last character, definitely move position
349 text = text.substring(0, position)
350 + codePointString(keypress.getKey().getChar())
351 + text.substring(position + 1);
352 screenPosition += StringUtils.width(text.codePointAt(position));
353 position += Character.charCount(keypress.getKey().getChar());
354 } else {
355 if (position == text.length()) {
356 // Append this character
357 appendChar(keypress.getKey().getChar());
358 } else {
359 // Insert this character
360 insertChar(keypress.getKey().getChar());
361 }
362 }
363 } else {
364 assert (!fixed);
365
366 // Append this character
367 appendChar(keypress.getKey().getChar());
368 }
369 dispatch(false);
370 return;
371 }
372
373 // Pass to parent for the things we don't care about.
374 super.onKeypress(keypress);
375 }
376
377 // ------------------------------------------------------------------------
378 // TWidget ----------------------------------------------------------------
379 // ------------------------------------------------------------------------
380
381 /**
382 * Draw the text field.
383 */
384 @Override
385 public void draw() {
386 CellAttributes fieldColor;
387
388 if (isAbsoluteActive()) {
389 fieldColor = getTheme().getColor(activeColorKey);
390 } else {
391 fieldColor = getTheme().getColor(inactiveColorKey);
392 }
393
394 int end = windowStart + getWidth();
395 if (end > StringUtils.width(text)) {
396 end = StringUtils.width(text);
397 }
398 hLineXY(0, 0, getWidth(), backgroundChar, fieldColor);
399 putStringXY(0, 0, text.substring(screenToTextPosition(windowStart),
400 screenToTextPosition(end)), fieldColor);
401
402 // Fix the cursor, it will be rendered by TApplication.drawAll().
403 updateCursor();
404 }
405
406 // ------------------------------------------------------------------------
407 // TField -----------------------------------------------------------------
408 // ------------------------------------------------------------------------
409
410 /**
411 * Convert a char (codepoint) to a string.
412 *
413 * @param ch the char
414 * @return the string
415 */
416 private String codePointString(final int ch) {
417 StringBuilder sb = new StringBuilder(1);
418 sb.append(Character.toChars(ch));
419 return sb.toString();
420 }
421
422 /**
423 * Get field background character.
424 *
425 * @return background character
426 */
427 public final int getBackgroundChar() {
428 return backgroundChar;
429 }
430
431 /**
432 * Set field background character.
433 *
434 * @param backgroundChar the background character
435 */
436 public void setBackgroundChar(final int backgroundChar) {
437 this.backgroundChar = backgroundChar;
438 }
439
440 /**
441 * Get field text.
442 *
443 * @return field text
444 */
445 public final String getText() {
446 return text;
447 }
448
449 /**
450 * Set field text.
451 *
452 * @param text the new field text
453 */
454 public void setText(final String text) {
455 assert (text != null);
456 this.text = text;
457 position = 0;
458 windowStart = 0;
459 }
460
461 /**
462 * Dispatch to the action function.
463 *
464 * @param enter if true, the user pressed Enter, else this was an update
465 * to the text.
466 */
467 protected void dispatch(final boolean enter) {
468 if (enter) {
469 if (enterAction != null) {
470 enterAction.DO();
471 }
472 } else {
473 if (updateAction != null) {
474 updateAction.DO();
475 }
476 }
477 }
478
479 /**
480 * Determine string position from screen position.
481 *
482 * @param screenPosition the position on screen
483 * @return the equivalent position in text
484 */
485 protected int screenToTextPosition(final int screenPosition) {
486 if (screenPosition == 0) {
487 return 0;
488 }
489
490 int n = 0;
491 for (int i = 0; i < text.length(); i++) {
492 n += StringUtils.width(text.codePointAt(i));
493 if (n >= screenPosition) {
494 return i + 1;
495 }
496 }
497 // screenPosition exceeds the available text length.
498 throw new IndexOutOfBoundsException("screenPosition " + screenPosition +
499 " exceeds available text length " + text.length());
500 }
501
502 /**
503 * Update the visible cursor position to match the location of position
504 * and windowStart.
505 */
506 protected void updateCursor() {
507 if ((screenPosition > getWidth()) && fixed) {
508 setCursorX(getWidth());
509 } else if ((screenPosition - windowStart >= getWidth()) && !fixed) {
510 setCursorX(getWidth() - 1);
511 } else {
512 setCursorX(screenPosition - windowStart);
513 }
514 }
515
516 /**
517 * Normalize windowStart such that most of the field data if visible.
518 */
519 protected void normalizeWindowStart() {
520 if (fixed) {
521 // windowStart had better be zero, there is nothing to do here.
522 assert (windowStart == 0);
523 return;
524 }
525 windowStart = screenPosition - (getWidth() - 1);
526 if (windowStart < 0) {
527 windowStart = 0;
528 }
529
530 updateCursor();
531 }
532
533 /**
534 * Append char to the end of the field.
535 *
536 * @param ch char to append
537 */
538 protected void appendChar(final int ch) {
539 // Append the LAST character
540 text += codePointString(ch);
541 position += Character.charCount(ch);
542 screenPosition += StringUtils.width(ch);
543
544 assert (position == text.length());
545
546 if (fixed) {
547 if (screenPosition >= getWidth()) {
548 position -= Character.charCount(ch);
549 screenPosition -= StringUtils.width(ch);
550 }
551 } else {
552 if ((screenPosition - windowStart) >= getWidth()) {
553 windowStart++;
554 }
555 }
556 }
557
558 /**
559 * Insert char somewhere in the middle of the field.
560 *
561 * @param ch char to append
562 */
563 protected void insertChar(final int ch) {
564 text = text.substring(0, position) + codePointString(ch)
565 + text.substring(position);
566 position += Character.charCount(ch);
567 screenPosition += StringUtils.width(ch);
568 if ((screenPosition - windowStart) == getWidth()) {
569 assert (!fixed);
570 windowStart++;
571 }
572 }
573
574 /**
575 * Position the cursor at the first column. The field may adjust the
576 * window start to show as much of the field as possible.
577 */
578 public void home() {
579 position = 0;
580 screenPosition = 0;
581 windowStart = 0;
582 }
583
584 /**
585 * Set the editing position to the last filled character. The field may
586 * adjust the window start to show as much of the field as possible.
587 */
588 public void end() {
589 position = text.length();
590 screenPosition = StringUtils.width(text);
591 if (fixed == true) {
592 if (screenPosition >= getWidth()) {
593 position = text.length() - 1;
594 screenPosition = StringUtils.width(text) - 1;
595 }
596 } else {
597 windowStart = StringUtils.width(text) - getWidth() + 1;
598 if (windowStart < 0) {
599 windowStart = 0;
600 }
601 }
602 }
603
604 /**
605 * Set the editing position. The field may adjust the window start to
606 * show as much of the field as possible.
607 *
608 * @param position the new position
609 * @throws IndexOutOfBoundsException if position is outside the range of
610 * the available text
611 */
612 public void setPosition(final int position) {
613 if ((position < 0) || (position >= text.length())) {
614 throw new IndexOutOfBoundsException("Max length is " +
615 StringUtils.width(text) + ", requested position " + position);
616 }
617 this.position = position;
618 normalizeWindowStart();
619 }
620
621 /**
622 * Set the active color key.
623 *
624 * @param activeColorKey ColorTheme key color to use when this field is
625 * active
626 */
627 public void setActiveColorKey(final String activeColorKey) {
628 this.activeColorKey = activeColorKey;
629 }
630
631 /**
632 * Set the inactive color key.
633 *
634 * @param inactiveColorKey ColorTheme key color to use when this field is
635 * inactive
636 */
637 public void setInactiveColorKey(final String inactiveColorKey) {
638 this.inactiveColorKey = inactiveColorKey;
639 }
640
641 /**
642 * Set the action to perform when the user presses enter.
643 *
644 * @param action the action to perform when the user presses enter
645 */
646 public void setEnterAction(final TAction action) {
647 enterAction = action;
648 }
649
650 /**
651 * Set the action to perform when the field is updated.
652 *
653 * @param action the action to perform when the field is updated
654 */
655 public void setUpdateAction(final TAction action) {
656 updateAction = action;
657 }
658
659 }