-
Notifications
You must be signed in to change notification settings - Fork 418
/
Copy pathInPlaceEditView.java
2215 lines (1910 loc) · 96.5 KB
/
InPlaceEditView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package com.codename1.impl.android;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.text.Selection;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.KeyListener;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.codename1.ui.Accessor;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.Font;
import com.codename1.ui.Form;
import com.codename1.ui.TextArea;
import com.codename1.ui.TextField;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.events.DataChangedListener;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.plaf.Style;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
//import java.util.Timer;
//import java.util.TimerTask;
//import java.util.logging.Level;
//import java.util.logging.Logger;
/**
*
* @author lior.gonnen
*
*/
public class InPlaceEditView extends FrameLayout{
private static final String TAG = "InPlaceEditView";
public static final int REASON_UNDEFINED = 0;
public static final int REASON_IME_ACTION = 1;
public static final int REASON_TOUCH_OUTSIDE = 2;
public static final int REASON_SYSTEM_KEY = 3;
static void scrollActiveTextfieldToVisible() {
if (isEditing() && sInstance != null) {
Runnable r = new Runnable() {
@Override
public void run() {
if (sInstance != null && sInstance.mEditText != null && sInstance.mEditText.mTextArea != null) {
TextArea ta = sInstance.mEditText.mTextArea;
if (isScrollableParent(ta)) {
ta.scrollRectToVisible(0, 0, ta.getWidth(), ta.getHeight(), ta);
ta.getComponentForm().getAnimationManager().flushAnimation(new Runnable() {
@Override
public void run() {
reLayoutEdit();
}
});
}
}
}
};
}
}
// The native Android edit-box to place over Codename One's edit-component
private EditView mEditText = null;
private EditView mLastEditText = null;
// The Codename One edit-component we're editing
// The EditText's layout parameters
private FrameLayout.LayoutParams mEditLayoutParams;
// Reference to the system's input method manager
private InputMethodManager mInputManager;
// True while editing is in progress
private static boolean mIsEditing = false;
private static Object editingLock = new Object();
private static boolean waitingForSynchronousEditingCompletion = false;
// Maps Codename One's input-types to Android input-types
private SparseIntArray mInputTypeMap = new SparseIntArray(10);
// Receives results from the InputMethodManager after calling show/hide soft-keyboard methods
private ResultReceiver mResultReceiver;
private int mLastEndEditReason = REASON_UNDEFINED;
private Resources mResources;
// Only a single instance of this class can exist
private static InPlaceEditView sInstance = null;
private static TextArea nextTextArea = null;
private AndroidImplementation impl;
private static long closedTime;
private static boolean showVKB = false;
private static boolean isClosing = false;
// Flag to indicate that the text editor is currently hidden - but an async edit
// is still in progress. This flag is only relevant in async edit mode.
private boolean textEditorHidden = false;
private static boolean resizeMode;
// Used to buffer input while the native editor is being initialized
// This is necessary because initialization may require us to
// asynchronously run code on the EDT to obtain the current text area
// text, and then again asynchronously on the UI thread to set the
// text, and, in the mean time, the user may have typed some text.
private List<TextChange> inputBuffer;
private static Runnable afterClose;
/**
* Private constructor
* To use this class, call the static 'edit' method.
* @param impl The current running activity
*/
private InPlaceEditView(final AndroidImplementation impl) {
super(impl.getActivity());
this.impl = impl;
mResources = impl.getActivity().getResources();
mResultReceiver = new DebugResultReceiver(getHandler());
mInputManager = (InputMethodManager) impl.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// We place this view as an overlay that takes up the entire screen
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setFocusableInTouchMode(true);
initInputTypeMap();
setBackgroundDrawable(null);
}
/**
* Prepare an int-to-int map that maps Codename One input-types to
* Android input types
*/
private void initInputTypeMap() {
mInputTypeMap.append(TextArea.ANY, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
mInputTypeMap.append(TextArea.DECIMAL, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
mInputTypeMap.append(TextArea.EMAILADDR, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
mInputTypeMap.append(TextArea.INITIAL_CAPS_SENTENCE, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
mInputTypeMap.append(TextArea.INITIAL_CAPS_WORD, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
mInputTypeMap.append(TextArea.UPPERCASE, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
mInputTypeMap.append(TextArea.NON_PREDICTIVE, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
mInputTypeMap.append(TextArea.NUMERIC, InputType.TYPE_CLASS_NUMBER);
mInputTypeMap.append(TextArea.PASSWORD, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
mInputTypeMap.append(TextArea.PHONENUMBER, InputType.TYPE_CLASS_PHONE);
mInputTypeMap.append(TextArea.URL, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
}
private boolean hasConstraint(int inputType, int constraint) {
return ((inputType & constraint) == constraint);
}
private boolean isNonPredictive(int inputType) {
return hasConstraint(inputType, TextArea.NON_PREDICTIVE) || hasConstraint(inputType, TextArea.SENSITIVE);
}
private int makeNonPredictive(int codenameOneInputType, int inputType) {
if (isNonPredictive(codenameOneInputType)) {
inputType = inputType | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
if (!hasConstraint(codenameOneInputType, TextArea.PASSWORD)) {
inputType = inputType | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
}
}
return inputType;
}
/**
* Get the Android equivalent input type for a given Codename One input-type
* @param codenameOneInputType One of the com.codename1.ui.TextArea input type constants
* @return The Android equivalent of the given input type
*/
private int getAndroidInputType(int codenameOneInputType) {
return getAndroidInputType(codenameOneInputType, false);
}
private int getAndroidInputType(int codenameOneInputType, boolean multiline) {
int type = mInputTypeMap.get(codenameOneInputType, -1);
if (type == -1) {
if (!multiline && hasConstraint(codenameOneInputType, TextArea.NUMERIC)) {
type = InputType.TYPE_CLASS_NUMBER;
} else if (!multiline && hasConstraint(codenameOneInputType, TextArea.DECIMAL)) {
type = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
} else if (!multiline && hasConstraint(codenameOneInputType, TextArea.EMAILADDR)) {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
} else if (hasConstraint(codenameOneInputType, TextArea.INITIAL_CAPS_SENTENCE)) {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
} else if (hasConstraint(codenameOneInputType, TextArea.INITIAL_CAPS_WORD)) {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
} else if (!multiline && hasConstraint(codenameOneInputType, TextArea.PASSWORD)) {
type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
} else if (!multiline && hasConstraint(codenameOneInputType, TextArea.PHONENUMBER)) {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_PHONE);
} else if (!multiline && hasConstraint(codenameOneInputType, TextArea.URL)) {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
} else {
type = makeNonPredictive(codenameOneInputType, InputType.TYPE_CLASS_TEXT);
}
}
// If we're editing standard text, disable auto complete.
// The name of the flag is a little misleading. From the docs:
// the text editor is performing auto-completion of the text being entered
// based on its own semantics, which it will present to the user as they type.
// This generally means that the input method should not be showing candidates itself,
// but can expect for the editor to supply its own completions/candidates from
// InputMethodSession.displayCompletions().
if ((type & InputType.TYPE_CLASS_TEXT) != 0 && (type & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) == 0) {
type |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
}
if (multiline) {
type |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
return type;
}
/**
* Shows the native text editor for the async editing session that is currently in progress.
* This is only used when in async edit mode.
*/
static void showActiveTextEditorAgain() {
if (sInstance != null) {
sInstance.showTextEditorAgain();
}
}
/**
* Allows the implementation to refresh the text field
*/
protected final void repaintTextEditor(final boolean focus) {
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (mEditText != null && mEditText.mTextArea != null) {
mEditText.mTextArea.repaint();
if (focus) {
mEditText.mTextArea.requestFocus();
}
}
}
});
}
/**
* Shows the native text field again after it has been hidden in async edit mode.
*/
private void showTextEditorAgain() {
if (!mIsEditing || !isTextEditorHidden()) {
return;
}
textEditorHidden = false;
final TextArea ta = mEditText.mTextArea;
// Set the input buffer to catch keyboard input occurring between now
// and when we have updated the native editor's text to match the
// current state of the textarea.
// This is necessary in case the textarea's text has been programmatically
// changed since the native aread was hidden.
synchronized (this) {
inputBuffer = new ArrayList<TextChange>();
}
// We are probably not on the EDT. We need to be on the EDT to
// safely get text from the textarea for synchronization.
Display.getInstance().callSerially(new Runnable() {
public void run() {
// Double check that the state is still correct.. i.e. we are editing
// and the editing text area hasn't changed since we issued this call.
if (mIsEditing && mEditText != null && mEditText.mTextArea == ta) {
final String text = ta.getText();
final int cursorPos = ta.getCursorPosition();
// Now that we have our text from the CN1 text area, we need to be on the
// Android UI thread in order to set the text of the native text editor.
impl.getActivity().runOnUiThread(new Runnable() {
public void run() {
// Double check that the state is still correct. I.e. we are editing
// and the editing text area hasn't changed since we issued this call.
if (mIsEditing && mEditText != null && mEditText.mTextArea == ta) {
// We will synchronize here mainly for the benefit of the inputBuffer
// so that we don't find it in an inconsistent state.
synchronized (InPlaceEditView.this) {
// Let's record the cursor positions of the native
// text editor in case we need to use them after synchronizing
// with the CN1 textarea.
int start = cursorPos;
int end = cursorPos;
/*
if (!inputBuffer.isEmpty()) {
// If the input buffer isn't empty, then our start
// and end positions will be "wonky"
start = end = inputBuffer.get(0).atPos;
// If the first change was a delete, then the atPos
// will point to the beginning of the deleted section
// so we need to adjust the end point to be *after*
// the deleted section to begin.
if (inputBuffer.get(0).deleteLength > 0) {
end = start = end + inputBuffer.get(0).deleteLength;
}
}
*/
StringBuilder buf = new StringBuilder();
buf.append(text);
// Loop through any pending changes in the input buffer
// (I.e. key strokes that have occurred since we initiated
// this async callback hell!!)
List<TextChange> tinput = inputBuffer;
if(tinput != null) {
for (TextChange change : tinput) {
// This change is "added" text. Try to add it
// at the correct cursor position. if not, add it at the
// end.
if (change.textToAppend != null) {
if (end >= 0 && end <= buf.length()) {
buf.insert(end, change.textToAppend);
end += change.textToAppend.length();
start = end;
} else {
buf.append(change.textToAppend);
end = buf.length();
start = end;
}
}
// The change is "deleted" text.
else if (change.deleteLength > 0) {
if (end >= change.deleteLength && end <= buf.length()) {
buf.delete(end - change.deleteLength, end);
end -= change.deleteLength;
start = end;
} else if (end > 0 && end < change.deleteLength) {
buf.delete(0, end);
end = 0;
start = end;
}
}
}
}
// Important: Clear the input buffer so that the TextWatcher
// knows to stop filling it up. We only need the inputBuffer
// to keep input between the original showTextEditorAgain() call
// and here.
inputBuffer = null;
mEditText.setText(buf.toString());
if (start < 0 || start > mEditText.getText().length()) {
start = mEditText.getText().length();
}
if (end < 0 || end > mEditText.getText().length()) {
end = mEditText.getText().length();
}
// Update the caret in the edit text field so we can continue.
mEditText.setSelection(start, end);
}
}
}
});
}
}
});
reLayoutEdit(true);
repaintTextEditor(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
endEdit(true);
}
/**
* Hides the native text editor while keeping the active async edit session going.
* This will effectively hide the native text editor, and show the light-weight text area
* with cursor still in the correct position.
*
* <p>This is just a static wrapper around {@link #hideTextEditor()}</p>
*/
static void hideActiveTextEditor() {
if (sInstance != null) {
sInstance.hideTextEditor();
}
}
/**
* Hides the native text editor while keeping the active async edit session going.
* This will effectively hide the native text editor, and show the light-weight text area
* with cursor still in the correct position.
*/
private void hideTextEditor() {
if (!mIsEditing || textEditorHidden || mEditText == null) {
return;
}
textEditorHidden = true;
final TextArea ta = mEditText.mTextArea;
// Since this may be called off the UI thread, we need to issue async request on UI thread
// to hide the text area.
impl.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (mEditText != null && mEditText.mTextArea == ta) {
// Note: Setting visibility to GONE doesn't work here because the TextWatcher
// will stop receiving input from the keyboard, so we don't have a way to
// reactivate the text editor when the user starts typing again. Using the margin
// to move it off screen keeps the text editor active.
mEditLayoutParams.setMargins(-Display.getInstance().getDisplayWidth(), 0, 0, 0);
InPlaceEditView.this.requestLayout();
final int cursorPos = mEditText.getSelectionStart();
// Since we are going to be displaying the CN1 text area now, we need to update
// the cursor. That needs to happen on the EDT.
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (mEditText != null && mEditText.mTextArea == ta && mIsEditing && textEditorHidden) {
if (ta instanceof TextField) {
((TextField)ta).setCursorPosition(cursorPos);
}
}
}
});
}
}
});
// Repaint the CN1 text area on the EDT. This is necessary because while the native editor
// was shown, the cn1 text area paints only its background. Now that the editor is hidden
// it should paint its foreground also.
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (mEditText != null && mEditText.mTextArea != null) {
mEditText.mTextArea.repaint();
}
}
});
//repaintTextEditor(true);
}
/**
* Checks if the native text editor is currently hidden. Only relevant in async edit mode.
*
* <p>This is just a static wrapper around {@link #isTextEditorHidden()}</p>
* @return
*/
static boolean isActiveTextEditorHidden() {
if (sInstance != null) {
return sInstance.isTextEditorHidden();
}
return true;
}
/**
* Checks if the native text editor is currently hidden. Only relevant in async edit mode.
* @return
*/
private boolean isTextEditorHidden() {
return textEditorHidden;
}
/*
static void handleActiveTouchEventIfHidden(MotionEvent event) {
if (sInstance != null && mIsEditing && isActiveTextEditorHidden()) {
sInstance.onTouchEvent(event);
}
}
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!impl.isAsyncEditMode()) {
boolean leaveVKBOpen = false;
if (mEditText != null && mEditText.mTextArea != null && mEditText.mTextArea.getComponentForm() != null) {
Component c = mEditText.mTextArea.getComponentForm().getResponderAt((int) event.getX(), (int) event.getY());
if ( mEditText.mTextArea.getClientProperty("leaveVKBOpen") != null
|| (c != null && c instanceof TextArea && ((TextArea) c).isEditable() && ((TextArea) c).isEnabled())) {
leaveVKBOpen = true;
}
}
// When the user touches the screen outside the text-area, finish editing
endEditing(REASON_TOUCH_OUTSIDE, leaveVKBOpen, 0);
} else {
final int evtX = (int) event.getX();
final int evtY = (int) event.getY();
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (mEditText != null && mEditText.mTextArea != null) {
TextArea tx = mEditText.mTextArea;
int x = tx.getAbsoluteX() + tx.getScrollX();
int y = tx.getAbsoluteY() + tx.getScrollY();
int w = tx.getWidth();
int h = tx.getHeight();
if (!(x <= evtX && y <= evtY && x + w >= evtX && y + h >= evtY)) {
hideTextEditor();
} else {
showTextEditorAgain();
}
}
}
});
}
// Return false so that the event will propagate to the underlying view
// We don't want to consume this event
return false;
}
/**
* Show or hide the virtual keyboard if necessary
* @param show Show the keyboard if true, hide it otherwise
*/
private void showVirtualKeyboard(boolean show) {
show = Boolean.parseBoolean(Display.getInstance().getProperty("showVkb", "" + show));
Log.i(TAG, "showVirtualKeyboard show=" + show);
boolean result = false;
if (show) {
// If we're in landscape, Android will not show the soft
// keyboard unless SHOW_FORCED is requested
Configuration config = mResources.getConfiguration();
boolean isLandscape = (config.orientation == Configuration.ORIENTATION_LANDSCAPE);
int showFlags = isLandscape ? InputMethodManager.SHOW_FORCED : InputMethodManager.SHOW_IMPLICIT;
mInputManager.restartInput(mEditText);
result = mInputManager.showSoftInput(mEditText, showFlags, mResultReceiver);
} else {
if(mEditText == null){
if(showVKB){
mInputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}else{
result = mInputManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0, mResultReceiver);
}
closedTime = System.currentTimeMillis();
}
showVKB = show;
final boolean showKeyboard = showVKB;
//final ActionListener listener = Display.getInstance().getVirtualKeyboardListener();
//if(listener != null){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//this is ugly but there is no real API to know if the
//keyboard is opened or closed
try {
Thread.sleep(600);
} catch (InterruptedException ex) {
}
Display.getInstance().fireVirtualKeyboardEvent(showKeyboard);
}
});
t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
t.start();
//}
Log.d(TAG, "InputMethodManager returned " + Boolean.toString(result).toUpperCase());
}
/**
* Returns true if the keyboard is currently on screen.
*/
public static boolean isKeyboardShowing(){
//There is no android API to know if the keyboard is currently showing
//This method will return false after 2 seconds since the keyboard was
//requested to be closed
return showVKB || (System.currentTimeMillis() - closedTime) < 2000;
}
static class TextAreaData {
final int absoluteY;
final int absoluteX;
final int paddingTop;
final int paddingLeft;
final int paddingRight;
final int paddingBottom;
final int scrollX;
final int scrollY;
final int verticalAlignment;
final int height;
final int width;
final int fontHeight;
final TextArea textArea;
final Component nextDown;
final boolean isRTL;
final boolean isSingleLineTextArea;
final String hint;
final boolean nativeHintBool;
final Object nativeFont;
final int fgColor;
final int maxSize;
final boolean isTextField;
int getAbsoluteY() {
return absoluteY;
}
int getAbsoluteX() {
return absoluteX;
}
int getScrollX() {
return scrollX;
}
int getScrollY() {
return scrollY;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
int getVerticalAlignment() {
return verticalAlignment;
}
boolean isRTL() {
return isRTL;
}
boolean isSingleLineTextArea() {
return isSingleLineTextArea;
}
Object getClientProperty(String key) {
return textArea.getClientProperty(key);
}
void putClientProperty(String key, Object value) {
textArea.putClientProperty(key, value);
}
Object getDoneListener() {
return ((TextArea)textArea).getDoneListener();
}
String getHint() {
return hint;
}
TextAreaData(TextArea ta) {
absoluteX = ta.getAbsoluteX();
absoluteY = ta.getAbsoluteY();
scrollX = ta.getScrollX();
scrollY = ta.getScrollY();
Style s = ta.getStyle();
paddingTop = s.getPaddingTop();
paddingLeft = s.getPaddingLeft(ta.isRTL());
paddingRight = s.getPaddingRight(ta.isRTL());
paddingBottom = s.getPaddingBottom();
isTextField = (ta instanceof TextField);
verticalAlignment = ta.getVerticalAlignment();
height = ta.getHeight();
width = ta.getWidth();
fontHeight = s.getFont().getHeight();
textArea = ta;
isRTL = ta.isRTL();
nextDown = textArea.getComponentForm().getNextComponent(textArea);
isSingleLineTextArea = textArea.isSingleLineTextArea();
hint = ta.getHint();
nativeHintBool = textArea.getUIManager().isThemeConstant("nativeHintBool", false);
nativeFont = s.getFont().getNativeFont();
fgColor = s.getFgColor();
maxSize = ta.getMaxSize();
}
}
// Timers for manually blinking cursor on Android 4.4
//private Timer cursorTimer;
//private TimerTask cursorTimerTask;
private KeyListener defaultKeyListener;
private int defaultMaxLines=-2;
private int defaultInputType;
private int defaultIMEOptions;
/**
* Start editing the given text-area
* This method is executed on the UI thread, so UI manipulation is safe here.
* @param activity Current running activity
* @param textArea The TextAreaData instance that wraps the CN1 TextArea that our internal EditText needs to overlap. We use
* a TextAreaData so that the text area properties can be accessed off the EDT safely.
* @param codenameOneInputType One of the input type constants in com.codename1.ui.TextArea
* @param initialText The text that appears in the Codename One text are before the call to startEditing
* @param isEditedFieldSwitch if true, then special case for async edit mode - the native editing is already active, no need to show
* native field, just change the connected field
*/
private synchronized void startEditing(Activity activity, TextAreaData textArea, String initialText, int codenameOneInputType, final boolean isEditedFieldSwitch) {
int txty = lastTextAreaY = textArea.getAbsoluteY() + textArea.getScrollY();
int txtx = lastTextAreaX = textArea.getAbsoluteX() + textArea.getScrollX();
lastTextAreaWidth = textArea.getWidth();
lastTextAreaHeight = textArea.getHeight();
int paddingTop = 0;
int paddingLeft = textArea.paddingLeft;
int paddingRight = textArea.paddingRight;
int paddingBottom = textArea.paddingBottom;
// An ugly hack to smooth over an apparent race condition where
// the lightweight textarea is not repainted after the native text field
// becomes visible - resulting in the hint still appearing while typing.
// https://github.com/codenameone/CodenameOne/issues/2629
// We just blindly repaint the textfield every 50ms for half a second
// to make sure it gets a repaint properly.
final TextArea fTextArea = textArea.textArea;
new Thread(new Runnable() {
public void run() {
for (int i=0; i< 10; i++) {
com.codename1.io.Util.sleep(50);
com.codename1.ui.CN.callSerially(new Runnable() {
public void run() {
fTextArea.repaint();
}
});
}
}
}).start();
if (textArea.isTextField) {
switch (textArea.getVerticalAlignment()) {
case Component.BOTTOM:
paddingTop = textArea.getHeight() - textArea.paddingBottom - textArea.fontHeight;
break;
case Component.CENTER:
paddingTop = textArea.getHeight() / 2 - textArea.fontHeight / 2;
break;
default:
paddingTop = textArea.paddingTop;
break;
}
} else {
paddingTop = textArea.paddingTop;
}
int id = activity.getResources().getIdentifier("cn1Style", "attr", activity.getApplicationInfo().packageName);
if (!isEditedFieldSwitch) {
mEditText = new EditView(activity, textArea.textArea, this, id);
defaultInputType = mEditText.getInputType();
defaultIMEOptions = mEditText.getImeOptions();
} else {
mEditText.switchToTextArea(textArea.textArea);
}
if(textArea.getClientProperty("blockCopyPaste") != null || Display.getInstance().getProperty("blockCopyPaste", "false").equals("true")) {
// The code below is taken from this stackoverflow answer: http://stackoverflow.com/a/22756538/756809
if (android.os.Build.VERSION.SDK_INT < 11) {
mEditText.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.clear();
}
});
} else {
mEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
return false;
}
});
}
} else if (isEditedFieldSwitch) {
//reset copy-paste protection
if (android.os.Build.VERSION.SDK_INT < 11) {
mEditText.setOnCreateContextMenuListener(null);
} else {
mEditText.setCustomSelectionActionModeCallback(null);
}
}
if (!isEditedFieldSwitch) {
mEditText.addTextChangedListener(mEditText.mTextWatcher);
}
mEditText.setBackgroundDrawable(null);
mEditText.setFocusableInTouchMode(true);
mEditLayoutParams = new FrameLayout.LayoutParams(0, 0);
// Set the appropriate gravity so that the left and top margins will be
// taken into account
mEditLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
mEditLayoutParams.setMargins(txtx, txty, 0, 0);
mEditLayoutParams.width = textArea.getWidth();
mEditLayoutParams.height = textArea.getHeight();
mEditText.setLayoutParams(mEditLayoutParams);
if(textArea.isRTL()){
mEditText.setGravity(Gravity.RIGHT | Gravity.TOP);
}else{
mEditText.setGravity(Gravity.LEFT | Gravity.TOP);
}
mEditText.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
Component nextDown = textArea.nextDown;
boolean imeOptionTaken = true;
int ime = EditorInfo.IME_FLAG_NO_EXTRACT_UI;
if (textArea.isSingleLineTextArea() || textArea.getDoneListener() != null) {
if(textArea.getClientProperty("searchField") != null) {
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_SEARCH);
} else {
if(textArea.getClientProperty("sendButton") != null) {
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_SEND);
} else {
if(textArea.getClientProperty("goButton") != null) {
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_GO);
} else {
if(textArea.getDoneListener() != null){
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_DONE);
} else if (nextDown != null) {
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_NEXT);
} else {
mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_DONE);
imeOptionTaken = false;
}
}
}
}
}
mEditText.setSingleLine(textArea.isSingleLineTextArea());
mEditText.setAdapter((ArrayAdapter<String>) null);
mEditText.setText(initialText);
if(!textArea.isSingleLineTextArea() && textArea.textArea.isGrowByContent() && textArea.textArea.getGrowLimit() > -1){
defaultMaxLines = mEditText.getMaxLines();
mEditText.setMaxLines(textArea.textArea.getGrowLimit());
}
if(textArea.nativeHintBool && textArea.getHint() != null) {
mEditText.setHint(textArea.getHint());
}
if (!isEditedFieldSwitch) {
addView(mEditText, mEditLayoutParams);
}
invalidate();
setVisibility(VISIBLE);
bringToFront();
mEditText.requestFocus();
Object nativeFont = textArea.nativeFont;
if (nativeFont == null) {
nativeFont = impl.getDefaultFont();
}
Paint p = (Paint) ((AndroidImplementation.NativeFont) nativeFont).font;
mEditText.setTypeface(p.getTypeface());
mEditText.setTextScaleX(p.getTextScaleX());
mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, p.getTextSize());
int fgColor = textArea.fgColor;
mEditText.setTextColor(Color.rgb(fgColor >> 16, (fgColor & 0x00ff00) >> 8, (fgColor & 0x0000ff)));
boolean password = false;
if((codenameOneInputType & TextArea.PASSWORD) == TextArea.PASSWORD){
codenameOneInputType = codenameOneInputType ^ TextArea.PASSWORD;
password = true;
}
if (textArea.isSingleLineTextArea()) {
mEditText.setInputType(getAndroidInputType(codenameOneInputType));
//if not ime was explicity requested and this is a single line textfield of type ANY add the emoji keyboard.
if(!imeOptionTaken && codenameOneInputType == TextArea.ANY){
mEditText.setInputType(getAndroidInputType(codenameOneInputType) | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
}
if(Display.getInstance().getProperty("andAddComma", "false").equals("true") &&
(codenameOneInputType & TextArea.DECIMAL) == TextArea.DECIMAL) {
defaultKeyListener = mEditText.getKeyListener();
mEditText.setKeyListener(DigitsKeyListener.getInstance("0123456789.,"));
}
} else {
if (textArea.getDoneListener() != null) {
mEditText.setHorizontallyScrolling(false);
mEditText.setMaxLines(Integer.MAX_VALUE);
mEditText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
mEditText.setMaxWidth(textArea.getWidth());
mEditText.setMaxHeight(textArea.getHeight());
mEditText.setHorizontalScrollBarEnabled(false);
mEditText.getLayoutParams().width = textArea.getWidth();
mEditText.getLayoutParams().height = textArea.getHeight();
} else {
mEditText.setInputType(getAndroidInputType(codenameOneInputType, true));
}
}
if (password) {
int type = mInputTypeMap.get(codenameOneInputType, InputType.TYPE_CLASS_TEXT);
if((type & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) == InputType.TYPE_TEXT_FLAG_CAP_SENTENCES){
type = type ^ InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;