summaryrefslogtreecommitdiff
path: root/loleaflet/src/layer/marker/TextInput.js
blob: 046a5d8086fadee3bad173c490a06f1d7a5028f9 (plain)
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
/* -*- js-indent-level: 8 -*- */
/*
 * L.TextInput is the hidden textarea, which handles text input events
 *
 * This is made significantly more difficult than expected by such a
 * mess of browser, and mobile IME quirks that it is not possible to
 * follow events, but we have to re-construct input from a browser
 * text area itself.
 */

/* global */

L.TextInput = L.Layer.extend({
	initialize: function() {
		// Flag to denote the composing state, derived from
		// compositionstart/compositionend events; unused
		this._isComposing = false;

		// We need to detect whether delete or backspace was
		// pressed sometimes - consider '  foo' -> ' foo'
		this._deleteHint = ''; // or 'delete' or 'backspace'

		// We need to detect line break in the tunneled formula
		// input window for the multiline case.
		this._linebreakHint = false;

		// Clearing the area can generate input events
		this._ignoreInputCount = 0;

		// If the last focus intended to accept user input.
		// Signifies whether the keyboard is meant to be visible.
		this._acceptInput = false;

		// Content
		this._lastContent = []; // unicode characters
		this._hasWorkingSelectionStart = undefined; // does it work ?
		this._ignoreNextBackspace = false;

		this._preSpaceChar = ' ';
		// Might need to be \xa0 in some legacy browsers ?
		if (L.Browser.android && L.Browser.webkit) {
			// fool GBoard into not auto-capitalizing constantly
			this._preSpaceChar = '\xa0';
		}
		this._postSpaceChar = ' ';

		// Debug flag, used in fancyLog(). See the debug() method.
//		this._isDebugOn = true;
		this._isDebugOn = false;

		this._initLayout();

		// Under-caret orange marker.
		this._cursorHandler = L.marker(new L.LatLng(0, 0), {
			icon: L.divIcon({
				className: 'leaflet-cursor-handler',
				iconSize: null
			}),
			draggable: true
		}).on('dragend', this._onCursorHandlerDragEnd, this);

		var that = this;
		this._selectionHandler = function(ev) { that._onEvent(ev); };

		// Auto-correct characters can trigger auto-correction, but
		// must be sent as key-up/down if we want correction.
		// cf. SvxAutoCorrect::IsAutoCorrectChar
		this._autoCorrectChars = {
			// tab, newline - handled elsewhere
			' ':  [ 32, 0,      0, 1284 ],
			'!':  [ 33, 0,      0, 4353 ],
			'"':  [ 34, 0,      0, 4353 ],
			'%':  [ 37, 0,      0, 4357 ],
			'\'': [ 39, 0,      0,  192 ],
			'*':  [ 42, 0,      0, 4360 ],
			',':  [ 44, 0,      0, 1291 ],
			'-':  [ 45, 0,      0, 1288 ],
			'.':  [ 46, 0,      0,  190 ],
			'/':  [ 47, 0,      0,  191 ],
			':':  [ 58, 0,      0, 5413 ],
			';':  [ 59, 0,      0, 1317 ],
			'?':  [ 63, 0,      0, 4287 ],
			'_':  [ 95, 0,      0, 5384 ]
		};
	},

	onAdd: function() {
		if (this._container) {
			this.getPane().appendChild(this._container);
			this.update();
		}

		this._emptyArea();

		this._map.on('updatepermission', this._onPermission, this);
		L.DomEvent.on(this._textArea, 'focus blur', this._onFocusBlur, this);

		// Do not wait for a 'focus' event to attach events if the
		// textarea/contenteditable is already focused (due to the autofocus
		// HTML attribute, the browser focusing it on DOM creation, or whatever)
		if (document.activeElement === this._textArea) {
			this._onFocusBlur({ type: 'focus' });
		}

		L.DomEvent.on(this._map.getContainer(), 'mousedown touchstart', this._abortComposition, this);
	},

	onRemove: function() {
		if (this._container) {
			this.getPane().removeChild(this._container);
		}

		this._map.off('updatepermission', this._onPermission, this);
		L.DomEvent.off(this._textArea, 'focus blur', this._onFocusBlur, this);
		L.DomEvent.off(this._map.getContainer(), 'mousedown touchstart', this._abortComposition, this);

		this._map.removeLayer(this._cursorHandler);
	},

	_onPermission: function(e) {
		if (e.perm === 'edit') {
			this._textArea.removeAttribute('disabled');
		} else {
			this._textArea.setAttribute('disabled', true);
		}
	},

	_onFocusBlur: function(ev) {
		this._fancyLog(ev.type, '');

		var onoff = (ev.type == 'focus' ? L.DomEvent.on : L.DomEvent.off).bind(L.DomEvent);

		// Debug - connect first for saner logging.
		onoff(
			this._textArea,
			'copy cut compositionstart compositionupdate compositionend select keydown keypress keyup beforeinput textInput textinput input',
			this._onEvent,
			this
		);

		onoff(this._textArea, 'input', this._onInput, this);
		onoff(this._textArea, 'beforeinput', this._onBeforeInput, this);
		onoff(this._textArea, 'compositionstart', this._onCompositionStart, this);
		onoff(this._textArea, 'compositionupdate', this._onCompositionUpdate, this);
		onoff(this._textArea, 'compositionend', this._onCompositionEnd, this);
		onoff(this._textArea, 'keydown', this._onKeyDown, this);
		onoff(this._textArea, 'keyup', this._onKeyUp, this);
		onoff(this._textArea, 'copy cut paste', this._map._handleDOMEvent, this._map);

		this._map.notifyActive();

		if (ev.type === 'blur' && this._isComposing) {
			this._abortComposition(ev);
		}
	},

	// Focus the textarea/contenteditable
	// @acceptInput (only on "mobile" (= mobile phone) or on iOS and Android in general) true if we want to
	// accept key input, and show the virtual keyboard.
	focus: function(acceptInput) {
		// Clicking or otherwise focusing the map should focus on the clipboard
		// container in order for the user to input text (and on-screen keyboards
		// to pop-up), unless the document is read only.
		if (this._map._permission !== 'edit') {
			this._acceptInput = false;
			return;
		}

		// Trick to avoid showing the software keyboard: Set the textarea
		// read-only before focus() and reset it again after the blur()
		if ((window.ThisIsAMobileApp || window.mode.isMobile()) && acceptInput !== true)
			this._textArea.setAttribute('readonly', true);

		this._textArea.focus();

		if ((window.ThisIsAMobileApp || window.mode.isMobile()) && acceptInput !== true) {
			this._acceptInput = false;
			this._textArea.blur();
			this._textArea.removeAttribute('readonly');
		} else {
			this._acceptInput = true;
		}
	},

	blur: function() {
		this._acceptInput = false;
		this._textArea.blur();
	},

	// Returns true if the last focus was to accept input.
	// Used to restore the keyboard.
	canAcceptKeyboardInput: function() {
		return this._acceptInput;
	},

	// Marks the content of the textarea/contenteditable as selected,
	// for system clipboard interaction.
	select: function select() {
		this._textArea.select();
	},

	getValue: function() {
		var value = this._textArea.value;
		return value;
	},

	getValueAsCodePoints: function() {
		var value = this.getValue();
		var arr = [];
		var code;
		for (var i = 0; i < value.length; ++i)
		{
			code = value.charCodeAt(i);

			// if it were not for IE11: "for (code of value)" does the job.
			if (code >= 0xd800 && code <= 0xdbff) // handle UTF16 pairs.
			{
				// TESTME: harder ...
				var high = (code - 0xd800) << 10;
				code = value.charCodeAt(++i);
				code = high + code - 0xdc00 + 0x100000;
			}
			arr.push(code);
		}
		return arr;
	},

	update: function() {
		if (this._container && this._map && this._latlng) {
			var position = this._map.latLngToLayerPoint(this._latlng).round();
			this._setPos(position);
		}
	},

	_initLayout: function() {
		this._container = L.DomUtil.create('div', 'clipboard-container');
		this._container.id = 'doc-clipboard-container';

		// The textarea allows the keyboard to pop up and so on.
		// Note that the contents of the textarea are NOT deleted on each composed
		// word, in order to make
		this._textArea = L.DomUtil.create('textarea', 'clipboard', this._container);
		this._textArea.setAttribute('autocapitalize', 'off');
		this._textArea.setAttribute('autofocus', 'true');
		this._textArea.setAttribute('autocorrect', 'off');
		this._textArea.setAttribute('autocomplete', 'off');
		this._textArea.setAttribute('spellcheck', 'false');

		// Prevent automatic line breaks in the textarea. Without this,
		// chromium/blink will trigger input/insertLineBreak events by
		// just adding whitespace.
		// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-wrap
		this._textArea.setAttribute('wrap', 'off');

		// Prevent autofocus
		this._textArea.setAttribute('disabled', true);

		this._setupStyles();

		this._emptyArea();
	},

	_setupStyles: function() {
		if (this._isDebugOn) {
			// Style for debugging
			this._container.style.opacity = 0.5;
			this._textArea.style.cssText = 'border:1px solid red !important';
			this._textArea.style.width = '120px';
			this._textArea.style.height = '50px';
			this._textArea.style.overflow = 'display';

			this._textArea.style.fontSize = '30px';
			this._textArea.style.position = 'relative';
			this._textArea.style.left = '10px';
		} else {
			this._container.style.opacity = 0;
			this._textArea.style.width = '1px';
			this._textArea.style.height = '1px';
			this._textArea.style.caretColor = 'transparent';

			if (L.Browser.isInternetExplorer || L.Browser.edge)
			{
				// Setting the font-size to zero is the only reliable
				// way to hide the caret in MSIE11, as the CSS "caret-color"
				// property is not implemented.
				this._textArea.style.fontSize = '0';
			}
		}
	},

	debug: function(debugOn) {
		this._isDebugOn = !!debugOn;
		this._setupStyles();
	},

	activeElement: function() {
		return this._textArea;
	},

	// Displays the caret and the under-caret marker.
	// Fetches the coordinates of the caret from the map's doclayer.
	showCursor: function() {
		if (!this._map._docLayer._cursorMarker) {
			return;
		}

		// Fetch top and bottom coords of caret
		var top = this._map._docLayer._visibleCursor.getNorthWest();
		var bottom = this._map._docLayer._visibleCursor.getSouthWest();

		// Display caret
		this._map.addLayer(this._map._docLayer._cursorMarker);

		// Move and display under-caret marker
		if (L.Browser.touch) {
			if (this._map._docLayer._selections.getLayers().length === 0) {
				this._cursorHandler.setLatLng(bottom).addTo(this._map);
			} else {
				this._map.removeLayer(this._cursorHandler);
			}
		}

		// Move the hidden text area with the cursor
		this._latlng = L.latLng(top);
		this.update();
	},

	// Hides the caret and the under-caret marker.
	hideCursor: function() {
		if (!this._map._docLayer._cursorMarker) {
			return;
		}
		this._map.removeLayer(this._map._docLayer._cursorMarker);
		this._map.removeLayer(this._cursorHandler);
	},

	_setPos: function(pos) {
		L.DomUtil.setPosition(this._container, pos);
	},

	// Generic handle attached to most text area events, just for debugging purposes.
	_onEvent: function _onEvent(ev) {
		var msg = {
			inputType: ev.inputType,
			data: ev.data,
			key: ev.key,
			isComposing: ev.isComposing
		};

		if ('key' in ev) {
			msg.key = ev.key;
			msg.keyCode = ev.keyCode;
			msg.code = ev.code;
			msg.which = ev.which;
		}
		this._fancyLog(ev.type, msg);
	},

	_fancyLog: function _fancyLog(type, payload) {
		// Avoid unhelpful exceptions
		if (payload === undefined)
			payload = 'undefined';
		else if (payload === null)
			payload = 'null';

		// Save to downloadable log
		L.Log.log(payload.toString(), 'INPUT');

		// Pretty-print on console (but only if "tile layer debug mode" is active)
		if (this._isDebugOn) {
			var state = this._isComposing ? 'C' : 'N';
			state += this._hasWorkingSelectionStart ? 'S' : '-';
			state += this._ignoreNextBackspace ? 'I' : '-';
			state += ' ';

			var textSel = this._textArea.selectionStart + '!' + this._textArea.selectionEnd;
			state += textSel + ' ';

			var sel = window.getSelection();
			var content = this.getValue();
			if (sel === null)
				state += '-1';
			else
			{
				state += sel.rangeCount;

				state += ' ';
				var cursorPos = -1;
				for (var i = 0; i < sel.rangeCount; ++i)
				{
					var range = sel.getRangeAt(i);
					state += range.startOffset + '-' + range.endOffset + ' ';
					if (cursorPos < 0)
						cursorPos = range.startOffset;
				}
				if (sel.toString() !== '')
					state += ': "' + sel.toString() + '" ';

				// inject probable cursor
				if (cursorPos >= 0)
					content = content.slice(0, cursorPos) + '|' + content.slice(cursorPos);
			}

			state += '[' + this._deleteHint + '] ';

			console.log2(
				+ new Date() + ' %cINPUT%c: ' + state
				+ '"' + content + '" ' + type + '%c ',
				'background:#bfb;color:black',
				'color:green',
				'color:black',
				JSON.stringify(payload)
			);
		}
	},

	// Backspaces and deletes at the beginning / end are filtered out, so
	// we get a beforeinput, but no input for them. Sometimes we can end up
	// in a state where we lost our leading / terminal chars and can't recover
	_onBeforeInput: function _onBeforeInput(ev) {
		this._ignoreNextBackspace = false;
		if (this._hasWorkingSelectionStart) {
			var value = this._textArea.value;
			if (value.length == 2 && value === this._preSpaceChar + this._postSpaceChar &&
			    this._textArea.selectionStart === 0)
			{
				// It seems some inputs eg. GBoard can magically move the cursor from " | " to "|  "
				console.log('Oh dear, gboard sabotaged our cursor position, fixing');
				// But when we detect the problem only emit a delete when we have one.
				if (ev.inputType && ev.inputType === 'deleteContentBackward')
				{
					this._removeTextContent(1, 0);
					// Having mended it we now get a real backspace on input (sometimes)
					this._ignoreNextBackspace = true;
				}
				this._emptyArea();
			}
		}
	},

	// Fired when text has been inputed, *during* and after composing/spellchecking
	_onInput: function _onInput(ev) {
		this._map.notifyActive();

		if (this._ignoreInputCount > 0) {
			console.log('ignoring synthetic input ' + this._ignoreInputCount);
			return;
		}

		if (ev.inputType) {
			if (ev.inputType == 'deleteContentForward')
				this._deleteHint = 'delete';
			else if (ev.inputType == 'deleteContentBackward')
				this._deleteHint = 'backspace';
			else
				this._deleteHint = '';
		}

		var ignoreBackspace = this._ignoreNextBackspace;
		this._ignoreNextBackspace = false;

		var content = this.getValueAsCodePoints();

		var preSpaceChar = this._preSpaceChar.charCodeAt(0);
		var postSpaceChar = this._postSpaceChar.charCodeAt(0);

		// We use a different leading and terminal space character
		// to differentiate backspace from delete, then replace the character.
		if (content.length < 1 || content[0] !== preSpaceChar) { // missing initial space
			console.log('Sending backspace');
			if (!ignoreBackspace)
				this._removeTextContent(1, 0);
			this._emptyArea();
			return;
		}
		if (content[content.length-1] !== postSpaceChar) { // missing trailing space.
			console.log('Sending delete');
			this._removeTextContent(0, 1);
			this._emptyArea();
			return;
		}
		if (content.length < 2) {
			console.log('Missing terminal nodes: ' + this._deleteHint);
			if (this._deleteHint == 'backspace' ||
			    this._textArea.selectionStart === 0)
			{
				if (!ignoreBackspace)
					this._removeTextContent(1, 0);
			}
			else if (this._deleteHint == 'delete' ||
				 this._textArea.selectionStart === 1)
				this._removeTextContent(0, 1);
			else
				console.log('Cant detect delete or backspace');
			this._emptyArea();
			return;
		}

		// remove leading & tailing spaces.
		content = content.slice(1, -1);

		var matchTo = 0;
		var sharedLength = Math.min(content.length, this._lastContent.length);
		while (matchTo < sharedLength && content[matchTo] === this._lastContent[matchTo])
			matchTo++;

		console.log('Comparison matchAt ' + matchTo + '\n' +
			    '\tnew "' + String.fromCharCode.apply(null, content) + '" (' + content.length + ')' + '\n' +
			    '\told "' + String.fromCharCode.apply(null, this._lastContent) + '" (' + this._lastContent.length + ')');

		var removeBefore = this._lastContent.length - matchTo;
		var removeAfter = 0;

		if (this._lastContent.length > content.length)
		{
			// Pressing '<space><delete>' can delete our terminal space
			// such that subsequent deletes will do nothing; need to
			// detect and reset in this case.
			if (this._deleteHint === 'delete')
			{
				removeBefore--;
				removeAfter++;
			}
		}

		if (removeBefore > 0 || removeAfter > 0)
			this._removeTextContent(removeBefore, removeAfter);

		var newText = content;
		if (matchTo > 0)
			newText = newText.slice(matchTo);

		this._lastContent = content;

		if (this._linebreakHint && this._map.dialog._calcInputBar &&
			this._map.getWinId() === this._map.dialog._calcInputBar.id) {
			this._sendKeyEvent(13, 5376);
		} else if (newText.length > 0) {
			this._sendText(String.fromCharCode.apply(null, newText));
		}

		// was a 'delete' and we need to reset world.
		if (removeAfter > 0)
			this._emptyArea();
	},

	// Sends the given (UTF-8) string of text to lowsd, as IME (text composition)
	// messages
	_sendText: function _sendText(text) {
		this._fancyLog('send-text-to-lowsd', text);

		// MSIE/Edge cannot compare a string to "\n" for whatever reason,
		// so compare charcode as well
		if (text === '\n' || (text.length === 1 && text.charCodeAt(0) === 13)) {
			// The composition messages doesn't play well with just a line break,
			// therefore send a keystroke.
			this._sendKeyEvent(13, 1280);
			this._emptyArea();
		} else {
			// The composition messages doesn't play well with line breaks inside
			// the composed word (e.g. word and a newline are queued client-side
			// and are sent together), therefore split and send keystrokes accordingly.

			var parts = text.split(/[\n\r]/);
			var l = parts.length;
			for (var i = 0; i < l; i++) {
				if (i !== 0) {
					this._sendKeyEvent(13, 1280);
					this._emptyArea();
				}
				if (parts[i].length > 0) {
					this._sendCompositionEvent(parts[i]);
				}
			}
		}
	},

	// Empties the textarea / contenteditable element.
	// If the browser supports the 'inputType' property on 'input' events, then
	// add empty spaces to the textarea / contenteditable, in order to
	// always catch deleteContentBackward/deleteContentForward input events
	// (some combination of browser + input method don't fire those on an
	// empty contenteditable).
	_emptyArea: function _emptyArea(noSelect) {
		this._fancyLog('empty-area');

		this._ignoreInputCount++;
		// Note: 0xA0 is 160, which is the character code for non-breaking space:
		// https://www.fileformat.info/info/unicode/char/00a0/index.htm

		// Using normal spaces would make FFX/Gecko collapse them into an
		// empty string.
		// FIXME: is that true !? ...

		console.log('Set old/lastContent to empty');
		this._lastContent = [];

		this._textArea.value = this._preSpaceChar + this._postSpaceChar;

		// avoid setting the focus keyboard
		if (!noSelect) {
			this._textArea.setSelectionRange(1, 1);

			if (this._hasWorkingSelectionStart === undefined)
				this._hasWorkingSelectionStart = (this._textArea.selectionStart === 1);
		}

		this._fancyLog('empty-area-end');

		this._ignoreInputCount--;
	},

	_onCompositionStart: function _onCompositionStart(/*ev*/) {
		this._isComposing = true;
	},

	// Handled only in legacy situations ('input' events with an inputType
	// property are preferred).
	_onCompositionUpdate: function _onCompositionUpdate(ev) {
		this._map.notifyActive();
		this._onInput(ev);
	},

	// Chrome doesn't fire any "input/insertCompositionText" with "isComposing" set to false.
	// Instead , it fires non-standard "textInput" events, but those can be tricky
	// to handle since Chrome also fires "input/insertText" events.
	// The approach here is to use "compositionend" events *only in Chrome* to mark
	// the composing text as committed to the text area.
	_onCompositionEnd: function _onCompositionEnd(ev) {
		this._map.notifyActive();
		this._isComposing = false;
		this._onInput(ev);
	},

	// Called when the user goes back to a word to spellcheck or replace it,
	// on a timeout.
	// Very difficult to handle right now, so the strategy is to panic and
	// empty the text area.
	_abortComposition: function _abortComposition(ev) {
		this._fancyLog('abort-composition', ev.type);
		if (this._isComposing)
			this._isComposing = false;
		this._emptyArea(document.activeElement !== this._textArea);
	},

	_onKeyDown: function _onKeyDown(ev) {
		if (ev.keyCode === 8)
			this._deleteHint = 'backspace';
		else if (ev.keyCode === 46)
			this._deleteHint = 'delete';
		else {
			this._deleteHint = '';
			this._linebreakHint = ev.keyCode === 13 && ev.shiftKey;
		}
	},

	// Check arrow keys on 'keyup' event; using 'ArrowLeft' or 'ArrowRight'
	// shall empty the textarea, to prevent FFX/Gecko from ever not having
	// whitespace around the caret.
	// Across browsers, arrow up/down / home / end would move the caret to
	// the beginning/end of the textarea/contenteditable.
	_onKeyUp: function _onKeyUp(ev) {
		this._map.notifyActive();
		if (ev.key === 'ArrowLeft' || ev.key === 'ArrowRight' ||
		    ev.key === 'ArrowUp' || ev.key === 'ArrowDown' ||
		    ev.key === 'Home' || ev.key === 'End' ||
		    ev.key === 'PageUp' || ev.key === 'PageDown'
		) {
			this._emptyArea();
		}
	},

	// Used in the deleteContentBackward for deleting multiple characters with a single
	// message.
	// Will remove characters from the queue first, if there are any.
	_removeTextContent: function _removeTextContent(before, after) {
		console.log('Remove ' + before + ' before, and ' + after + ' after');

		/// TODO: rename the event to 'removetextcontent' as soon as lowsd supports it
		/// TODO: Ask Marco about it
		this._map._socket.sendMessage(
			'removetextcontext id=' +
			this._map.getWinId() +
			' before=' + before +
			' after=' + after
		);
	},

	// Tiny helper - encapsulates sending a 'textinput' websocket message.
	// sends a pair of "input" for a composition update paird with an "end"
	_sendCompositionEvent: function _sendCompositionEvent(text) {
		console.log('sending to lowsd: ', text);

		// We want to trigger auto-correction, but not if we may
		// have to delete a count of characters in the future,
		// which is specific to crazy mobile keyboard / IMEs:
		if (!window.mode.isMobile() && !window.mode.isTablet() &&
		    this._autoCorrectChars[text])
		{
			var codes = this._autoCorrectChars[text];
			this._sendKeyEvent(codes[0], codes[1], 'input');
			this._sendKeyEvent(codes[2], codes[3], 'up');
		}
		else
		{
			var encodedText = encodeURIComponent(text);
			var winId = this._map.getWinId();
			this._map._socket.sendMessage(
				'textinput id=' + winId + ' type=input text=' + encodedText);
			this._map._socket.sendMessage(
				'textinput id=' + winId + ' type=end text=' + encodedText);
		}
	},

	// Tiny helper - encapsulates sending a 'key' or 'windowkey' websocket message
	// "type" can be "input" (default) or "up"
	_sendKeyEvent: function _sendKeyEvent(charCode, unoKeyCode, type) {
		if (!type) {
			type = 'input';
		}
		if (this._map.editorHasFocus()) {
			this._map._socket.sendMessage(
				'key type=' + type + ' char=' + charCode + ' key=' + unoKeyCode + '\n'
			);
		} else {
			this._map._socket.sendMessage(
				'windowkey id=' +
					this._map.getWinId() +
					' type=' +
					type +
					' char=' +
					charCode +
					' key=' +
					unoKeyCode +
					'\n'
			);
		}
	},

	_onCursorHandlerDragEnd: function _onCursorHandlerDragEnd(ev) {
		var cursorPos = this._map._docLayer._latLngToTwips(ev.target.getLatLng());
		this._map._docLayer._postMouseEvent('buttondown', cursorPos.x, cursorPos.y, 1, 1, 0);
		this._map._docLayer._postMouseEvent('buttonup', cursorPos.x, cursorPos.y, 1, 1, 0);
	}
});

L.textInput = function() {
	return new L.TextInput();
};