Support text input using the OS’s IME system

This change extends the use of the event trap to allow in-line character addition
using the OS's IME. The event trap will now be moved to within the local user's
cursor block, and will become visible when a composition start event is detected.

This has been tested on Chrome, FF & Safari on all platforms. In addition, this
enables support in FF on Android.

Known issues
- No IME support on Chrome under Linux. The compositionend event emitted by Chrome
contains no data, so the input character can't be detected.
This commit is contained in:
Philip Peitsch
2013-12-18 11:05:32 +11:00
parent be6c4379f0
commit 8b6ef8f6ff
9 changed files with 338 additions and 28 deletions
+1
View File
@@ -314,6 +314,7 @@ set(UNTYPEDLIBJSFILES
lib/xmldom/RelaxNG2.js
lib/gui/Caret.js
lib/gui/EventManager.js
lib/gui/InputMethodEditor.js
lib/gui/ShadowCursor.js
lib/gui/UndoManager.js
lib/gui/UndoStateRules.js
-2
View File
@@ -199,8 +199,6 @@ gui.CaretManager = function CaretManager(sessionController) {
// wire up the cursor update to caret visibility update
cursor.subscribe(ops.OdtCursor.signalCursorUpdated, scheduleCaretVisibilityCheck);
// Negative tab index still allows focus, but removes accessibility by keyboard
getCanvasElement().setAttribute("tabindex", -1);
// Pass event focus to the session controller
sessionController.getEventManager().focus();
} else {
+14 -24
View File
@@ -35,7 +35,7 @@
* @source: https://github.com/kogmbh/WebODF/
*/
/*global runtime, gui */
/*global runtime, gui, core */
/**
* Event wiring and management abstraction layer
@@ -197,6 +197,7 @@ gui.EventManager = function EventManager(odtDocument) {
// Internet explorer will only supply mouse up & down on the window object
// For other browser though, listening to both will cause two events to be processed
listenEvent(/**@type {!Window}*/(window), eventName, delegate.handleEvent);
// TODO this needs to be rebound if canvasElement changes
listenEvent(canvasElement, eventName, delegate.handleEvent);
listenEvent(eventTrap, eventName, delegate.handleEvent);
}
@@ -227,8 +228,9 @@ gui.EventManager = function EventManager(odtDocument) {
* @returns {boolean}
*/
function hasFocus() {
return odtDocument.getDOM().activeElement === getCanvasElement();
return odtDocument.getDOM().activeElement === eventTrap;
}
this.hasFocus = hasFocus;
/**
* Find the all scrollable ancestor for the specified element
@@ -253,32 +255,25 @@ gui.EventManager = function EventManager(odtDocument) {
* Return event focus back to the event manager
*/
this.focus = function() {
var scrollParents,
canvasElement = getCanvasElement(),
selection = window.getSelection();
var scrollParents;
if (!hasFocus()) {
// http://www.whatwg.org/specs/web-apps/current-work/#focus-management
// Passing focus back to an element that did not previously have it will also
// cause the element to attempt to recentre back into scroll view
scrollParents = findScrollableParents(eventTrap);
canvasElement.focus();
eventTrap.focus();
scrollParents.forEach(function(scrollParent) {
scrollParent.restore();
});
}
if (selection && selection.extend) {
if (eventTrap.parentNode !== canvasElement) {
// The undo manager can replace the root element, discarding the original.
// The event trap node is still valid, and simply needs to be re-attached
// after this occurs.
canvasElement.appendChild(eventTrap);
}
// A browser selection in an editable area is necessary to allow cut/copy events to fire
// It doesn't have to be an accurate selection however as the SessionController will override
// the default browser handling.
selection.collapse(eventTrap.firstChild, 0);
selection.extend(eventTrap, eventTrap.childNodes.length);
}
};
/**
* Returns the event trap div
* @returns {!Element}
*/
this.getEventTrap = function() {
return eventTrap;
};
/**
@@ -305,11 +300,6 @@ gui.EventManager = function EventManager(odtDocument) {
};
eventTrap = doc.createElement("div");
eventTrap.id = "eventTrap";
eventTrap.setAttribute("contenteditable", "true");
eventTrap.style.position = "absolute";
eventTrap.style.left = "-10000px";
// Content is necessary for cut/copy to be enabled
eventTrap.appendChild(doc.createTextNode("dummy content"));
canvasElement.appendChild(eventTrap);
}
init();
+176
View File
@@ -0,0 +1,176 @@
/**
* Copyright (C) 2013 KO GmbH <copyright@kogmbh.com>
*
* @licstart
* The JavaScript code in this page is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero General Public License
* (GNU AGPL) as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. The code is distributed
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU AGPL for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this code. If not, see <http://www.gnu.org/licenses/>.
*
* As additional permission under GNU AGPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* As a special exception to the AGPL, any HTML file which merely makes function
* calls to this code, and for that purpose includes it by reference shall be
* deemed a separate work for copyright law purposes. In addition, the copyright
* holders of this code give you permission to combine this code with free
* software libraries that are released under the GNU LGPL. You may copy and
* distribute such a system following the terms of the GNU AGPL for this code
* and the LGPL for the libraries. If you modify this code, you may extend this
* exception to your version of the code, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your
* version.
*
* This license applies to this entire compilation.
* @licend
* @source: http://www.webodf.org/
* @source: https://github.com/kogmbh/WebODF/
*/
/*global runtime, gui, core, ops*/
runtime.loadClass("core.DomUtils");
runtime.loadClass("core.ScheduledTask");
runtime.loadClass("ops.OdtDocument");
runtime.loadClass("ops.OdtCursor");
/**
* @constructor
* @param {!string} inputMemberId
* @param {!ops.OdtDocument} odtDocument
* @param {!gui.EventManager} eventManager
*/
gui.InputMethodEditor = function InputMethodEditor(inputMemberId, odtDocument, eventManager) {
"use strict";
var window = runtime.getWindow(),
localCursor = null,
eventTrap = eventManager.getEventTrap(),
domUtils = new core.DomUtils(),
FAKE_CONTENT = "b",
clearTrapText;
/**
* Get the current canvas element. The current trivial undo manager replaces the root element
* of the ODF container with a clone from a previous state. This results in the root element
* being changed. As such, it can't be stored, and should be queried on each use.
* @returns {!Element}
*/
function getCanvasElement() {
// TODO Remove when a proper undo manager arrives
return odtDocument.getOdfCanvas().getElement();
}
function resetWindowSelection() {
var selection = window.getSelection(),
textNode = eventTrap.firstChild,
doc = eventTrap.ownerDocument;
if (!domUtils.containsNode(getCanvasElement(), eventTrap)) {
// TODO Remove when a proper undo manager arrives
// The undo manager can replace the root element, discarding the original.
// The event trap node is still valid, and simply needs to be re-attached
// after this occurs.
// Don't worry about the local caret yet. The event trap will eventually be moved to
// a new valid local caret when it is registered upon cursor re-registration
getCanvasElement().appendChild(eventTrap);
}
if (!textNode) {
// Content is necessary for cut/copy/paste to be enabled
textNode = eventTrap.appendChild(doc.createTextNode(""));
}
// If there is a local cursor, and it is collapsed, collapse the window selection as well.
// Otherwise, ensure some text is selected by default.
// A browser selection in an editable area is necessary to allow cut/copy events to fire
// It doesn't have to be an accurate selection however as the SessionController will override
// the default browser handling.
if (localCursor && localCursor.getSelectedRange().collapsed) {
textNode.deleteData(0, textNode.length);
} else {
textNode.replaceData(0, textNode.length, FAKE_CONTENT);
}
// Obtain document focus again after a cursor update
// This is necessary because the cursor currently removes then adds itself back into the DOM
// breaking the focus on the event trap as a result
eventManager.focus();
selection.collapse(eventTrap.firstChild, 0);
if (selection.extend) {
selection.extend(eventTrap, eventTrap.childNodes.length);
}
}
function compositionStart() {
var cursorNode = localCursor.getNode();
cursorNode.setAttributeNS("urn:webodf:names:cursor", "composing", "true");
}
function compositionEnd() {
var cursorNode = localCursor.getNode();
cursorNode.removeAttributeNS("urn:webodf:names:cursor", "composing");
// The text is not updated until after the composition event fires
clearTrapText.trigger();
}
/**
* Handle a cursor registration event
* @param {!ops.OdtCursor} cursor
*/
this.registerCursor = function (cursor) {
var cursorNode, hasFocus;
if (cursor.getMemberId() === inputMemberId) {
hasFocus = eventManager.hasFocus();
localCursor = cursor;
localCursor.subscribe(ops.OdtCursor.signalCursorUpdated, resetWindowSelection);
cursorNode = localCursor.getNode();
cursorNode.insertBefore(eventTrap, cursorNode.firstChild);
if (hasFocus) {
// Relocating the event trap will reset the window selection
// Restore this again if the document previously had focus
resetWindowSelection();
}
}
};
/**
* Handle a cursor removal event
* @param {!string} memberid Member id of the removed cursor
*/
this.removeCursor = function (memberid) {
var hasFocus;
if (memberid === inputMemberId) {
hasFocus = eventManager.hasFocus();
localCursor.unsubscribe(ops.OdtCursor.signalCursorUpdated, resetWindowSelection);
localCursor = null;
getCanvasElement().appendChild(eventTrap);
resetWindowSelection();
if (hasFocus) {
// Relocating the event trap will reset the window selection
// Restore this again if the document previously had focus
eventManager.focus();
}
}
};
function init() {
eventManager.subscribe('compositionstart', compositionStart);
eventManager.subscribe('compositionend', compositionEnd);
eventTrap.setAttribute("contenteditable", "true");
// Negative tab index still allows focus, but removes accessibility by keyboard
eventTrap.setAttribute("tabindex", -1);
clearTrapText = new core.ScheduledTask(resetWindowSelection, 0);
}
init();
};
+25 -1
View File
@@ -58,6 +58,7 @@ runtime.loadClass("gui.TextManipulator");
runtime.loadClass("gui.AnnotationController");
runtime.loadClass("gui.EventManager");
runtime.loadClass("gui.PlainTextPasteboard");
runtime.loadClass("gui.InputMethodEditor");
/**
* @constructor
@@ -110,6 +111,7 @@ gui.SessionController = (function () {
drawShadowCursorTask,
redrawRegionSelectionTask,
pasteHandler = new gui.PlainTextPasteboard(odtDocument, inputMemberId),
inputMethodEditor = new gui.InputMethodEditor(inputMemberId, odtDocument, eventManager),
clickCount = 0,
hyperlinkClickHandler = new gui.HyperlinkClickHandler(odtDocument.getRootNode),
hyperlinkController = new gui.HyperlinkController(session, inputMemberId);
@@ -887,7 +889,7 @@ gui.SessionController = (function () {
// Unfortunately, clearing the range will also blur the current focus.
selection.removeAllRanges();
selection.addRange(range.cloneRange());
/**@type{!IEElement}*/(odtDocument.getOdfCanvas().getElement()).setActive();
/**@type{!IEElement}*/(eventManager.getEventTrap()).setActive();
}
}
@@ -1019,6 +1021,19 @@ gui.SessionController = (function () {
}
}
/**
* Handle composition end event. If there is data specified, treat this as text
* to be inserted into the document.
* @param {!CompositionEvent} e
*/
function insertNonEmptyData(e) {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-compositionend
var input = e.data;
if (input) {
textManipulator.insertText(input);
}
}
/**
* @return {undefined}
*/
@@ -1026,6 +1041,8 @@ gui.SessionController = (function () {
var op;
odtDocument.getOdfCanvas().getElement().classList.add("virtualSelections");
eventManager.subscribe("compositionupdate", textManipulator.removeCurrentSelection);
eventManager.subscribe("compositionend", insertNonEmptyData);
eventManager.subscribe("keydown", keyDownHandler.handleEvent);
eventManager.subscribe("keypress", keyPressHandler.handleEvent);
eventManager.subscribe("keyup", keyUpHandler.handleEvent);
@@ -1044,6 +1061,9 @@ gui.SessionController = (function () {
odtDocument.subscribe(ops.OdtDocument.signalOperationExecuted, redrawRegionSelectionTask.trigger);
odtDocument.subscribe(ops.OdtDocument.signalOperationExecuted, updateUndoStack);
odtDocument.subscribe(ops.OdtDocument.signalCursorAdded, inputMethodEditor.registerCursor);
odtDocument.subscribe(ops.OdtDocument.signalCursorRemoved, inputMethodEditor.removeCursor);
op = new ops.OpAddCursor();
op.init({memberid: inputMemberId});
session.enqueue([op]);
@@ -1069,9 +1089,13 @@ gui.SessionController = (function () {
undoManager.resetInitialState();
}
odtDocument.unsubscribe(ops.OdtDocument.signalCursorAdded, inputMethodEditor.registerCursor);
odtDocument.unsubscribe(ops.OdtDocument.signalCursorRemoved, inputMethodEditor.removeCursor);
odtDocument.unsubscribe(ops.OdtDocument.signalOperationExecuted, updateUndoStack);
odtDocument.unsubscribe(ops.OdtDocument.signalOperationExecuted, redrawRegionSelectionTask.trigger);
eventManager.unsubscribe("compositionupdate", textManipulator.removeCurrentSelection);
eventManager.unsubscribe("compositionend", insertNonEmptyData);
eventManager.unsubscribe("keydown", keyDownHandler.handleEvent);
eventManager.unsubscribe("keypress", keyPressHandler.handleEvent);
eventManager.unsubscribe("keyup", keyUpHandler.handleEvent);
+8
View File
@@ -137,6 +137,13 @@
"odf/Namespaces.js",
"odf/OdfCanvas.js"
],
"gui/InputMethodEditor.js": [
"core/DomUtils.js",
"core/ScheduledTask.js",
"gui/EventManager.js",
"ops/OdtCursor.js",
"ops/OdtDocument.js"
],
"gui/KeyboardHandler.js": [
],
"gui/PlainTextPasteboard.js": [
@@ -181,6 +188,7 @@
"gui/HyperlinkController.js",
"gui/ImageManager.js",
"gui/ImageSelector.js",
"gui/InputMethodEditor.js",
"gui/KeyboardHandler.js",
"gui/PlainTextPasteboard.js",
"gui/SelectionMover.js",
+56
View File
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html>
<head>
<title>IME test harness</title>
</head>
<body>
<h1>Enter text using an IME into the box below</h1>
<div id="editArea" contenteditable="true" style="width: 100px; height: 100px; background-color: red"></div>
<pre id="log"></pre>
<script type="text/javascript">
var editArea = document.getElementById("editArea"),
log = document.getElementById("log"),
updateRequested = false,
cycleCount = 0;
function updateTick() {
if (updateRequested) {
updateRequested = false;
cycleCount++;
}
}
function logInfo(text) {
log.insertBefore(document.createTextNode(text + " |cycle: " + cycleCount + "\n"), log.firstChild);
updateRequested = true;
}
editArea.addEventListener("input", function() {
logInfo("input: " + editArea.textContent);
});
editArea.addEventListener("textInput", function(e) {
logInfo("textInput: " + e.data);
});
editArea.addEventListener("keydown", function(e) {
logInfo("keydown: " + String.fromCharCode(e.which));
});
editArea.addEventListener("keypress", function(e) {
logInfo("keypress: " + String.fromCharCode(e.which));
});
editArea.addEventListener("keyup", function(e) {
logInfo("keyup: " + String.fromCharCode(e.which));
});
editArea.addEventListener("compositionstart", function(e) {
logInfo("compositionstart: " + e.data);
});
editArea.addEventListener("compositionupdate", function(e) {
logInfo("compositionupdate: " + e.data);
});
editArea.addEventListener("compositionend", function(e) {
logInfo("compositionend: " + e.data);
});
setInterval(updateTick, 0);
</script>
</body>
</html>
+12
View File
@@ -615,3 +615,15 @@ Range.END_TO_END = 2;
* @type {!number}
*/
Range.END_TO_START = 3;
/**
* https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#interface-CompositionEvent
* @constructor
* @extends Event
*/
function CompositionEvent() { "use strict"; }
/**
* @type {!string}
*/
CompositionEvent.prototype.data;
+46 -1
View File
@@ -222,13 +222,14 @@ video {
/* below set up the cursor */
cursor|cursor {
display: inline;
width: 0px;
width: 0;
height: 1em;
/* making the position relative enables the avatar to use
the cursor as reference for its absolute position */
position: relative;
z-index: 1;
}
cursor|cursor > .caret {
/* IMPORTANT: when changing these values ensure DEFAULT_CARET_TOP and DEFAULT_CARET_HEIGHT
in Caret.js remain in sync */
@@ -269,6 +270,50 @@ cursor|cursor > .handle:after {
left: 43%;
}
/** Input Method Editor input pane & behaviours */
/* not within a cursor */
#eventTrap {
height: 1px;
margin: auto 0;
display: block;
position: absolute;
left: -10000px;
width: 1px;
outline: none;
}
/* within a cursor */
cursor|cursor > #eventTrap {
display: inline-block;
position: static;
left: 0;
margin-right: -1px; /* Hide the content editable's own caret */
color: rgba(255, 255, 255, 0); /** additionally hide the blinking caret by setting the colour to fully transparent */
overflow: hidden; /* The overflow visibility is used to hide and show characters being entered */
height: 1px;
width: 1px; /* marginRight + width must equal 0 so chrome & FF don't think the element takes up space */
}
cursor|cursor[cursor|composing="true"] > #eventTrap {
color: inherit; /* make colour non-transparent again to show the entered text */
overflow: visible; /* The overflow visibility is used to hide and show characters being entered */
height: auto;
width: auto;
}
cursor|cursor[cursor|composing="true"] {
display: inline-block;
width: auto;
height: inherit;
}
cursor|cursor[cursor|composing="true"] > .caret {
/* during composition, the caret should be pushed along by the composition text, inline with the text */
position: static;
/* as it is now part of an inline-block, it will no longer need correct to top or height values to align properly */
height: auto !important;
top: auto !important;
}
.editInfoMarker {
position: absolute;