MozKeyboard.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const Cc = Components.classes;
  6. const Ci = Components.interfaces;
  7. const Cu = Components.utils;
  8. const Cr = Components.results;
  9. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  10. Cu.import("resource://gre/modules/Services.jsm");
  11. Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
  12. XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
  13. "@mozilla.org/childprocessmessagemanager;1", "nsISyncMessageSender");
  14. XPCOMUtils.defineLazyServiceGetter(this, "tm",
  15. "@mozilla.org/thread-manager;1", "nsIThreadManager");
  16. /*
  17. * A WeakMap to map input method iframe window to
  18. * it's active status, kbID, and ipcHelper.
  19. */
  20. var WindowMap = {
  21. // WeakMap of <window, object> pairs.
  22. _map: null,
  23. /*
  24. * Set the object associated to the window and return it.
  25. */
  26. _getObjForWin: function(win) {
  27. if (!this._map) {
  28. this._map = new WeakMap();
  29. }
  30. if (this._map.has(win)) {
  31. return this._map.get(win);
  32. } else {
  33. let obj = {
  34. active: false,
  35. kbID: undefined,
  36. ipcHelper: null
  37. };
  38. this._map.set(win, obj);
  39. return obj;
  40. }
  41. },
  42. /*
  43. * Check if the given window is active.
  44. */
  45. isActive: function(win) {
  46. if (!this._map || !win) {
  47. return false;
  48. }
  49. return this._getObjForWin(win).active;
  50. },
  51. /*
  52. * Set the active status of the given window.
  53. */
  54. setActive: function(win, isActive) {
  55. if (!win) {
  56. return;
  57. }
  58. let obj = this._getObjForWin(win);
  59. obj.active = isActive;
  60. },
  61. /*
  62. * Get the keyboard ID (assigned by Keyboard.jsm) of the given window.
  63. */
  64. getKbID: function(win) {
  65. if (!this._map || !win) {
  66. return undefined;
  67. }
  68. let obj = this._getObjForWin(win);
  69. return obj.kbID;
  70. },
  71. /*
  72. * Set the keyboard ID (assigned by Keyboard.jsm) of the given window.
  73. */
  74. setKbID: function(win, kbID) {
  75. if (!win) {
  76. return;
  77. }
  78. let obj = this._getObjForWin(win);
  79. obj.kbID = kbID;
  80. },
  81. /*
  82. * Get InputContextDOMRequestIpcHelper instance attached to this window.
  83. */
  84. getInputContextIpcHelper: function(win) {
  85. if (!win) {
  86. return;
  87. }
  88. let obj = this._getObjForWin(win);
  89. if (!obj.ipcHelper) {
  90. obj.ipcHelper = new InputContextDOMRequestIpcHelper(win);
  91. }
  92. return obj.ipcHelper;
  93. },
  94. /*
  95. * Unset InputContextDOMRequestIpcHelper instance.
  96. */
  97. unsetInputContextIpcHelper: function(win) {
  98. if (!win) {
  99. return;
  100. }
  101. let obj = this._getObjForWin(win);
  102. if (!obj.ipcHelper) {
  103. return;
  104. }
  105. obj.ipcHelper = null;
  106. }
  107. };
  108. var cpmmSendAsyncMessageWithKbID = function (self, msg, data) {
  109. data.kbID = WindowMap.getKbID(self._window);
  110. cpmm.sendAsyncMessage(msg, data);
  111. };
  112. /**
  113. * ==============================================
  114. * InputMethodManager
  115. * ==============================================
  116. */
  117. function MozInputMethodManager(win) {
  118. this._window = win;
  119. }
  120. MozInputMethodManager.prototype = {
  121. supportsSwitchingForCurrentInputContext: false,
  122. _window: null,
  123. classID: Components.ID("{7e9d7280-ef86-11e2-b778-0800200c9a66}"),
  124. QueryInterface: XPCOMUtils.generateQI([]),
  125. set oninputcontextfocus(handler) {
  126. this.__DOM_IMPL__.setEventHandler("oninputcontextfocus", handler);
  127. },
  128. get oninputcontextfocus() {
  129. return this.__DOM_IMPL__.getEventHandler("oninputcontextfocus");
  130. },
  131. set oninputcontextblur(handler) {
  132. this.__DOM_IMPL__.setEventHandler("oninputcontextblur", handler);
  133. },
  134. get oninputcontextblur() {
  135. return this.__DOM_IMPL__.getEventHandler("oninputcontextblur");
  136. },
  137. set onshowallrequest(handler) {
  138. this.__DOM_IMPL__.setEventHandler("onshowallrequest", handler);
  139. },
  140. get onshowallrequest() {
  141. return this.__DOM_IMPL__.getEventHandler("onshowallrequest");
  142. },
  143. set onnextrequest(handler) {
  144. this.__DOM_IMPL__.setEventHandler("onnextrequest", handler);
  145. },
  146. get onnextrequest() {
  147. return this.__DOM_IMPL__.getEventHandler("onnextrequest");
  148. },
  149. set onaddinputrequest(handler) {
  150. this.__DOM_IMPL__.setEventHandler("onaddinputrequest", handler);
  151. },
  152. get onaddinputrequest() {
  153. return this.__DOM_IMPL__.getEventHandler("onaddinputrequest");
  154. },
  155. set onremoveinputrequest(handler) {
  156. this.__DOM_IMPL__.setEventHandler("onremoveinputrequest", handler);
  157. },
  158. get onremoveinputrequest() {
  159. return this.__DOM_IMPL__.getEventHandler("onremoveinputrequest");
  160. },
  161. showAll: function() {
  162. if (!WindowMap.isActive(this._window)) {
  163. return;
  164. }
  165. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:ShowInputMethodPicker', {});
  166. },
  167. next: function() {
  168. if (!WindowMap.isActive(this._window)) {
  169. return;
  170. }
  171. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SwitchToNextInputMethod', {});
  172. },
  173. supportsSwitching: function() {
  174. if (!WindowMap.isActive(this._window)) {
  175. return false;
  176. }
  177. return this.supportsSwitchingForCurrentInputContext;
  178. },
  179. hide: function() {
  180. if (!WindowMap.isActive(this._window)) {
  181. return;
  182. }
  183. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:RemoveFocus', {});
  184. },
  185. setSupportsSwitchingTypes: function(types) {
  186. cpmm.sendAsyncMessage('System:SetSupportsSwitchingTypes', {
  187. types: types
  188. });
  189. },
  190. handleFocus: function(data) {
  191. let detail = new MozInputContextFocusEventDetail(this._window, data);
  192. let wrappedDetail =
  193. this._window.MozInputContextFocusEventDetail._create(this._window, detail);
  194. let event = new this._window.CustomEvent('inputcontextfocus',
  195. { cancelable: true, detail: wrappedDetail });
  196. let handled = !this.__DOM_IMPL__.dispatchEvent(event);
  197. // A gentle warning if the event is not preventDefault() by the content.
  198. if (!handled) {
  199. dump('MozKeyboard.js: A frame with input-manage permission did not' +
  200. ' handle the inputcontextfocus event dispatched.\n');
  201. }
  202. },
  203. handleBlur: function(data) {
  204. let event =
  205. new this._window.Event('inputcontextblur', { cancelable: true });
  206. let handled = !this.__DOM_IMPL__.dispatchEvent(event);
  207. // A gentle warning if the event is not preventDefault() by the content.
  208. if (!handled) {
  209. dump('MozKeyboard.js: A frame with input-manage permission did not' +
  210. ' handle the inputcontextblur event dispatched.\n');
  211. }
  212. },
  213. dispatchShowAllRequestEvent: function() {
  214. this._fireSimpleEvent('showallrequest');
  215. },
  216. dispatchNextRequestEvent: function() {
  217. this._fireSimpleEvent('nextrequest');
  218. },
  219. _fireSimpleEvent: function(eventType) {
  220. let event = new this._window.Event(eventType);
  221. let handled = !this.__DOM_IMPL__.dispatchEvent(event, { cancelable: true });
  222. // A gentle warning if the event is not preventDefault() by the content.
  223. if (!handled) {
  224. dump('MozKeyboard.js: A frame with input-manage permission did not' +
  225. ' handle the ' + eventType + ' event dispatched.\n');
  226. }
  227. },
  228. handleAddInput: function(data) {
  229. let p = this._fireInputRegistryEvent('addinputrequest', data);
  230. if (!p) {
  231. return;
  232. }
  233. p.then(() => {
  234. cpmm.sendAsyncMessage('System:InputRegistry:Add:Done', {
  235. id: data.id
  236. });
  237. }, (error) => {
  238. cpmm.sendAsyncMessage('System:InputRegistry:Add:Done', {
  239. id: data.id,
  240. error: error || 'Unknown Error'
  241. });
  242. });
  243. },
  244. handleRemoveInput: function(data) {
  245. let p = this._fireInputRegistryEvent('removeinputrequest', data);
  246. if (!p) {
  247. return;
  248. }
  249. p.then(() => {
  250. cpmm.sendAsyncMessage('System:InputRegistry:Remove:Done', {
  251. id: data.id
  252. });
  253. }, (error) => {
  254. cpmm.sendAsyncMessage('System:InputRegistry:Remove:Done', {
  255. id: data.id,
  256. error: error || 'Unknown Error'
  257. });
  258. });
  259. },
  260. _fireInputRegistryEvent: function(eventType, data) {
  261. let detail = new MozInputRegistryEventDetail(this._window, data);
  262. let wrappedDetail =
  263. this._window.MozInputRegistryEventDetail._create(this._window, detail);
  264. let event = new this._window.CustomEvent(eventType,
  265. { cancelable: true, detail: wrappedDetail });
  266. let handled = !this.__DOM_IMPL__.dispatchEvent(event);
  267. // A gentle warning if the event is not preventDefault() by the content.
  268. if (!handled) {
  269. dump('MozKeyboard.js: A frame with input-manage permission did not' +
  270. ' handle the ' + eventType + ' event dispatched.\n');
  271. return null;
  272. }
  273. return detail.takeChainedPromise();
  274. }
  275. };
  276. function MozInputContextFocusEventDetail(win, data) {
  277. this.type = data.type;
  278. this.inputType = data.inputType;
  279. this.value = data.value;
  280. // Exposed as MozInputContextChoicesInfo dictionary defined in WebIDL
  281. this.choices = data.choices;
  282. this.min = data.min;
  283. this.max = data.max;
  284. }
  285. MozInputContextFocusEventDetail.prototype = {
  286. classID: Components.ID("{e0794208-ac50-40e8-b22e-6ee0b4c4e6e8}"),
  287. QueryInterface: XPCOMUtils.generateQI([]),
  288. type: undefined,
  289. inputType: undefined,
  290. value: '',
  291. choices: null,
  292. min: undefined,
  293. max: undefined
  294. };
  295. function MozInputRegistryEventDetail(win, data) {
  296. this._window = win;
  297. this.manifestURL = data.manifestURL;
  298. this.inputId = data.inputId;
  299. // Exposed as MozInputMethodInputManifest dictionary defined in WebIDL
  300. this.inputManifest = data.inputManifest;
  301. this._chainedPromise = Promise.resolve();
  302. }
  303. MozInputRegistryEventDetail.prototype = {
  304. classID: Components.ID("{02130070-9b3e-4f38-bbd9-f0013aa36717}"),
  305. QueryInterface: XPCOMUtils.generateQI([]),
  306. _window: null,
  307. manifestURL: undefined,
  308. inputId: undefined,
  309. inputManifest: null,
  310. waitUntil: function(p) {
  311. // Need an extra protection here since waitUntil will be an no-op
  312. // when chainedPromise is already returned.
  313. if (!this._chainedPromise) {
  314. throw new this._window.DOMException(
  315. 'Must call waitUntil() within the event handling loop.',
  316. 'InvalidStateError');
  317. }
  318. this._chainedPromise = this._chainedPromise
  319. .then(function() { return p; });
  320. },
  321. takeChainedPromise: function() {
  322. var p = this._chainedPromise;
  323. this._chainedPromise = null;
  324. return p;
  325. }
  326. };
  327. /**
  328. * ==============================================
  329. * InputMethod
  330. * ==============================================
  331. */
  332. function MozInputMethod() { }
  333. MozInputMethod.prototype = {
  334. __proto__: DOMRequestIpcHelper.prototype,
  335. _window: null,
  336. _inputcontext: null,
  337. _wrappedInputContext: null,
  338. _mgmt: null,
  339. _wrappedMgmt: null,
  340. _supportsSwitchingTypes: [],
  341. _inputManageId: undefined,
  342. classID: Components.ID("{4607330d-e7d2-40a4-9eb8-43967eae0142}"),
  343. QueryInterface: XPCOMUtils.generateQI([
  344. Ci.nsIDOMGlobalPropertyInitializer,
  345. Ci.nsIObserver,
  346. Ci.nsISupportsWeakReference
  347. ]),
  348. init: function mozInputMethodInit(win) {
  349. this._window = win;
  350. this._mgmt = new MozInputMethodManager(win);
  351. this._wrappedMgmt = win.MozInputMethodManager._create(win, this._mgmt);
  352. this.innerWindowID = win.QueryInterface(Ci.nsIInterfaceRequestor)
  353. .getInterface(Ci.nsIDOMWindowUtils)
  354. .currentInnerWindowID;
  355. Services.obs.addObserver(this, "inner-window-destroyed", false);
  356. cpmm.addWeakMessageListener('Keyboard:Focus', this);
  357. cpmm.addWeakMessageListener('Keyboard:Blur', this);
  358. cpmm.addWeakMessageListener('Keyboard:SelectionChange', this);
  359. cpmm.addWeakMessageListener('Keyboard:GetContext:Result:OK', this);
  360. cpmm.addWeakMessageListener('Keyboard:SupportsSwitchingTypesChange', this);
  361. cpmm.addWeakMessageListener('Keyboard:ReceiveHardwareKeyEvent', this);
  362. cpmm.addWeakMessageListener('InputRegistry:Result:OK', this);
  363. cpmm.addWeakMessageListener('InputRegistry:Result:Error', this);
  364. if (this._hasInputManagePerm(win)) {
  365. this._inputManageId = cpmm.sendSyncMessage('System:RegisterSync', {})[0];
  366. cpmm.addWeakMessageListener('System:Focus', this);
  367. cpmm.addWeakMessageListener('System:Blur', this);
  368. cpmm.addWeakMessageListener('System:ShowAll', this);
  369. cpmm.addWeakMessageListener('System:Next', this);
  370. cpmm.addWeakMessageListener('System:InputRegistry:Add', this);
  371. cpmm.addWeakMessageListener('System:InputRegistry:Remove', this);
  372. }
  373. },
  374. uninit: function mozInputMethodUninit() {
  375. this._window = null;
  376. this._mgmt = null;
  377. this._wrappedMgmt = null;
  378. cpmm.removeWeakMessageListener('Keyboard:Focus', this);
  379. cpmm.removeWeakMessageListener('Keyboard:Blur', this);
  380. cpmm.removeWeakMessageListener('Keyboard:SelectionChange', this);
  381. cpmm.removeWeakMessageListener('Keyboard:GetContext:Result:OK', this);
  382. cpmm.removeWeakMessageListener('Keyboard:SupportsSwitchingTypesChange', this);
  383. cpmm.removeWeakMessageListener('Keyboard:ReceiveHardwareKeyEvent', this);
  384. cpmm.removeWeakMessageListener('InputRegistry:Result:OK', this);
  385. cpmm.removeWeakMessageListener('InputRegistry:Result:Error', this);
  386. this.setActive(false);
  387. if (typeof this._inputManageId === 'number') {
  388. cpmm.sendAsyncMessage('System:Unregister', {
  389. 'id': this._inputManageId
  390. });
  391. cpmm.removeWeakMessageListener('System:Focus', this);
  392. cpmm.removeWeakMessageListener('System:Blur', this);
  393. cpmm.removeWeakMessageListener('System:ShowAll', this);
  394. cpmm.removeWeakMessageListener('System:Next', this);
  395. cpmm.removeWeakMessageListener('System:InputRegistry:Add', this);
  396. cpmm.removeWeakMessageListener('System:InputRegistry:Remove', this);
  397. }
  398. },
  399. receiveMessage: function mozInputMethodReceiveMsg(msg) {
  400. if (msg.name.startsWith('Keyboard') &&
  401. !WindowMap.isActive(this._window)) {
  402. return;
  403. }
  404. let data = msg.data;
  405. if (msg.name.startsWith('System') &&
  406. this._inputManageId !== data.inputManageId) {
  407. return;
  408. }
  409. delete data.inputManageId;
  410. let resolver = ('requestId' in data) ?
  411. this.takePromiseResolver(data.requestId) : null;
  412. switch(msg.name) {
  413. case 'Keyboard:Focus':
  414. // XXX Bug 904339 could receive 'text' event twice
  415. this.setInputContext(data);
  416. break;
  417. case 'Keyboard:Blur':
  418. this.setInputContext(null);
  419. break;
  420. case 'Keyboard:SelectionChange':
  421. if (this.inputcontext) {
  422. this._inputcontext.updateSelectionContext(data, false);
  423. }
  424. break;
  425. case 'Keyboard:GetContext:Result:OK':
  426. this.setInputContext(data);
  427. break;
  428. case 'Keyboard:SupportsSwitchingTypesChange':
  429. this._supportsSwitchingTypes = data.types;
  430. break;
  431. case 'Keyboard:ReceiveHardwareKeyEvent':
  432. if (!Ci.nsIHardwareKeyHandler) {
  433. break;
  434. }
  435. let defaultPrevented = Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;
  436. // |event.preventDefault()| is allowed to be called only when
  437. // |event.cancelable| is true
  438. if (this._inputcontext && data.keyDict.cancelable) {
  439. defaultPrevented |= this._inputcontext.forwardHardwareKeyEvent(data);
  440. }
  441. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:ReplyHardwareKeyEvent', {
  442. type: data.type,
  443. defaultPrevented: defaultPrevented
  444. });
  445. break;
  446. case 'InputRegistry:Result:OK':
  447. resolver.resolve();
  448. break;
  449. case 'InputRegistry:Result:Error':
  450. resolver.reject(data.error);
  451. break;
  452. case 'System:Focus':
  453. this._mgmt.handleFocus(data);
  454. break;
  455. case 'System:Blur':
  456. this._mgmt.handleBlur(data);
  457. break;
  458. case 'System:ShowAll':
  459. this._mgmt.dispatchShowAllRequestEvent();
  460. break;
  461. case 'System:Next':
  462. this._mgmt.dispatchNextRequestEvent();
  463. break;
  464. case 'System:InputRegistry:Add':
  465. this._mgmt.handleAddInput(data);
  466. break;
  467. case 'System:InputRegistry:Remove':
  468. this._mgmt.handleRemoveInput(data);
  469. break;
  470. }
  471. },
  472. observe: function mozInputMethodObserve(subject, topic, data) {
  473. let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
  474. if (wId == this.innerWindowID)
  475. this.uninit();
  476. },
  477. get mgmt() {
  478. return this._wrappedMgmt;
  479. },
  480. get inputcontext() {
  481. if (!WindowMap.isActive(this._window)) {
  482. return null;
  483. }
  484. return this._wrappedInputContext;
  485. },
  486. set oninputcontextchange(handler) {
  487. this.__DOM_IMPL__.setEventHandler("oninputcontextchange", handler);
  488. },
  489. get oninputcontextchange() {
  490. return this.__DOM_IMPL__.getEventHandler("oninputcontextchange");
  491. },
  492. setInputContext: function mozKeyboardContextChange(data) {
  493. if (this._inputcontext) {
  494. this._inputcontext.destroy();
  495. this._inputcontext = null;
  496. this._wrappedInputContext = null;
  497. this._mgmt.supportsSwitchingForCurrentInputContext = false;
  498. }
  499. if (data) {
  500. this._mgmt.supportsSwitchingForCurrentInputContext =
  501. (this._supportsSwitchingTypes.indexOf(data.inputType) !== -1);
  502. this._inputcontext = new MozInputContext(data);
  503. this._inputcontext.init(this._window);
  504. // inputcontext will be exposed as a WebIDL object. Create its
  505. // content-side object explicitly to avoid Bug 1001325.
  506. this._wrappedInputContext =
  507. this._window.MozInputContext._create(this._window, this._inputcontext);
  508. }
  509. let event = new this._window.Event("inputcontextchange");
  510. this.__DOM_IMPL__.dispatchEvent(event);
  511. },
  512. setActive: function mozInputMethodSetActive(isActive) {
  513. if (WindowMap.isActive(this._window) === isActive) {
  514. return;
  515. }
  516. WindowMap.setActive(this._window, isActive);
  517. if (isActive) {
  518. // Activate current input method.
  519. // If there is already an active context, then this will trigger
  520. // a GetContext:Result:OK event, and we can initialize ourselves.
  521. // Otherwise silently ignored.
  522. // get keyboard ID from Keyboard.jsm,
  523. // or if we already have it, get it from our map
  524. // Note: if we need to get it from Keyboard.jsm,
  525. // we have to use a synchronous message
  526. var kbID = WindowMap.getKbID(this._window);
  527. if (kbID) {
  528. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:RegisterSync', {});
  529. } else {
  530. let res = cpmm.sendSyncMessage('Keyboard:RegisterSync', {});
  531. WindowMap.setKbID(this._window, res[0]);
  532. }
  533. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:GetContext', {});
  534. } else {
  535. // Deactive current input method.
  536. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:Unregister', {});
  537. if (this._inputcontext) {
  538. this.setInputContext(null);
  539. }
  540. }
  541. },
  542. addInput: function(inputId, inputManifest) {
  543. return this.createPromiseWithId(function(resolverId) {
  544. let appId = this._window.document.nodePrincipal.appId;
  545. cpmm.sendAsyncMessage('InputRegistry:Add', {
  546. requestId: resolverId,
  547. inputId: inputId,
  548. inputManifest: inputManifest,
  549. appId: appId
  550. });
  551. }.bind(this));
  552. },
  553. removeInput: function(inputId) {
  554. return this.createPromiseWithId(function(resolverId) {
  555. let appId = this._window.document.nodePrincipal.appId;
  556. cpmm.sendAsyncMessage('InputRegistry:Remove', {
  557. requestId: resolverId,
  558. inputId: inputId,
  559. appId: appId
  560. });
  561. }.bind(this));
  562. },
  563. setValue: function(value) {
  564. cpmm.sendAsyncMessage('System:SetValue', {
  565. 'value': value
  566. });
  567. },
  568. setSelectedOption: function(index) {
  569. cpmm.sendAsyncMessage('System:SetSelectedOption', {
  570. 'index': index
  571. });
  572. },
  573. setSelectedOptions: function(indexes) {
  574. cpmm.sendAsyncMessage('System:SetSelectedOptions', {
  575. 'indexes': indexes
  576. });
  577. },
  578. removeFocus: function() {
  579. cpmm.sendAsyncMessage('System:RemoveFocus', {});
  580. },
  581. // Only the system app needs that, so instead of testing a permission which
  582. // is allowed for all chrome:// url, we explicitly test that this is the
  583. // system app's start URL.
  584. _hasInputManagePerm: function(win) {
  585. let url = win.location.href;
  586. let systemAppIndex;
  587. try {
  588. systemAppIndex = Services.prefs.getCharPref('b2g.system_startup_url');
  589. } catch(e) {
  590. dump('MozKeyboard.jsm: no system app startup url set (pref is b2g.system_startup_url)');
  591. }
  592. dump(`MozKeyboard.jsm expecting ${systemAppIndex}\n`);
  593. return url == systemAppIndex;
  594. }
  595. };
  596. /**
  597. * ==============================================
  598. * InputContextDOMRequestIpcHelper
  599. * ==============================================
  600. */
  601. function InputContextDOMRequestIpcHelper(win) {
  602. this.initDOMRequestHelper(win,
  603. ["Keyboard:GetText:Result:OK",
  604. "Keyboard:GetText:Result:Error",
  605. "Keyboard:SetSelectionRange:Result:OK",
  606. "Keyboard:ReplaceSurroundingText:Result:OK",
  607. "Keyboard:SendKey:Result:OK",
  608. "Keyboard:SendKey:Result:Error",
  609. "Keyboard:SetComposition:Result:OK",
  610. "Keyboard:EndComposition:Result:OK",
  611. "Keyboard:SequenceError"]);
  612. }
  613. InputContextDOMRequestIpcHelper.prototype = {
  614. __proto__: DOMRequestIpcHelper.prototype,
  615. _inputContext: null,
  616. attachInputContext: function(inputCtx) {
  617. if (this._inputContext) {
  618. throw new Error("InputContextDOMRequestIpcHelper: detach the context first.");
  619. }
  620. this._inputContext = inputCtx;
  621. },
  622. // Unset ourselves when the window is destroyed.
  623. uninit: function() {
  624. WindowMap.unsetInputContextIpcHelper(this._window);
  625. },
  626. detachInputContext: function() {
  627. // All requests that are still pending need to be invalidated
  628. // because the context is no longer valid.
  629. this.forEachPromiseResolver(k => {
  630. this.takePromiseResolver(k).reject("InputContext got destroyed");
  631. });
  632. this._inputContext = null;
  633. },
  634. receiveMessage: function(msg) {
  635. if (!this._inputContext) {
  636. dump('InputContextDOMRequestIpcHelper received message without context attached.\n');
  637. return;
  638. }
  639. this._inputContext.receiveMessage(msg);
  640. }
  641. };
  642. function MozInputContextSelectionChangeEventDetail(ctx, ownAction) {
  643. this._ctx = ctx;
  644. this.ownAction = ownAction;
  645. }
  646. MozInputContextSelectionChangeEventDetail.prototype = {
  647. classID: Components.ID("ef35443e-a400-4ae3-9170-c2f4e05f7aed"),
  648. QueryInterface: XPCOMUtils.generateQI([]),
  649. ownAction: false,
  650. get selectionStart() {
  651. return this._ctx.selectionStart;
  652. },
  653. get selectionEnd() {
  654. return this._ctx.selectionEnd;
  655. }
  656. };
  657. function MozInputContextSurroundingTextChangeEventDetail(ctx, ownAction) {
  658. this._ctx = ctx;
  659. this.ownAction = ownAction;
  660. }
  661. MozInputContextSurroundingTextChangeEventDetail.prototype = {
  662. classID: Components.ID("1c50fdaf-74af-4b2e-814f-792caf65a168"),
  663. QueryInterface: XPCOMUtils.generateQI([]),
  664. ownAction: false,
  665. get text() {
  666. return this._ctx.text;
  667. },
  668. get textBeforeCursor() {
  669. return this._ctx.textBeforeCursor;
  670. },
  671. get textAfterCursor() {
  672. return this._ctx.textAfterCursor;
  673. }
  674. };
  675. /**
  676. * ==============================================
  677. * HardwareInput
  678. * ==============================================
  679. */
  680. function MozHardwareInput() {
  681. }
  682. MozHardwareInput.prototype = {
  683. classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),
  684. QueryInterface: XPCOMUtils.generateQI([]),
  685. };
  686. /**
  687. * ==============================================
  688. * InputContext
  689. * ==============================================
  690. */
  691. function MozInputContext(data) {
  692. this._context = {
  693. type: data.type,
  694. inputType: data.inputType,
  695. inputMode: data.inputMode,
  696. lang: data.lang,
  697. selectionStart: data.selectionStart,
  698. selectionEnd: data.selectionEnd,
  699. text: data.value
  700. };
  701. this._contextId = data.contextId;
  702. }
  703. MozInputContext.prototype = {
  704. _window: null,
  705. _context: null,
  706. _contextId: -1,
  707. _ipcHelper: null,
  708. _hardwareinput: null,
  709. _wrappedhardwareinput: null,
  710. classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),
  711. QueryInterface: XPCOMUtils.generateQI([
  712. Ci.nsIObserver,
  713. Ci.nsISupportsWeakReference
  714. ]),
  715. init: function ic_init(win) {
  716. this._window = win;
  717. this._ipcHelper = WindowMap.getInputContextIpcHelper(win);
  718. this._ipcHelper.attachInputContext(this);
  719. this._hardwareinput = new MozHardwareInput();
  720. this._wrappedhardwareinput =
  721. this._window.MozHardwareInput._create(this._window, this._hardwareinput);
  722. },
  723. destroy: function ic_destroy() {
  724. // A consuming application might still hold a cached version of
  725. // this object. After destroying all methods will throw because we
  726. // cannot create new promises anymore, but we still hold
  727. // (outdated) information in the context. So let's clear that out.
  728. for (var k in this._context) {
  729. if (this._context.hasOwnProperty(k)) {
  730. this._context[k] = null;
  731. }
  732. }
  733. this._ipcHelper.detachInputContext();
  734. this._ipcHelper = null;
  735. this._window = null;
  736. this._hardwareinput = null;
  737. this._wrappedhardwareinput = null;
  738. },
  739. receiveMessage: function ic_receiveMessage(msg) {
  740. if (!msg || !msg.json) {
  741. dump('InputContext received message without data\n');
  742. return;
  743. }
  744. let json = msg.json;
  745. let resolver = this._ipcHelper.takePromiseResolver(json.requestId);
  746. if (!resolver) {
  747. dump('InputContext received invalid requestId.\n');
  748. return;
  749. }
  750. // Update context first before resolving promise to avoid race condition
  751. if (json.selectioninfo) {
  752. this.updateSelectionContext(json.selectioninfo, true);
  753. }
  754. switch (msg.name) {
  755. case "Keyboard:SendKey:Result:OK":
  756. resolver.resolve(true);
  757. break;
  758. case "Keyboard:SendKey:Result:Error":
  759. resolver.reject(json.error);
  760. break;
  761. case "Keyboard:GetText:Result:OK":
  762. resolver.resolve(json.text);
  763. break;
  764. case "Keyboard:GetText:Result:Error":
  765. resolver.reject(json.error);
  766. break;
  767. case "Keyboard:SetSelectionRange:Result:OK":
  768. case "Keyboard:ReplaceSurroundingText:Result:OK":
  769. resolver.resolve(
  770. Cu.cloneInto(json.selectioninfo, this._window));
  771. break;
  772. case "Keyboard:SequenceError":
  773. // Occurs when a new element got focus, but the inputContext was
  774. // not invalidated yet...
  775. resolver.reject("InputContext has expired");
  776. break;
  777. case "Keyboard:SetComposition:Result:OK": // Fall through.
  778. case "Keyboard:EndComposition:Result:OK":
  779. resolver.resolve(true);
  780. break;
  781. default:
  782. dump("Could not find a handler for " + msg.name);
  783. resolver.reject();
  784. break;
  785. }
  786. },
  787. updateSelectionContext: function ic_updateSelectionContext(data, ownAction) {
  788. if (!this._context) {
  789. return;
  790. }
  791. let selectionDirty =
  792. this._context.selectionStart !== data.selectionStart ||
  793. this._context.selectionEnd !== data.selectionEnd;
  794. let surroundDirty = selectionDirty || data.text !== this._contextId.text;
  795. this._context.text = data.text;
  796. this._context.selectionStart = data.selectionStart;
  797. this._context.selectionEnd = data.selectionEnd;
  798. if (selectionDirty) {
  799. let selectionChangeDetail =
  800. new MozInputContextSelectionChangeEventDetail(this, ownAction);
  801. let wrappedSelectionChangeDetail =
  802. this._window.MozInputContextSelectionChangeEventDetail
  803. ._create(this._window, selectionChangeDetail);
  804. let selectionChangeEvent = new this._window.CustomEvent("selectionchange",
  805. { cancelable: false, detail: wrappedSelectionChangeDetail });
  806. this.__DOM_IMPL__.dispatchEvent(selectionChangeEvent);
  807. }
  808. if (surroundDirty) {
  809. let surroundingTextChangeDetail =
  810. new MozInputContextSurroundingTextChangeEventDetail(this, ownAction);
  811. let wrappedSurroundingTextChangeDetail =
  812. this._window.MozInputContextSurroundingTextChangeEventDetail
  813. ._create(this._window, surroundingTextChangeDetail);
  814. let selectionChangeEvent = new this._window.CustomEvent("surroundingtextchange",
  815. { cancelable: false, detail: wrappedSurroundingTextChangeDetail });
  816. this.__DOM_IMPL__.dispatchEvent(selectionChangeEvent);
  817. }
  818. },
  819. // tag name of the input field
  820. get type() {
  821. return this._context.type;
  822. },
  823. // type of the input field
  824. get inputType() {
  825. return this._context.inputType;
  826. },
  827. get inputMode() {
  828. return this._context.inputMode;
  829. },
  830. get lang() {
  831. return this._context.lang;
  832. },
  833. getText: function ic_getText(offset, length) {
  834. let text;
  835. if (offset && length) {
  836. text = this._context.text.substr(offset, length);
  837. } else if (offset) {
  838. text = this._context.text.substr(offset);
  839. } else {
  840. text = this._context.text;
  841. }
  842. return this._window.Promise.resolve(text);
  843. },
  844. get selectionStart() {
  845. return this._context.selectionStart;
  846. },
  847. get selectionEnd() {
  848. return this._context.selectionEnd;
  849. },
  850. get text() {
  851. return this._context.text;
  852. },
  853. get textBeforeCursor() {
  854. let text = this._context.text;
  855. let start = this._context.selectionStart;
  856. return (start < 100) ?
  857. text.substr(0, start) :
  858. text.substr(start - 100, 100);
  859. },
  860. get textAfterCursor() {
  861. let text = this._context.text;
  862. let start = this._context.selectionStart;
  863. let end = this._context.selectionEnd;
  864. return text.substr(start, end - start + 100);
  865. },
  866. get hardwareinput() {
  867. return this._wrappedhardwareinput;
  868. },
  869. setSelectionRange: function ic_setSelectionRange(start, length) {
  870. let self = this;
  871. return this._sendPromise(function(resolverId) {
  872. cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetSelectionRange', {
  873. contextId: self._contextId,
  874. requestId: resolverId,
  875. selectionStart: start,
  876. selectionEnd: start + length
  877. });
  878. });
  879. },
  880. get onsurroundingtextchange() {
  881. return this.__DOM_IMPL__.getEventHandler("onsurroundingtextchange");
  882. },
  883. set onsurroundingtextchange(handler) {
  884. this.__DOM_IMPL__.setEventHandler("onsurroundingtextchange", handler);
  885. },
  886. get onselectionchange() {
  887. return this.__DOM_IMPL__.getEventHandler("onselectionchange");
  888. },
  889. set onselectionchange(handler) {
  890. this.__DOM_IMPL__.setEventHandler("onselectionchange", handler);
  891. },
  892. replaceSurroundingText: function ic_replaceSurrText(text, offset, length) {
  893. let self = this;
  894. return this._sendPromise(function(resolverId) {
  895. cpmmSendAsyncMessageWithKbID(self, 'Keyboard:ReplaceSurroundingText', {
  896. contextId: self._contextId,
  897. requestId: resolverId,
  898. text: text,
  899. offset: offset || 0,
  900. length: length || 0
  901. });
  902. });
  903. },
  904. deleteSurroundingText: function ic_deleteSurrText(offset, length) {
  905. return this.replaceSurroundingText(null, offset, length);
  906. },
  907. sendKey: function ic_sendKey(dictOrKeyCode, charCode, modifiers, repeat) {
  908. if (typeof dictOrKeyCode === 'number') {
  909. // XXX: modifiers are ignored in this API method.
  910. return this._sendPromise((resolverId) => {
  911. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
  912. contextId: this._contextId,
  913. requestId: resolverId,
  914. method: 'sendKey',
  915. keyCode: dictOrKeyCode,
  916. charCode: charCode,
  917. repeat: repeat
  918. });
  919. });
  920. } else if (typeof dictOrKeyCode === 'object') {
  921. return this._sendPromise((resolverId) => {
  922. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
  923. contextId: this._contextId,
  924. requestId: resolverId,
  925. method: 'sendKey',
  926. keyboardEventDict: this._getkeyboardEventDict(dictOrKeyCode)
  927. });
  928. });
  929. } else {
  930. // XXX: Should not reach here; implies WebIDL binding error.
  931. throw new TypeError('Unknown argument passed.');
  932. }
  933. },
  934. keydown: function ic_keydown(dict) {
  935. return this._sendPromise((resolverId) => {
  936. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
  937. contextId: this._contextId,
  938. requestId: resolverId,
  939. method: 'keydown',
  940. keyboardEventDict: this._getkeyboardEventDict(dict)
  941. });
  942. });
  943. },
  944. keyup: function ic_keyup(dict) {
  945. return this._sendPromise((resolverId) => {
  946. cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
  947. contextId: this._contextId,
  948. requestId: resolverId,
  949. method: 'keyup',
  950. keyboardEventDict: this._getkeyboardEventDict(dict)
  951. });
  952. });
  953. },
  954. setComposition: function ic_setComposition(text, cursor, clauses, dict) {
  955. let self = this;
  956. return this._sendPromise((resolverId) => {
  957. cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetComposition', {
  958. contextId: self._contextId,
  959. requestId: resolverId,
  960. text: text,
  961. cursor: (typeof cursor !== 'undefined') ? cursor : text.length,
  962. clauses: clauses || null,
  963. keyboardEventDict: this._getkeyboardEventDict(dict)
  964. });
  965. });
  966. },
  967. endComposition: function ic_endComposition(text, dict) {
  968. let self = this;
  969. return this._sendPromise((resolverId) => {
  970. cpmmSendAsyncMessageWithKbID(self, 'Keyboard:EndComposition', {
  971. contextId: self._contextId,
  972. requestId: resolverId,
  973. text: text || '',
  974. keyboardEventDict: this._getkeyboardEventDict(dict)
  975. });
  976. });
  977. },
  978. // Generate a new keyboard event by the received keyboard dictionary
  979. // and return defaultPrevented's result of the event after dispatching.
  980. forwardHardwareKeyEvent: function ic_forwardHardwareKeyEvent(data) {
  981. if (!Ci.nsIHardwareKeyHandler) {
  982. return;
  983. }
  984. if (!this._context) {
  985. return Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;
  986. }
  987. let evt = new this._window.KeyboardEvent(data.type,
  988. Cu.cloneInto(data.keyDict,
  989. this._window));
  990. this._hardwareinput.__DOM_IMPL__.dispatchEvent(evt);
  991. return this._getDefaultPreventedValue(evt);
  992. },
  993. _getDefaultPreventedValue: function(evt) {
  994. if (!Ci.nsIHardwareKeyHandler) {
  995. return;
  996. }
  997. let flags = Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;
  998. if (evt.defaultPrevented) {
  999. flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED;
  1000. }
  1001. if (evt.defaultPreventedByChrome) {
  1002. flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED_BY_CHROME;
  1003. }
  1004. if (evt.defaultPreventedByContent) {
  1005. flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED_BY_CONTENT;
  1006. }
  1007. return flags;
  1008. },
  1009. _sendPromise: function(callback) {
  1010. let self = this;
  1011. return this._ipcHelper.createPromiseWithId(function(aResolverId) {
  1012. if (!WindowMap.isActive(self._window)) {
  1013. self._ipcHelper.removePromiseResolver(aResolverId);
  1014. reject('Input method is not active.');
  1015. return;
  1016. }
  1017. callback(aResolverId);
  1018. });
  1019. },
  1020. // Take a MozInputMethodKeyboardEventDict dict, creates a keyboardEventDict
  1021. // object that can be sent to forms.js
  1022. _getkeyboardEventDict: function(dict) {
  1023. if (typeof dict !== 'object' || !dict.key) {
  1024. return;
  1025. }
  1026. var keyboardEventDict = {
  1027. key: dict.key,
  1028. code: dict.code,
  1029. repeat: dict.repeat,
  1030. flags: 0
  1031. };
  1032. if (dict.printable) {
  1033. keyboardEventDict.flags |=
  1034. Ci.nsITextInputProcessor.KEY_FORCE_PRINTABLE_KEY;
  1035. }
  1036. if (/^[a-zA-Z0-9]$/.test(dict.key)) {
  1037. // keyCode must follow the key value in this range;
  1038. // disregard the keyCode from content.
  1039. keyboardEventDict.keyCode = dict.key.toUpperCase().charCodeAt(0);
  1040. } else if (typeof dict.keyCode === 'number') {
  1041. // Allow keyCode to be specified for other key values.
  1042. keyboardEventDict.keyCode = dict.keyCode;
  1043. // Allow keyCode to be explicitly set to zero.
  1044. if (dict.keyCode === 0) {
  1045. keyboardEventDict.flags |=
  1046. Ci.nsITextInputProcessor.KEY_KEEP_KEYCODE_ZERO;
  1047. }
  1048. }
  1049. return keyboardEventDict;
  1050. }
  1051. };
  1052. this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MozInputMethod]);