WebAPI/KeboardIME: Difference between revisions

From MozillaWiki
Jump to navigation Jump to search
(→‎Proposed API: Update proposed API to the latest one posted on dev-webapi)
(Remove the IDL draft)
 
(68 intermediate revisions by 9 users not shown)
Line 1: Line 1:
= Virtual Keyboard/IME API =


__TOC__
__TOC__
Line 18: Line 17:
# [https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.webapi/Vs3-HGv9NNw WebAPI mailing list post]
# [https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.webapi/Vs3-HGv9NNw WebAPI mailing list post]
# [https://groups.google.com/forum/?fromgroups=#!topic/mozilla.dev.webapi/A7dIBaR3lpU Extended API mailing list post]
# [https://groups.google.com/forum/?fromgroups=#!topic/mozilla.dev.webapi/A7dIBaR3lpU Extended API mailing list post]
# [https://groups.google.com/forum/#!msg/mozilla.dev.webapi/nZLOEvEL3Tk/M-nSnP6HZgoJ Polished Keyboard API]


Implementation:
Implementation:
#{{bug|737110}} - Bug 737110 - Virtual Keyboard API
#{{bug|737110}} - Bug 737110 - Virtual Keyboard API
#{{bug|805586}} - [keyboard] keyboard needs a 'hide keyboard' button(main tracking bug)
#{{bug|844716}} - Enable keyboard Apps to get/set selection range of the input field
#{{bug|860546}} - [keyboard] JS changes to a textfield while keyboard is displayed do not get passed to keyboard
#{{bug|861665}} - Allow IME to get notification when text field content is changed
#{{bug|861515}} - Keyboard should be able to modify the text of the input field directly
#{{bug|838308}} - mozKeyboard should require a permission to use
#{{bug|842436}} - Keyboard API: There should only be one keyboard active, and Gecko should block interaction from non-active keyboards


== Features ==
== Features ==
Line 33: Line 26:
The Virtual Keyboard/IME API supports the following features:
The Virtual Keyboard/IME API supports the following features:


* Notifies the VKB app when the focus text field was changing in other
* Notifies the VKB app when the focus text field was changing in other apps
apps
* Allow user to manual hide the keyboard. Check {{bug|737110}}.
* Allow user to manual hide the keyboard. Check {{bug|737110}}.
* The VKB app should be responsive to properties and the state of the  input field (more than HTML5 input type, including current content,  cursor position, x-inputmode {{bug|796544}}).
* The VKB app should be responsive to properties and the state of the  input field (more than HTML5 input type, including current content,  cursor position, x-inputmode {{bug|796544}}).
Line 45: Line 37:
* The return key label of the VKB can be customized.
* The return key label of the VKB can be customized.


== Proposed API ==
== Proposed Manifest of a 3rd-Party IME ==


partial interface Navigator {
Just like any other apps, keyboard apps register themselves in the same apps registry. We extend the manifest syntax here to describe layout(s) available in a given keyboard app. Gaia will be paring the manifest. There are 3 special fields to distinguish and describe a 3rd-party IME:
    readonly attribute InputMethodManager mozInputMethodManager;
* [Line 4] a "role" field with value "keyboard" declares it's an IME app. Homescreen app will ignore some role types when displaying app icons, and "keyboard" is one of them. (see {{bug|892397}})
    readonly attribute InputMethodConnection mozInputMethodConnection;
* [Line 6-8] a "permissions" field that requests "keyboard" permission. All IME apps need this permission for sending input keys and updating the value of a input field.
};
* [Line 9-30] a "inputs" field specifies supported layouts. Each layout is described in a key-value pair, where the key represents the layout name (will be shown up on Settings app with the app name), and the value describes the detailed information of the layout, including launch path of the layout and supported input types. (See [[#Layout Matching Algorithm]])
** The allowed value in "types" field is a subset of [http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#attr-input-type type attribute of input element]: text, search, tel, number, url, email. Other types will be ignored by FxOS Gaia in the initial version because at this point UI for <select> and <input type=date> (called "value selectors") are not open for 3rd-party implementation.


dictionary InputMethodInfo {
{
    url: 'XXX',
  "name": "3rd-party Keyboard",
    name: 'IME name',
  "description": "3rd-party Keyboard",
    locale: 'en-US',
  "type": "privilege",
};
  "role": "input",
  "launch_path": "/settings.html",
  "developer": {
    "name": "developer's name",
    "url": "https://keyboard.example.com"
  },
  "permissions": {
    "input": {}
  },
  "inputs": {
    "en": {
      "launch_path": "/index.html#en",
      "name": "English",
      "description": "English layout",
      "types": ["url", "text"],
      "locales": {
        "en-US": {
          "name": "English",
          "description": "English layout"
        },
        "zh-TW": {
          "name": "英文",
          "description": "英文鍵盤"
        }
      }
    },
    "en-Dvorak": {
      "launch_path": "/index.html#en-Dvorak",
      "name": "English (Dvorak)",
      "description": "Dvorak layout",
      "types": ["url", "text"]
    },
    "es": {
      "launch_path": "/index.html#es",
      "name": "Spanish",
      "description": "Spanish layout",
      "types": ["url", "text"]
    },
    "pt-BR": {
      "launch_path": "/index.html#pt-BR",
      "name": "Portuguese Brazilian",
      "description": "Portuguese Brazilian layout",
      "types": ["url", "text"]
    },
    "pl": {
      "launch_path": "/index.html#pl",
      "name": "Polish",
      "description": "Polish layout",
      "types": ["url", "text"]
    },
    "ca": {
      "launch_path": "/index.html#ca",
      "name": "Catalan",
      "description": "Catalan layout",
      "types": ["url", "text"]
    },
    "cz": {
      "launch_path": "/index.html#cz",
      "name": "Czech",
      "description": "Czech layout",
      "types": ["url", "text"]
    },
    "fr": {
      "launch_path": "/index.html#fr",
      "name": "French",
      "description": "French layout",
      "types": ["url", "text"]
    },
    "de": {
      "launch_path": "/index.html#de",
      "name": "German",
      "description": "German layout",
      "types": ["url", "text"]
    },
    "nb": {
      "launch_path": "/index.html#nb",
      "name": "Norwegian Bokmal",
      "description": "Norwegian Bokmal layout",
      "types": ["url", "text"]
    },
    "sk": {
      "launch_path": "/index.html#sk",
      "name": "Slovak",
      "description": "Slovak layout",
      "types": ["url", "text"]
    },
    "tr-Q": {
      "launch_path": "/index.html#tr-Q",
      "name": "Turkish Q",
      "description": "Turkish Q layout",
      "types": ["url", "text"]
    },
    "tr-F": {
      "launch_path": "/index.html#tr-F",
      "name": "Turkish F",
      "description": "Turkish F layout",
      "types": ["url", "text"]
    },
    "ro": {
      "launch_path": "/index.html#ro",
      "name": "Romanian",
      "description": "Romanian layout",
      "types": ["url", "text"]
    },
    "ru": {
      "launch_path": "/index.html#ru",
      "name": "Russian",
      "description": "Russian layout",
      "types": ["url", "text"]
    },
    "sr-Cyrl": {
      "launch_path": "/index.html#sr-Cyrl",
      "name": "Serbian (Cyrillic)",
      "description": "Serbian (Cyrillic) layout",
      "types": ["url", "text"]
    },
    "sr-Latn": {
      "launch_path": "/index.html#sr-Latn",
      "name": "Serbian (Latin)",
      "description": "Serbian (Latin) layout",
      "types": ["url", "text"]
    },
    "ar": {
      "launch_path": "/index.html#ar",
      "name": "Arabic",
      "description": "Arabic layout",
      "types": ["url", "text"]
    },
    "he": {
      "launch_path": "/index.html#he",
      "name": "Hebrew",
      "description": "Hebrew layout",
      "types": ["url", "text"]
    },
    "hu": {
      "launch_path": "/index.html#hu",
      "name": "Hungarian",
      "description": "Hungarian layout",
      "types": ["url", "text"]
    },
    "el": {
      "launch_path": "/index.html#el",
      "name": "Greek",
      "description": "Greek layout",
      "types": ["url", "text"]
    },
    "zh-Hans-Pinyin": {
      "launch_path": "/index.html#zh-Hans-Pinyin",
      "name": "Pinyin",
      "description": "Pinyin",
      "types": ["url", "text"]
    },
    "number": {
      "launch_path": "/index.html#numberLayout",
      "name": "Number",
      "description": "Number layout",
      "types": ["number"]
    }
  },
  "locales": {
    "en-US": {
      "name": "3rd-party Keyboard",
      "description": "3rd-party Keyboard"
    },
    "zh-TW": {
      "name": "第三方鍵盤",
      "description": "第三方鍵盤"
    }
  },
  "default_locale": "en-US"
}


// Manages the list of IMEs, enables/disables IME and switches to an IME.
=== Layout Matching Algorithm ===
interface InputMethodManager {
    // Show a (system) menu for all enabled input methods that allow user to select.
    void showInputMethodPicker();
    // Get a list of all installed IMEs.
    Promise<InputMethodInfo[]> getAll();
    // Get a list of all enabled IMEs.
    Promise<InputMethodInfo[]> getEnabled();
    // Get input method info of the caller IME.
    Promise<InputMethodInfo> getSelf();
    // Switch to the given IME.
    // Privileged API. Only the system app and current IME can switch IME.
    Promise<boolean> setCurrentInputMethod(InputMethodInfo info);
    // Switch to next IME.
    // We may not need this method and use setCurrentInputMethod instead.
    Promise<boolean> switchToNextInputMethod();
    // Get current IME.
    Promise<InputMethodInfo> getCurrentInputMethod();
    // Enable an IME.
    // Privileged API. Only the system app can eanble an IME.
    Promise<boolean> enable(InputMethodInfo info);
    // Disable an IME.
    // Privileged API. Only the system app can disable an IME.
    Promise<boolean> disable(InputMethodInfo info);
  };


// The input context, which are attributes and information of current input field.
When an input field is focused, if its <code>type</code> attribute is one of the allowed values stated above, it will be used to filter a set of candidate layouts. A candidate layout means it can handle this input type or is possible to let user input all characters that this input field can accept.
dictionary InputMethodContext {
For example, if the type of a input is "url", then a layout with "url" or "text" listed in the <code>types</code> of its manifest will be matched. However, if a input field with type "text", then all layouts that support "text" will be matched, but those layouts that only support "url" will not. This is because we believe layouts that can handle "text" could be a fallback for "url" input type, but not vice versa. We also believe "text" could be a fallback for all allowed types stated above.
    // This is used to specify the target of input field operations. This ID becomes invalid as soon as user leaves input field and blur event is sent.
    long contextId;
    // The tag name of input field, which is enum of "input", "textarea", or "contenteditable"
    DOMString name;
    // The type of the input field, which is enum of text, number, password, url, search and email.
    DOMString type;
    /*
      * The input mode string.
      * https://bugzilla.mozilla.org/show_bug.cgi?id=796544
      * It can be one of the following values:
      * "none"
      * "verbatim"   - no capitalization, no word suggestions
      * "latin"      - word suggestions but no capitalization
      * "latin-prose" - word suggestions and capitalization at the start of sentences
      * "latin-name"  - word suggestions and capitalize each word
      * "digit"      - digits(0-9) only.
      */
    DOMString inputmode;
    /*
    * The primary language for the input field.
    * It is the value of HTMLElement.lang.
    * see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#htmlelement
    */
    DOMString lang;
};


interface InputMethodConnection: EventTarget {
The matching algorithm of keyboard manager in System app is as follows:
    // It informs the IME that text input has started in an input field. If the IME is activated, this event is sent when focus enters a new input field. Otherwise this event is sent when user switches to the IME and activates it.
    attribute EventHandler onstart;
    // It informs the IME that text input has finished in last input field. This event is sent when focus leaves current input field or user switches to another IME.
    attribute EventHandler onfinish;
    // This event is sent when the attributes of input context has changed, such as type, but focus has not.
    attribute EventHandler oncontextchange;
    /*
    * This event is sent when the text around the cursor is changed, due to either text
    * editing or cursor movement. The text length is limited to 100 characters for each
    * back and forth direction.
    *
    * The event handler function is specified as:
    * @param beforeString Text before and including cursor position.
    * @param afterString Text after and excluing cursor position.
    * function(long contextId, DOMString beforeText, DOMString afterText) {
    * ...
    *  }
    */
    attribute SurroundingTextChangeEventHandler onsurroundingtextchange;
    // User moves the cursor, changes the selection, or alters the composing text length
    attribute EventHandler onselectionchange;
    // TODO: maybe the parameters could be simpler?
    Promise<boolean> sendKey(long contextId, long keyCode, long charCode, long modifiers);
    // Or Promise<boolean> sendKey(long contextId, KeyboardEvent event)
    /*
    *  Get the whole text content of the input field.
    */
    Promise<DOMString> getText(long contextId);
    /*
    * Commit text to current input field and replace text around cursor position. It will clear the current composition.
    *
    * @param text The string to be replaced with.
    * @param offset The offset from the cursor position where replacing starts. Defaults to 0.
    * @param length The length of text to replace. Defaults to 0.
    */
    Promise<boolean> commitText(long contextId, DOMString text, [optional] long offset, [optional] long length);
    /*
      *
      * Delete text around the cursor.
      * @param offset The offset from the cursor position where deletion starts.
      * @param length The length of text to delete.
      */
    Promise<boolean> deleteSurroundingText(long offset, long length);
    // The start and stop position of the selection.
    readonly attribute long selectionStart;
    readonly attribute long selectionEnd;
    /*
      * Set the selection range of the the editable text.
      * Note: This method cannot be used to move the cursor during composition. Calling this
      * method will cancel composition.
      * @param start The beginning of the selected text.
      * @param length The length of the selected text.
      *
      * Note that the start position should be less or equal to the end position.
      * To move the cursor, set the start and end position to the same value.
      */
    Promise<boolean> setSelectionRange(long contextId, long start, long length);
    /*
      * Set current composition. It will start or update composition.
      * @param cursor Position in the text of the cursor.
      */
    Promise<boolean> setComposition(long contextId, DOMString text, long cursor);
    /*
      * Clear composition. Called to cancel composition.
      * Use commitText to end composition and commit text.
      */
    Promise<boolean> clearComposition(long contextId);
    // Clear the focus of the current input field and hide the keyboard.
    Promise<boolean> removeFocus(long contextId);
    // The input method context
    readonly attribute InputMethodContext elementInfo;
};


[TreatNonCallableAsNull]
# With the given type, find all layouts claims to support the said type and put it into the list.
callback SurroundingTextChangeEventHandlerNonNull = void (long contextId, DOMString beforeText, DOMString afterText);
# Next, find layouts claims to support "text" and put it into the list. Layouts do not get duplicated listing even if it supports both types.
typedef SurroundingTextChangeEventHandlerNonNull? SurroundingTextChangeEventHandler;
# Present the user with the choice of the layouts available to handle the input field. The order of presenting list is depend on UX design and/or user preferences in Settings.


== Examples ==
== Proposed API ==


var conn = navigator.mozInputMethodConnection;
'''The API has made available to privileged apps. See the [http://dxr.mozilla.org/mozilla-central/source/dom/webidl/InputMethod.webidl WebIDL] for the current interface.'''


// Called when the user starts or finishes editing an input field
[https://wiki.mozilla.org/index.php?title=WebAPI/KeboardIME&oldid=1029753#Proposed_API History of this section]
conn.oninputmethodstatechange= function(event) {
    if (conn.inputStarted) {
        // Text input should start
    } else {
        // Text input should end
    }
};


// Insert a string at the current cursor position
=== Use cases for each of the methods ===
conn.replaceSurroundingText('Hello world');


// Clear delete 5 characters before the cursor position.
* For a simple virtual keyboard action (send a character and key events w/ each user action), use <code>sendKey()</code>. TODO: should we allow backspace key to be sent from the method? If not, how do send these non-printable characters and it's effect with key events?
conn.replaceSurroundingText('', 5);
**[yxl] I perfer to allowing non-printable character, such as backspace key, to be sent, if there is no security issue. This would give the IME more flexibility.
* For spellcheck, autocomplete etc, use surrounding text methods.
* For cursor moment helper features, use <code>setSelectionRange()</code> and related attributes.
* For Asian IMEs that sends characters and composition along with the composition events, use <code>setComposition()</code> and <code>endComposition()</code>.


// Get the selected text
It is important to stick with the given use cases because the web application might need to react with what the user actually do. To test the events currently sent to the web, see http://jsfiddle.net/timdream/YDGgk/ .
conn.getText(conn.selectionStart, conn.selectionEnd, function callback(text) {
    var selectedText = text;
});


// Get notified when the text content has changed.
== Examples ==
conn.ontextchange = function() {
  conn.getText(0, conn.textLength, function(text) {
    console.log(text);
  }
}


// Move the cursor position
The following "snowman filler" Keyboard app will start filling snowman character ("☃") and follow by characters "SNOW" with key events to the input field whenever the user is focus on a input field and switch to the keyboard app.
var position = 10;
conn.setSelectionRange(position, position);


// Hide the keyboard
If the field is a numeric field, it will fill "1337".
conn.removeFocus();


  // Switch the focus onto the next input field if possible
  var timer;
  if (conn.canAdvanceFocus) {
function startTyping(inputContext) {
    conn.advanceFocus();
  clearTimeout(timer);
  timer = setInterval(function typing() {
    /* [JJ] So I think that this code shouldn't be here, because you'll get lots of clutter
      *      as you'll also have to take languages into account.
      *      Rather rely on entry points in manifest...
      */
    if (inputContext.inputmode === 'numeric' || inputContext.type === 'number') {
      ['1', '3', '3', '7'].forEach(function (k) {
        // For numbers, keyCode is same as the charCode.
        inputContext.sendKey(k.charCodeAt(0), k.charCodeAt(0));
      });
    } else {
      // It's not a good idea to commit text w/o sending events. So we should first send composition events.
      inputContext.setComposition('☃');
      // end the composition and commit the text.
      inputContext.endComposition('☃');
      ['S', 'N', 'O', 'W'].forEach(function (k) {
        // For capital Latin letters, keyCode is same as the charCode.
        inputContext.sendKey(k.charCodeAt(0), k.charCodeAt(0));
      });
  }, 1000);
}
function stopTyping() {
  clearTimeout(timer);
}
var im = navigator.inputMethod;
im.addEventListener('inputcontextchange', function contextchanged(evt) {
  if (evt.inputcontext) {
      // Got a new context, start working with it.
      startTyping(evt.inputcontext);
  } else {
      // The user have removed the focus, we are not allow to type into the text field anymore.
      stopTyping();
  }
});
  if (im.inputcontext) {
  // The webpage here is loaded *after* the user has place the focus on the text field,
  // let's start typing now.
  startTyping(im.inputcontext);
  }
  }


Line 269: Line 315:


http://developer.chrome.com/trunk/extensions/input.ime.html
http://developer.chrome.com/trunk/extensions/input.ime.html
[[Category:Web APIs]]

Latest revision as of 03:35, 3 November 2014

Introduction

Virtual Keyboard/IME API aims to implement the system IME as a Web App. It will be used in Firefox OS and use cases could be found in the Firefox OS Keyboard UX document(WIP).

The API provides the communication channel between the IME App and the other App that receives user's inputs.

It is very different from the IME API from Google that aims to re-use the system's IME in a web page.

Status

API discussion:

  1. WebAPI mailing list post
  2. Extended API mailing list post
  3. Polished Keyboard API

Implementation:

  1. bug 737110 - Bug 737110 - Virtual Keyboard API

Features

The Virtual Keyboard/IME API supports the following features:

  • Notifies the VKB app when the focus text field was changing in other apps
  • Allow user to manual hide the keyboard. Check bug 737110.
  • The VKB app should be responsive to properties and the state of the input field (more than HTML5 input type, including current content, cursor position, x-inputmode bug 796544).
  • Sends trust
  • The VKB app should be able to send trusted key events such as they are considered by the other apps as user' inputs.
  • The VKB app should be able to send a character or a string to the current input cursor position.
  • Keyboard should be able to overwrite the current value of the input field of the input field and set the cursor position.
  • The VKB app should be able to move the cursor position or select a specified range of text.
  • The VKB should be able to switch the focus onto the previous/next input field.
  • The return key label of the VKB can be customized.

Proposed Manifest of a 3rd-Party IME

Just like any other apps, keyboard apps register themselves in the same apps registry. We extend the manifest syntax here to describe layout(s) available in a given keyboard app. Gaia will be paring the manifest. There are 3 special fields to distinguish and describe a 3rd-party IME:

  • [Line 4] a "role" field with value "keyboard" declares it's an IME app. Homescreen app will ignore some role types when displaying app icons, and "keyboard" is one of them. (see bug 892397)
  • [Line 6-8] a "permissions" field that requests "keyboard" permission. All IME apps need this permission for sending input keys and updating the value of a input field.
  • [Line 9-30] a "inputs" field specifies supported layouts. Each layout is described in a key-value pair, where the key represents the layout name (will be shown up on Settings app with the app name), and the value describes the detailed information of the layout, including launch path of the layout and supported input types. (See #Layout Matching Algorithm)
    • The allowed value in "types" field is a subset of type attribute of input element: text, search, tel, number, url, email. Other types will be ignored by FxOS Gaia in the initial version because at this point UI for <select> and <input type=date> (called "value selectors") are not open for 3rd-party implementation.

{

 "name": "3rd-party Keyboard",
 "description": "3rd-party Keyboard",
 "type": "privilege",
 "role": "input",
 "launch_path": "/settings.html",
 "developer": {
   "name": "developer's name",
   "url": "https://keyboard.example.com"
 },
 "permissions": {
   "input": {}
 },
 "inputs": {
   "en": {
     "launch_path": "/index.html#en",
     "name": "English",
     "description": "English layout",
     "types": ["url", "text"],
     "locales": {
       "en-US": {
         "name": "English",
         "description": "English layout"
       },
       "zh-TW": {
         "name": "英文",
         "description": "英文鍵盤"
       }
     }
   },
   "en-Dvorak": {
     "launch_path": "/index.html#en-Dvorak",
     "name": "English (Dvorak)",
     "description": "Dvorak layout",
     "types": ["url", "text"]
   },
   "es": {
     "launch_path": "/index.html#es",
     "name": "Spanish",
     "description": "Spanish layout",
     "types": ["url", "text"]
   },
   "pt-BR": {
     "launch_path": "/index.html#pt-BR",
     "name": "Portuguese Brazilian",
     "description": "Portuguese Brazilian layout",
     "types": ["url", "text"]
   },
   "pl": {
     "launch_path": "/index.html#pl",
     "name": "Polish",
     "description": "Polish layout",
     "types": ["url", "text"]
   },
   "ca": {
     "launch_path": "/index.html#ca",
     "name": "Catalan",
     "description": "Catalan layout",
     "types": ["url", "text"]
   },
   "cz": {
     "launch_path": "/index.html#cz",
     "name": "Czech",
     "description": "Czech layout",
     "types": ["url", "text"]
   },
   "fr": {
     "launch_path": "/index.html#fr",
     "name": "French",
     "description": "French layout",
     "types": ["url", "text"]
   },
   "de": {
     "launch_path": "/index.html#de",
     "name": "German",
     "description": "German layout",
     "types": ["url", "text"]
   },
   "nb": {
     "launch_path": "/index.html#nb",
     "name": "Norwegian Bokmal",
     "description": "Norwegian Bokmal layout",
     "types": ["url", "text"]
   },
   "sk": {
     "launch_path": "/index.html#sk",
     "name": "Slovak",
     "description": "Slovak layout",
     "types": ["url", "text"]
   },
   "tr-Q": {
     "launch_path": "/index.html#tr-Q",
     "name": "Turkish Q",
     "description": "Turkish Q layout",
     "types": ["url", "text"]
   },
   "tr-F": {
     "launch_path": "/index.html#tr-F",
     "name": "Turkish F",
     "description": "Turkish F layout",
     "types": ["url", "text"]
   },
   "ro": {
     "launch_path": "/index.html#ro",
     "name": "Romanian",
     "description": "Romanian layout",
     "types": ["url", "text"]
   },
   "ru": {
     "launch_path": "/index.html#ru",
     "name": "Russian",
     "description": "Russian layout",
     "types": ["url", "text"]
   },
   "sr-Cyrl": {
     "launch_path": "/index.html#sr-Cyrl",
     "name": "Serbian (Cyrillic)",
     "description": "Serbian (Cyrillic) layout",
     "types": ["url", "text"]
   },
   "sr-Latn": {
     "launch_path": "/index.html#sr-Latn",
     "name": "Serbian (Latin)",
     "description": "Serbian (Latin) layout",
     "types": ["url", "text"]
   },
   "ar": {
     "launch_path": "/index.html#ar",
     "name": "Arabic",
     "description": "Arabic layout",
     "types": ["url", "text"]
   },
   "he": {
     "launch_path": "/index.html#he",
     "name": "Hebrew",
     "description": "Hebrew layout",
     "types": ["url", "text"]
   },
   "hu": {
     "launch_path": "/index.html#hu",
     "name": "Hungarian",
     "description": "Hungarian layout",
     "types": ["url", "text"]
   },
   "el": {
     "launch_path": "/index.html#el",
     "name": "Greek",
     "description": "Greek layout",
     "types": ["url", "text"]
   },
   "zh-Hans-Pinyin": {
     "launch_path": "/index.html#zh-Hans-Pinyin",
     "name": "Pinyin",
     "description": "Pinyin",
     "types": ["url", "text"]
   },
   "number": {
     "launch_path": "/index.html#numberLayout",
     "name": "Number",
     "description": "Number layout",
     "types": ["number"]
   }
 },
 "locales": {
   "en-US": {
     "name": "3rd-party Keyboard",
     "description": "3rd-party Keyboard"
   },
   "zh-TW": {
     "name": "第三方鍵盤",
     "description": "第三方鍵盤"
   }
 },
 "default_locale": "en-US"

}

Layout Matching Algorithm

When an input field is focused, if its type attribute is one of the allowed values stated above, it will be used to filter a set of candidate layouts. A candidate layout means it can handle this input type or is possible to let user input all characters that this input field can accept. For example, if the type of a input is "url", then a layout with "url" or "text" listed in the types of its manifest will be matched. However, if a input field with type "text", then all layouts that support "text" will be matched, but those layouts that only support "url" will not. This is because we believe layouts that can handle "text" could be a fallback for "url" input type, but not vice versa. We also believe "text" could be a fallback for all allowed types stated above.

The matching algorithm of keyboard manager in System app is as follows:

  1. With the given type, find all layouts claims to support the said type and put it into the list.
  2. Next, find layouts claims to support "text" and put it into the list. Layouts do not get duplicated listing even if it supports both types.
  3. Present the user with the choice of the layouts available to handle the input field. The order of presenting list is depend on UX design and/or user preferences in Settings.

Proposed API

The API has made available to privileged apps. See the WebIDL for the current interface.

History of this section

Use cases for each of the methods

  • For a simple virtual keyboard action (send a character and key events w/ each user action), use sendKey(). TODO: should we allow backspace key to be sent from the method? If not, how do send these non-printable characters and it's effect with key events?
    • [yxl] I perfer to allowing non-printable character, such as backspace key, to be sent, if there is no security issue. This would give the IME more flexibility.
  • For spellcheck, autocomplete etc, use surrounding text methods.
  • For cursor moment helper features, use setSelectionRange() and related attributes.
  • For Asian IMEs that sends characters and composition along with the composition events, use setComposition() and endComposition().

It is important to stick with the given use cases because the web application might need to react with what the user actually do. To test the events currently sent to the web, see http://jsfiddle.net/timdream/YDGgk/ .

Examples

The following "snowman filler" Keyboard app will start filling snowman character ("☃") and follow by characters "SNOW" with key events to the input field whenever the user is focus on a input field and switch to the keyboard app.

If the field is a numeric field, it will fill "1337".

var timer;
function startTyping(inputContext) {
  clearTimeout(timer);
  timer = setInterval(function typing() {
    /* [JJ] So I think that this code shouldn't be here, because you'll get lots of clutter
     *      as you'll also have to take languages into account.
     *      Rather rely on entry points in manifest...
     */

    if (inputContext.inputmode === 'numeric' || inputContext.type === 'number') {
      ['1', '3', '3', '7'].forEach(function (k) {
        // For numbers, keyCode is same as the charCode.
        inputContext.sendKey(k.charCodeAt(0), k.charCodeAt(0));
      });
    } else {
      // It's not a good idea to commit text w/o sending events. So we should first send composition events.
      inputContext.setComposition('☃');
      // end the composition and commit the text.
      inputContext.endComposition('☃');
      ['S', 'N', 'O', 'W'].forEach(function (k) {
        // For capital Latin letters, keyCode is same as the charCode.
        inputContext.sendKey(k.charCodeAt(0), k.charCodeAt(0));
      });
  }, 1000);
}

function stopTyping() {
  clearTimeout(timer);
}

var im = navigator.inputMethod;

im.addEventListener('inputcontextchange', function contextchanged(evt) {
  if (evt.inputcontext) {
     // Got a new context, start working with it.
     startTyping(evt.inputcontext);
  } else {
     // The user have removed the focus, we are not allow to type into the text field anymore.
     stopTyping();
  }
});

if (im.inputcontext) {
  // The webpage here is loaded *after* the user has place the focus on the text field,
  // let's start typing now.
  startTyping(im.inputcontext);
}

Related

Android IME API:

http://developer.android.com/guide/topics/text/creating-input-method.html#IMEAPI

iOS Keyboard Management:

http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1

Chrome Extensions API:

http://developer.chrome.com/trunk/extensions/input.ime.html