summaryrefslogtreecommitdiff
path: root/dom/inputmethod/MozKeyboard.js
blob: 3996f3e5d685185560b02e70575793bb0a37741f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cr = Components.results;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/DOMRequestHelper.jsm");

XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
  "@mozilla.org/childprocessmessagemanager;1", "nsISyncMessageSender");

XPCOMUtils.defineLazyServiceGetter(this, "tm",
  "@mozilla.org/thread-manager;1", "nsIThreadManager");

/*
 * A WeakMap to map input method iframe window to
 * it's active status, kbID, and ipcHelper.
 */
var WindowMap = {
  // WeakMap of <window, object> pairs.
  _map: null,

  /*
   * Set the object associated to the window and return it.
   */
  _getObjForWin: function(win) {
    if (!this._map) {
      this._map = new WeakMap();
    }
    if (this._map.has(win)) {
      return this._map.get(win);
    } else {
      let obj = {
        active: false,
        kbID: undefined,
        ipcHelper: null
      };
      this._map.set(win, obj);

      return obj;
    }
  },

  /*
   * Check if the given window is active.
   */
  isActive: function(win) {
    if (!this._map || !win) {
      return false;
    }

    return this._getObjForWin(win).active;
  },

  /*
   * Set the active status of the given window.
   */
  setActive: function(win, isActive) {
    if (!win) {
      return;
    }
    let obj = this._getObjForWin(win);
    obj.active = isActive;
  },

  /*
   * Get the keyboard ID (assigned by Keyboard.jsm) of the given window.
   */
  getKbID: function(win) {
    if (!this._map || !win) {
      return undefined;
    }

    let obj = this._getObjForWin(win);
    return obj.kbID;
  },

  /*
   * Set the keyboard ID (assigned by Keyboard.jsm) of the given window.
   */
  setKbID: function(win, kbID) {
    if (!win) {
      return;
    }
    let obj = this._getObjForWin(win);
    obj.kbID = kbID;
  },

  /*
   * Get InputContextDOMRequestIpcHelper instance attached to this window.
   */
  getInputContextIpcHelper: function(win) {
    if (!win) {
      return;
    }
    let obj = this._getObjForWin(win);
    if (!obj.ipcHelper) {
      obj.ipcHelper = new InputContextDOMRequestIpcHelper(win);
    }
    return obj.ipcHelper;
  },

  /*
   * Unset InputContextDOMRequestIpcHelper instance.
   */
  unsetInputContextIpcHelper: function(win) {
    if (!win) {
      return;
    }
    let obj = this._getObjForWin(win);
    if (!obj.ipcHelper) {
      return;
    }
    obj.ipcHelper = null;
  }
};

var cpmmSendAsyncMessageWithKbID = function (self, msg, data) {
  data.kbID = WindowMap.getKbID(self._window);
  cpmm.sendAsyncMessage(msg, data);
};

/**
 * ==============================================
 * InputMethodManager
 * ==============================================
 */
function MozInputMethodManager(win) {
  this._window = win;
}

MozInputMethodManager.prototype = {
  supportsSwitchingForCurrentInputContext: false,
  _window: null,

  classID: Components.ID("{7e9d7280-ef86-11e2-b778-0800200c9a66}"),

  QueryInterface: XPCOMUtils.generateQI([]),

  set oninputcontextfocus(handler) {
    this.__DOM_IMPL__.setEventHandler("oninputcontextfocus", handler);
  },

  get oninputcontextfocus() {
    return this.__DOM_IMPL__.getEventHandler("oninputcontextfocus");
  },

  set oninputcontextblur(handler) {
    this.__DOM_IMPL__.setEventHandler("oninputcontextblur", handler);
  },

  get oninputcontextblur() {
    return this.__DOM_IMPL__.getEventHandler("oninputcontextblur");
  },

  set onshowallrequest(handler) {
    this.__DOM_IMPL__.setEventHandler("onshowallrequest", handler);
  },

  get onshowallrequest() {
    return this.__DOM_IMPL__.getEventHandler("onshowallrequest");
  },

  set onnextrequest(handler) {
    this.__DOM_IMPL__.setEventHandler("onnextrequest", handler);
  },

  get onnextrequest() {
    return this.__DOM_IMPL__.getEventHandler("onnextrequest");
  },

  set onaddinputrequest(handler) {
    this.__DOM_IMPL__.setEventHandler("onaddinputrequest", handler);
  },

  get onaddinputrequest() {
    return this.__DOM_IMPL__.getEventHandler("onaddinputrequest");
  },

  set onremoveinputrequest(handler) {
    this.__DOM_IMPL__.setEventHandler("onremoveinputrequest", handler);
  },

  get onremoveinputrequest() {
    return this.__DOM_IMPL__.getEventHandler("onremoveinputrequest");
  },

  showAll: function() {
    if (!WindowMap.isActive(this._window)) {
      return;
    }
    cpmmSendAsyncMessageWithKbID(this, 'Keyboard:ShowInputMethodPicker', {});
  },

  next: function() {
    if (!WindowMap.isActive(this._window)) {
      return;
    }
    cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SwitchToNextInputMethod', {});
  },

  supportsSwitching: function() {
    if (!WindowMap.isActive(this._window)) {
      return false;
    }
    return this.supportsSwitchingForCurrentInputContext;
  },

  hide: function() {
    if (!WindowMap.isActive(this._window)) {
      return;
    }
    cpmmSendAsyncMessageWithKbID(this, 'Keyboard:RemoveFocus', {});
  },

  setSupportsSwitchingTypes: function(types) {
    cpmm.sendAsyncMessage('System:SetSupportsSwitchingTypes', {
      types: types
    });
  },

  handleFocus: function(data) {
    let detail = new MozInputContextFocusEventDetail(this._window, data);
    let wrappedDetail =
      this._window.MozInputContextFocusEventDetail._create(this._window, detail);
    let event = new this._window.CustomEvent('inputcontextfocus',
      { cancelable: true, detail: wrappedDetail });

    let handled = !this.__DOM_IMPL__.dispatchEvent(event);

    // A gentle warning if the event is not preventDefault() by the content.
    if (!handled) {
      dump('MozKeyboard.js: A frame with input-manage permission did not' +
        ' handle the inputcontextfocus event dispatched.\n');
    }
  },

  handleBlur: function(data) {
    let event =
      new this._window.Event('inputcontextblur', { cancelable: true });

    let handled = !this.__DOM_IMPL__.dispatchEvent(event);

    // A gentle warning if the event is not preventDefault() by the content.
    if (!handled) {
      dump('MozKeyboard.js: A frame with input-manage permission did not' +
        ' handle the inputcontextblur event dispatched.\n');
    }
  },

  dispatchShowAllRequestEvent: function() {
    this._fireSimpleEvent('showallrequest');
  },

  dispatchNextRequestEvent: function() {
    this._fireSimpleEvent('nextrequest');
  },

  _fireSimpleEvent: function(eventType) {
    let event = new this._window.Event(eventType);
    let handled = !this.__DOM_IMPL__.dispatchEvent(event, { cancelable: true });

    // A gentle warning if the event is not preventDefault() by the content.
    if (!handled) {
      dump('MozKeyboard.js: A frame with input-manage permission did not' +
        ' handle the ' + eventType + ' event dispatched.\n');
    }
  },

  handleAddInput: function(data) {
    let p = this._fireInputRegistryEvent('addinputrequest', data);
    if (!p) {
      return;
    }

    p.then(() => {
      cpmm.sendAsyncMessage('System:InputRegistry:Add:Done', {
        id: data.id
      });
    }, (error) => {
      cpmm.sendAsyncMessage('System:InputRegistry:Add:Done', {
        id: data.id,
        error: error || 'Unknown Error'
      });
    });
  },

  handleRemoveInput: function(data) {
    let p = this._fireInputRegistryEvent('removeinputrequest', data);
    if (!p) {
      return;
    }

    p.then(() => {
      cpmm.sendAsyncMessage('System:InputRegistry:Remove:Done', {
        id: data.id
      });
    }, (error) => {
      cpmm.sendAsyncMessage('System:InputRegistry:Remove:Done', {
        id: data.id,
        error: error || 'Unknown Error'
      });
    });
  },

  _fireInputRegistryEvent: function(eventType, data) {
    let detail = new MozInputRegistryEventDetail(this._window, data);
    let wrappedDetail =
      this._window.MozInputRegistryEventDetail._create(this._window, detail);
    let event = new this._window.CustomEvent(eventType,
      { cancelable: true, detail: wrappedDetail });
    let handled = !this.__DOM_IMPL__.dispatchEvent(event);

    // A gentle warning if the event is not preventDefault() by the content.
    if (!handled) {
      dump('MozKeyboard.js: A frame with input-manage permission did not' +
        ' handle the ' + eventType + ' event dispatched.\n');

      return null;
    }
    return detail.takeChainedPromise();
  }
};

function MozInputContextFocusEventDetail(win, data) {
  this.type = data.type;
  this.inputType = data.inputType;
  this.value = data.value;
  // Exposed as MozInputContextChoicesInfo dictionary defined in WebIDL
  this.choices = data.choices;
  this.min = data.min;
  this.max = data.max;
}
MozInputContextFocusEventDetail.prototype = {
  classID: Components.ID("{e0794208-ac50-40e8-b22e-6ee0b4c4e6e8}"),
  QueryInterface: XPCOMUtils.generateQI([]),

  type: undefined,
  inputType: undefined,
  value: '',
  choices: null,
  min: undefined,
  max: undefined
};

function MozInputRegistryEventDetail(win, data) {
  this._window = win;

  this.manifestURL = data.manifestURL;
  this.inputId = data.inputId;
  // Exposed as MozInputMethodInputManifest dictionary defined in WebIDL
  this.inputManifest = data.inputManifest;

  this._chainedPromise = Promise.resolve();
}
MozInputRegistryEventDetail.prototype = {
  classID: Components.ID("{02130070-9b3e-4f38-bbd9-f0013aa36717}"),
  QueryInterface: XPCOMUtils.generateQI([]),

  _window: null,

  manifestURL: undefined,
  inputId: undefined,
  inputManifest: null,

  waitUntil: function(p) {
    // Need an extra protection here since waitUntil will be an no-op
    // when chainedPromise is already returned.
    if (!this._chainedPromise) {
      throw new this._window.DOMException(
        'Must call waitUntil() within the event handling loop.',
        'InvalidStateError');
    }

    this._chainedPromise = this._chainedPromise
      .then(function() { return p; });
  },

  takeChainedPromise: function() {
    var p = this._chainedPromise;
    this._chainedPromise = null;
    return p;
  }
};

/**
 * ==============================================
 * InputMethod
 * ==============================================
 */
function MozInputMethod() { }

MozInputMethod.prototype = {
  __proto__: DOMRequestIpcHelper.prototype,

  _window: null,
  _inputcontext: null,
  _wrappedInputContext: null,
  _mgmt: null,
  _wrappedMgmt: null,
  _supportsSwitchingTypes: [],
  _inputManageId: undefined,

  classID: Components.ID("{4607330d-e7d2-40a4-9eb8-43967eae0142}"),

  QueryInterface: XPCOMUtils.generateQI([
    Ci.nsIDOMGlobalPropertyInitializer,
    Ci.nsIObserver,
    Ci.nsISupportsWeakReference
  ]),

  init: function mozInputMethodInit(win) {
    this._window = win;
    this._mgmt = new MozInputMethodManager(win);
    this._wrappedMgmt = win.MozInputMethodManager._create(win, this._mgmt);
    this.innerWindowID = win.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils)
                            .currentInnerWindowID;

    Services.obs.addObserver(this, "inner-window-destroyed", false);

    cpmm.addWeakMessageListener('Keyboard:Focus', this);
    cpmm.addWeakMessageListener('Keyboard:Blur', this);
    cpmm.addWeakMessageListener('Keyboard:SelectionChange', this);
    cpmm.addWeakMessageListener('Keyboard:GetContext:Result:OK', this);
    cpmm.addWeakMessageListener('Keyboard:SupportsSwitchingTypesChange', this);
    cpmm.addWeakMessageListener('Keyboard:ReceiveHardwareKeyEvent', this);
    cpmm.addWeakMessageListener('InputRegistry:Result:OK', this);
    cpmm.addWeakMessageListener('InputRegistry:Result:Error', this);

    if (this._hasInputManagePerm(win)) {
      this._inputManageId = cpmm.sendSyncMessage('System:RegisterSync', {})[0];
      cpmm.addWeakMessageListener('System:Focus', this);
      cpmm.addWeakMessageListener('System:Blur', this);
      cpmm.addWeakMessageListener('System:ShowAll', this);
      cpmm.addWeakMessageListener('System:Next', this);
      cpmm.addWeakMessageListener('System:InputRegistry:Add', this);
      cpmm.addWeakMessageListener('System:InputRegistry:Remove', this);
    }
  },

  uninit: function mozInputMethodUninit() {
    this._window = null;
    this._mgmt = null;
    this._wrappedMgmt = null;

    cpmm.removeWeakMessageListener('Keyboard:Focus', this);
    cpmm.removeWeakMessageListener('Keyboard:Blur', this);
    cpmm.removeWeakMessageListener('Keyboard:SelectionChange', this);
    cpmm.removeWeakMessageListener('Keyboard:GetContext:Result:OK', this);
    cpmm.removeWeakMessageListener('Keyboard:SupportsSwitchingTypesChange', this);
    cpmm.removeWeakMessageListener('Keyboard:ReceiveHardwareKeyEvent', this);
    cpmm.removeWeakMessageListener('InputRegistry:Result:OK', this);
    cpmm.removeWeakMessageListener('InputRegistry:Result:Error', this);
    this.setActive(false);

    if (typeof this._inputManageId === 'number') {
      cpmm.sendAsyncMessage('System:Unregister', {
        'id': this._inputManageId
      });
      cpmm.removeWeakMessageListener('System:Focus', this);
      cpmm.removeWeakMessageListener('System:Blur', this);
      cpmm.removeWeakMessageListener('System:ShowAll', this);
      cpmm.removeWeakMessageListener('System:Next', this);
      cpmm.removeWeakMessageListener('System:InputRegistry:Add', this);
      cpmm.removeWeakMessageListener('System:InputRegistry:Remove', this);
    }
  },

  receiveMessage: function mozInputMethodReceiveMsg(msg) {
    if (msg.name.startsWith('Keyboard') &&
        !WindowMap.isActive(this._window)) {
      return;
    }

    let data = msg.data;

    if (msg.name.startsWith('System') &&
      this._inputManageId !== data.inputManageId) {
      return;
    }
    delete data.inputManageId;

    let resolver = ('requestId' in data) ?
      this.takePromiseResolver(data.requestId) : null;

    switch(msg.name) {
      case 'Keyboard:Focus':
        // XXX Bug 904339 could receive 'text' event twice
        this.setInputContext(data);
        break;
      case 'Keyboard:Blur':
        this.setInputContext(null);
        break;
      case 'Keyboard:SelectionChange':
        if (this.inputcontext) {
          this._inputcontext.updateSelectionContext(data, false);
        }
        break;
      case 'Keyboard:GetContext:Result:OK':
        this.setInputContext(data);
        break;
      case 'Keyboard:SupportsSwitchingTypesChange':
        this._supportsSwitchingTypes = data.types;
        break;
      case 'Keyboard:ReceiveHardwareKeyEvent':
        if (!Ci.nsIHardwareKeyHandler) {
          break;
        }

        let defaultPrevented = Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;

        // |event.preventDefault()| is allowed to be called only when
        // |event.cancelable| is true
        if (this._inputcontext && data.keyDict.cancelable) {
          defaultPrevented |= this._inputcontext.forwardHardwareKeyEvent(data);
        }

        cpmmSendAsyncMessageWithKbID(this, 'Keyboard:ReplyHardwareKeyEvent', {
                                       type: data.type,
                                       defaultPrevented: defaultPrevented
                                     });
        break;
      case 'InputRegistry:Result:OK':
        resolver.resolve();

        break;

      case 'InputRegistry:Result:Error':
        resolver.reject(data.error);

        break;

      case 'System:Focus':
        this._mgmt.handleFocus(data);
        break;

      case 'System:Blur':
        this._mgmt.handleBlur(data);
        break;

      case 'System:ShowAll':
        this._mgmt.dispatchShowAllRequestEvent();
        break;

      case 'System:Next':
        this._mgmt.dispatchNextRequestEvent();
        break;

      case 'System:InputRegistry:Add':
        this._mgmt.handleAddInput(data);
        break;

      case 'System:InputRegistry:Remove':
        this._mgmt.handleRemoveInput(data);
        break;
    }
  },

  observe: function mozInputMethodObserve(subject, topic, data) {
    let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
    if (wId == this.innerWindowID)
      this.uninit();
  },

  get mgmt() {
    return this._wrappedMgmt;
  },

  get inputcontext() {
    if (!WindowMap.isActive(this._window)) {
      return null;
    }
    return this._wrappedInputContext;
  },

  set oninputcontextchange(handler) {
    this.__DOM_IMPL__.setEventHandler("oninputcontextchange", handler);
  },

  get oninputcontextchange() {
    return this.__DOM_IMPL__.getEventHandler("oninputcontextchange");
  },

  setInputContext: function mozKeyboardContextChange(data) {
    if (this._inputcontext) {
      this._inputcontext.destroy();
      this._inputcontext = null;
      this._wrappedInputContext = null;
      this._mgmt.supportsSwitchingForCurrentInputContext = false;
    }

    if (data) {
      this._mgmt.supportsSwitchingForCurrentInputContext =
        (this._supportsSwitchingTypes.indexOf(data.inputType) !== -1);

      this._inputcontext = new MozInputContext(data);
      this._inputcontext.init(this._window);
      // inputcontext will be exposed as a WebIDL object. Create its
      // content-side object explicitly to avoid Bug 1001325.
      this._wrappedInputContext =
        this._window.MozInputContext._create(this._window, this._inputcontext);
    }

    let event = new this._window.Event("inputcontextchange");
    this.__DOM_IMPL__.dispatchEvent(event);
  },

  setActive: function mozInputMethodSetActive(isActive) {
    if (WindowMap.isActive(this._window) === isActive) {
      return;
    }

    WindowMap.setActive(this._window, isActive);

    if (isActive) {
      // Activate current input method.
      // If there is already an active context, then this will trigger
      // a GetContext:Result:OK event, and we can initialize ourselves.
      // Otherwise silently ignored.

      // get keyboard ID from Keyboard.jsm,
      // or if we already have it, get it from our map
      // Note: if we need to get it from Keyboard.jsm,
      // we have to use a synchronous message
      var kbID = WindowMap.getKbID(this._window);
      if (kbID) {
        cpmmSendAsyncMessageWithKbID(this, 'Keyboard:RegisterSync', {});
      } else {
        let res = cpmm.sendSyncMessage('Keyboard:RegisterSync', {});
        WindowMap.setKbID(this._window, res[0]);
      }

      cpmmSendAsyncMessageWithKbID(this, 'Keyboard:GetContext', {});
    } else {
      // Deactive current input method.
      cpmmSendAsyncMessageWithKbID(this, 'Keyboard:Unregister', {});
      if (this._inputcontext) {
        this.setInputContext(null);
      }
    }
  },

  addInput: function(inputId, inputManifest) {
    return this.createPromiseWithId(function(resolverId) {
      let appId = this._window.document.nodePrincipal.appId;

      cpmm.sendAsyncMessage('InputRegistry:Add', {
        requestId: resolverId,
        inputId: inputId,
        inputManifest: inputManifest,
        appId: appId
      });
    }.bind(this));
  },

  removeInput: function(inputId) {
    return this.createPromiseWithId(function(resolverId) {
      let appId = this._window.document.nodePrincipal.appId;

      cpmm.sendAsyncMessage('InputRegistry:Remove', {
        requestId: resolverId,
        inputId: inputId,
        appId: appId
      });
    }.bind(this));
  },

  setValue: function(value) {
    cpmm.sendAsyncMessage('System:SetValue', {
      'value': value
    });
  },

  setSelectedOption: function(index) {
    cpmm.sendAsyncMessage('System:SetSelectedOption', {
      'index': index
    });
  },

  setSelectedOptions: function(indexes) {
    cpmm.sendAsyncMessage('System:SetSelectedOptions', {
      'indexes': indexes
    });
  },

  removeFocus: function() {
    cpmm.sendAsyncMessage('System:RemoveFocus', {});
  },

  // Only the system app needs that, so instead of testing a permission which
  // is allowed for all chrome:// url, we explicitly test that this is the
  // system app's start URL.
  _hasInputManagePerm: function(win) {
    let url = win.location.href;
    let systemAppIndex;
    try {
      systemAppIndex = Services.prefs.getCharPref('b2g.system_startup_url');
    } catch(e) {
      dump('MozKeyboard.jsm: no system app startup url set (pref is b2g.system_startup_url)');
    }

    dump(`MozKeyboard.jsm expecting ${systemAppIndex}\n`);
    return url == systemAppIndex;
  }
};

/**
 * ==============================================
 * InputContextDOMRequestIpcHelper
 * ==============================================
 */
function InputContextDOMRequestIpcHelper(win) {
  this.initDOMRequestHelper(win,
    ["Keyboard:GetText:Result:OK",
     "Keyboard:GetText:Result:Error",
     "Keyboard:SetSelectionRange:Result:OK",
     "Keyboard:ReplaceSurroundingText:Result:OK",
     "Keyboard:SendKey:Result:OK",
     "Keyboard:SendKey:Result:Error",
     "Keyboard:SetComposition:Result:OK",
     "Keyboard:EndComposition:Result:OK",
     "Keyboard:SequenceError"]);
}

InputContextDOMRequestIpcHelper.prototype = {
  __proto__: DOMRequestIpcHelper.prototype,
  _inputContext: null,

  attachInputContext: function(inputCtx) {
    if (this._inputContext) {
      throw new Error("InputContextDOMRequestIpcHelper: detach the context first.");
    }

    this._inputContext = inputCtx;
  },

  // Unset ourselves when the window is destroyed.
  uninit: function() {
    WindowMap.unsetInputContextIpcHelper(this._window);
  },

  detachInputContext: function() {
    // All requests that are still pending need to be invalidated
    // because the context is no longer valid.
    this.forEachPromiseResolver(k => {
      this.takePromiseResolver(k).reject("InputContext got destroyed");
    });

    this._inputContext = null;
  },

  receiveMessage: function(msg) {
    if (!this._inputContext) {
      dump('InputContextDOMRequestIpcHelper received message without context attached.\n');
      return;
    }

    this._inputContext.receiveMessage(msg);
  }
};

function MozInputContextSelectionChangeEventDetail(ctx, ownAction) {
  this._ctx = ctx;
  this.ownAction = ownAction;
}

MozInputContextSelectionChangeEventDetail.prototype = {
  classID: Components.ID("ef35443e-a400-4ae3-9170-c2f4e05f7aed"),
  QueryInterface: XPCOMUtils.generateQI([]),

  ownAction: false,

  get selectionStart() {
    return this._ctx.selectionStart;
  },

  get selectionEnd() {
    return this._ctx.selectionEnd;
  }
};

function MozInputContextSurroundingTextChangeEventDetail(ctx, ownAction) {
  this._ctx = ctx;
  this.ownAction = ownAction;
}

MozInputContextSurroundingTextChangeEventDetail.prototype = {
  classID: Components.ID("1c50fdaf-74af-4b2e-814f-792caf65a168"),
  QueryInterface: XPCOMUtils.generateQI([]),

  ownAction: false,

  get text() {
    return this._ctx.text;
  },

  get textBeforeCursor() {
    return this._ctx.textBeforeCursor;
  },

  get textAfterCursor() {
    return this._ctx.textAfterCursor;
  }
};

/**
 * ==============================================
 * HardwareInput
 * ==============================================
 */
function MozHardwareInput() {
}

MozHardwareInput.prototype = {
  classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),
  QueryInterface: XPCOMUtils.generateQI([]),
};

/**
 * ==============================================
 * InputContext
 * ==============================================
 */
function MozInputContext(data) {
  this._context = {
    type: data.type,
    inputType: data.inputType,
    inputMode: data.inputMode,
    lang: data.lang,
    selectionStart: data.selectionStart,
    selectionEnd: data.selectionEnd,
    text: data.value
  };

  this._contextId = data.contextId;
}

MozInputContext.prototype = {
  _window: null,
  _context: null,
  _contextId: -1,
  _ipcHelper: null,
  _hardwareinput: null,
  _wrappedhardwareinput: null,

  classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),

  QueryInterface: XPCOMUtils.generateQI([
    Ci.nsIObserver,
    Ci.nsISupportsWeakReference
  ]),

  init: function ic_init(win) {
    this._window = win;

    this._ipcHelper = WindowMap.getInputContextIpcHelper(win);
    this._ipcHelper.attachInputContext(this);
    this._hardwareinput = new MozHardwareInput();
    this._wrappedhardwareinput =
      this._window.MozHardwareInput._create(this._window, this._hardwareinput);
  },

  destroy: function ic_destroy() {
    // A consuming application might still hold a cached version of
    // this object. After destroying all methods will throw because we
    // cannot create new promises anymore, but we still hold
    // (outdated) information in the context. So let's clear that out.
    for (var k in this._context) {
      if (this._context.hasOwnProperty(k)) {
        this._context[k] = null;
      }
    }

    this._ipcHelper.detachInputContext();
    this._ipcHelper = null;

    this._window = null;
    this._hardwareinput = null;
    this._wrappedhardwareinput = null;
  },

  receiveMessage: function ic_receiveMessage(msg) {
    if (!msg || !msg.json) {
      dump('InputContext received message without data\n');
      return;
    }

    let json = msg.json;
    let resolver = this._ipcHelper.takePromiseResolver(json.requestId);

    if (!resolver) {
      dump('InputContext received invalid requestId.\n');
      return;
    }

    // Update context first before resolving promise to avoid race condition
    if (json.selectioninfo) {
      this.updateSelectionContext(json.selectioninfo, true);
    }

    switch (msg.name) {
      case "Keyboard:SendKey:Result:OK":
        resolver.resolve(true);
        break;
      case "Keyboard:SendKey:Result:Error":
        resolver.reject(json.error);
        break;
      case "Keyboard:GetText:Result:OK":
        resolver.resolve(json.text);
        break;
      case "Keyboard:GetText:Result:Error":
        resolver.reject(json.error);
        break;
      case "Keyboard:SetSelectionRange:Result:OK":
      case "Keyboard:ReplaceSurroundingText:Result:OK":
        resolver.resolve(
          Cu.cloneInto(json.selectioninfo, this._window));
        break;
      case "Keyboard:SequenceError":
        // Occurs when a new element got focus, but the inputContext was
        // not invalidated yet...
        resolver.reject("InputContext has expired");
        break;
      case "Keyboard:SetComposition:Result:OK": // Fall through.
      case "Keyboard:EndComposition:Result:OK":
        resolver.resolve(true);
        break;
      default:
        dump("Could not find a handler for " + msg.name);
        resolver.reject();
        break;
    }
  },

  updateSelectionContext: function ic_updateSelectionContext(data, ownAction) {
    if (!this._context) {
      return;
    }

    let selectionDirty =
      this._context.selectionStart !== data.selectionStart ||
      this._context.selectionEnd !== data.selectionEnd;
    let surroundDirty = selectionDirty || data.text !== this._contextId.text;

    this._context.text = data.text;
    this._context.selectionStart = data.selectionStart;
    this._context.selectionEnd = data.selectionEnd;

    if (selectionDirty) {
      let selectionChangeDetail =
        new MozInputContextSelectionChangeEventDetail(this, ownAction);
      let wrappedSelectionChangeDetail =
        this._window.MozInputContextSelectionChangeEventDetail
          ._create(this._window, selectionChangeDetail);
      let selectionChangeEvent = new this._window.CustomEvent("selectionchange",
        { cancelable: false, detail: wrappedSelectionChangeDetail });

      this.__DOM_IMPL__.dispatchEvent(selectionChangeEvent);
    }

    if (surroundDirty) {
      let surroundingTextChangeDetail =
        new MozInputContextSurroundingTextChangeEventDetail(this, ownAction);
      let wrappedSurroundingTextChangeDetail =
        this._window.MozInputContextSurroundingTextChangeEventDetail
          ._create(this._window, surroundingTextChangeDetail);
      let selectionChangeEvent = new this._window.CustomEvent("surroundingtextchange",
        { cancelable: false, detail: wrappedSurroundingTextChangeDetail });

      this.__DOM_IMPL__.dispatchEvent(selectionChangeEvent);
    }
  },

  // tag name of the input field
  get type() {
    return this._context.type;
  },

  // type of the input field
  get inputType() {
    return this._context.inputType;
  },

  get inputMode() {
    return this._context.inputMode;
  },

  get lang() {
    return this._context.lang;
  },

  getText: function ic_getText(offset, length) {
    let text;
    if (offset && length) {
      text = this._context.text.substr(offset, length);
    } else if (offset) {
      text = this._context.text.substr(offset);
    } else {
      text = this._context.text;
    }

    return this._window.Promise.resolve(text);
  },

  get selectionStart() {
    return this._context.selectionStart;
  },

  get selectionEnd() {
    return this._context.selectionEnd;
  },

  get text() {
    return this._context.text;
  },

  get textBeforeCursor() {
    let text = this._context.text;
    let start = this._context.selectionStart;
    return (start < 100) ?
      text.substr(0, start) :
      text.substr(start - 100, 100);
  },

  get textAfterCursor() {
    let text = this._context.text;
    let start = this._context.selectionStart;
    let end = this._context.selectionEnd;
    return text.substr(start, end - start + 100);
  },

  get hardwareinput() {
    return this._wrappedhardwareinput;
  },

  setSelectionRange: function ic_setSelectionRange(start, length) {
    let self = this;
    return this._sendPromise(function(resolverId) {
      cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetSelectionRange', {
        contextId: self._contextId,
        requestId: resolverId,
        selectionStart: start,
        selectionEnd: start + length
      });
    });
  },

  get onsurroundingtextchange() {
    return this.__DOM_IMPL__.getEventHandler("onsurroundingtextchange");
  },

  set onsurroundingtextchange(handler) {
    this.__DOM_IMPL__.setEventHandler("onsurroundingtextchange", handler);
  },

  get onselectionchange() {
    return this.__DOM_IMPL__.getEventHandler("onselectionchange");
  },

  set onselectionchange(handler) {
    this.__DOM_IMPL__.setEventHandler("onselectionchange", handler);
  },

  replaceSurroundingText: function ic_replaceSurrText(text, offset, length) {
    let self = this;
    return this._sendPromise(function(resolverId) {
      cpmmSendAsyncMessageWithKbID(self, 'Keyboard:ReplaceSurroundingText', {
        contextId: self._contextId,
        requestId: resolverId,
        text: text,
        offset: offset || 0,
        length: length || 0
      });
    });
  },

  deleteSurroundingText: function ic_deleteSurrText(offset, length) {
    return this.replaceSurroundingText(null, offset, length);
  },

  sendKey: function ic_sendKey(dictOrKeyCode, charCode, modifiers, repeat) {
    if (typeof dictOrKeyCode === 'number') {
      // XXX: modifiers are ignored in this API method.

      return this._sendPromise((resolverId) => {
        cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
          contextId: this._contextId,
          requestId: resolverId,
          method: 'sendKey',
          keyCode: dictOrKeyCode,
          charCode: charCode,
          repeat: repeat
        });
      });
    } else if (typeof dictOrKeyCode === 'object') {
      return this._sendPromise((resolverId) => {
        cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
          contextId: this._contextId,
          requestId: resolverId,
          method: 'sendKey',
          keyboardEventDict: this._getkeyboardEventDict(dictOrKeyCode)
        });
      });
    } else {
      // XXX: Should not reach here; implies WebIDL binding error.
      throw new TypeError('Unknown argument passed.');
    }
  },

  keydown: function ic_keydown(dict) {
    return this._sendPromise((resolverId) => {
      cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
        contextId: this._contextId,
         requestId: resolverId,
        method: 'keydown',
        keyboardEventDict: this._getkeyboardEventDict(dict)
       });
     });
   },

  keyup: function ic_keyup(dict) {
    return this._sendPromise((resolverId) => {
      cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
        contextId: this._contextId,
        requestId: resolverId,
        method: 'keyup',
        keyboardEventDict: this._getkeyboardEventDict(dict)
      });
    });
  },

  setComposition: function ic_setComposition(text, cursor, clauses, dict) {
    let self = this;
    return this._sendPromise((resolverId) => {
      cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetComposition', {
        contextId: self._contextId,
        requestId: resolverId,
        text: text,
        cursor: (typeof cursor !== 'undefined') ? cursor : text.length,
        clauses: clauses || null,
        keyboardEventDict: this._getkeyboardEventDict(dict)
      });
    });
  },

  endComposition: function ic_endComposition(text, dict) {
    let self = this;
    return this._sendPromise((resolverId) => {
      cpmmSendAsyncMessageWithKbID(self, 'Keyboard:EndComposition', {
        contextId: self._contextId,
        requestId: resolverId,
        text: text || '',
        keyboardEventDict: this._getkeyboardEventDict(dict)
      });
    });
  },

  // Generate a new keyboard event by the received keyboard dictionary
  // and return defaultPrevented's result of the event after dispatching.
  forwardHardwareKeyEvent: function ic_forwardHardwareKeyEvent(data) {
    if (!Ci.nsIHardwareKeyHandler) {
      return;
    }

    if (!this._context) {
      return Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;
    }
    let evt = new this._window.KeyboardEvent(data.type,
                                             Cu.cloneInto(data.keyDict,
                                                          this._window));
    this._hardwareinput.__DOM_IMPL__.dispatchEvent(evt);
    return this._getDefaultPreventedValue(evt);
  },

  _getDefaultPreventedValue: function(evt) {
    if (!Ci.nsIHardwareKeyHandler) {
      return;
    }

    let flags = Ci.nsIHardwareKeyHandler.NO_DEFAULT_PREVENTED;

    if (evt.defaultPrevented) {
      flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED;
    }

    if (evt.defaultPreventedByChrome) {
      flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED_BY_CHROME;
    }

    if (evt.defaultPreventedByContent) {
      flags |= Ci.nsIHardwareKeyHandler.DEFAULT_PREVENTED_BY_CONTENT;
    }

    return flags;
  },

  _sendPromise: function(callback) {
    let self = this;
    return this._ipcHelper.createPromiseWithId(function(aResolverId) {
      if (!WindowMap.isActive(self._window)) {
        self._ipcHelper.removePromiseResolver(aResolverId);
        reject('Input method is not active.');
        return;
      }
      callback(aResolverId);
    });
  },

  // Take a MozInputMethodKeyboardEventDict dict, creates a keyboardEventDict
  // object that can be sent to forms.js
  _getkeyboardEventDict: function(dict) {
    if (typeof dict !== 'object' || !dict.key) {
      return;
    }

    var keyboardEventDict = {
      key: dict.key,
      code: dict.code,
      repeat: dict.repeat,
      flags: 0
    };

    if (dict.printable) {
      keyboardEventDict.flags |=
        Ci.nsITextInputProcessor.KEY_FORCE_PRINTABLE_KEY;
    }

    if (/^[a-zA-Z0-9]$/.test(dict.key)) {
      // keyCode must follow the key value in this range;
      // disregard the keyCode from content.
      keyboardEventDict.keyCode = dict.key.toUpperCase().charCodeAt(0);
    } else if (typeof dict.keyCode === 'number') {
      // Allow keyCode to be specified for other key values.
      keyboardEventDict.keyCode = dict.keyCode;

      // Allow keyCode to be explicitly set to zero.
      if (dict.keyCode === 0) {
        keyboardEventDict.flags |=
          Ci.nsITextInputProcessor.KEY_KEEP_KEYCODE_ZERO;
      }
    }

    return keyboardEventDict;
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MozInputMethod]);