summaryrefslogtreecommitdiffstats
path: root/dom/browser-element/mochitest/browserElement_SetInputMethodActive.js
blob: 2b94f5cda47b69e20d802b4b7d033bf56206615e (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
/* Any copyright is dedicated to the public domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

// Bug 905573 - Add setInputMethodActive to browser elements to allow gaia
// system set the active IME app.
'use strict';

SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);

// We'll need to get the appId from the current document,
// it's either SpecialPowers.Ci.nsIScriptSecurityManager.NO_APP_ID when
// we are not running inside an app (e.g. Firefox Desktop),
// or the appId of Mochitest app when we are running inside that app
// (e.g. Emulator).
var currentAppId = SpecialPowers.wrap(document).nodePrincipal.appId;
var inApp =
  currentAppId !== SpecialPowers.Ci.nsIScriptSecurityManager.NO_APP_ID;
// We will also need the manifest URL and set it on iframes.
var currentAppManifestURL;

if (inApp) {
  let appsService = SpecialPowers.Cc["@mozilla.org/AppsService;1"]
                      .getService(SpecialPowers.Ci.nsIAppsService);

  currentAppManifestURL = appsService.getManifestURLByLocalId(currentAppId);
};

info('appId=' + currentAppId);
info('manifestURL=' + currentAppManifestURL);

function setup() {
  let appInfo = SpecialPowers.Cc['@mozilla.org/xre/app-info;1']
                .getService(SpecialPowers.Ci.nsIXULAppInfo);
  if (appInfo.name != 'B2G') {
    SpecialPowers.Cu.import("resource://gre/modules/Keyboard.jsm", window);
  }

  SpecialPowers.setBoolPref("dom.mozInputMethod.enabled", true);
  SpecialPowers.addPermission('input-manage', true, document);
}

function tearDown() {
  SpecialPowers.setBoolPref("dom.mozInputMethod.enabled", false);
  SpecialPowers.removePermission('input-manage', document);
  SimpleTest.finish();
}

function runTest() {
  createFrames();
}

var gInputMethodFrames = [];
var gInputFrame;

function createFrames() {
  // Create two input method iframes.
  let loadendCount = 0;
  let countLoadend = function() {
    loadendCount++;
    if (loadendCount === 3) {
      setPermissions();
     }
   };

   // Create an input field to receive string from input method iframes.
   gInputFrame = document.createElement('iframe');
   gInputFrame.setAttribute('mozbrowser', 'true');
   gInputFrame.src = 'file_browserElement_SetInputMethodActive.html';
   document.body.appendChild(gInputFrame);
   gInputFrame.addEventListener('mozbrowserloadend', countLoadend);

   for (let i = 0; i < 2; i++) {
     let frame = gInputMethodFrames[i] = document.createElement('iframe');
     frame.setAttribute('mozbrowser', 'true');
     if (currentAppManifestURL) {
       frame.setAttribute('mozapp', currentAppManifestURL);
     }
     frame.addEventListener('mozbrowserloadend', countLoadend);
     frame.src = 'file_empty.html#' + i;
     document.body.appendChild(frame);
   }
 }

function setPermissions() {
  let permissions = [{
    type: 'input',
    allow: true,
    context: {
      url: SimpleTest.getTestFileURL('/file_empty.html'),
      originAttributes: {
        appId: currentAppId,
        inIsolatedMozBrowser: true
      }
    }
  }];

  if (inApp) {
    // The current document would also need to be given access for IPC to
    // recognize our permission (why)?
    permissions.push({
      type: 'input', allow: true, context: document });
  }

  SpecialPowers.pushPermissions(permissions,
    SimpleTest.waitForFocus.bind(SimpleTest, startTest));
}

 function startTest() {
  // The frame script running in the frame where the input is hosted.
  let appFrameScript = function appFrameScript() {
    let input = content.document.body.firstElementChild;
    input.oninput = function() {
      sendAsyncMessage('test:InputMethod:oninput', {
        from: 'input',
        value: this.value
      });
    };

    input.onblur = function() {
      // "Expected" lost of focus since the test is finished.
      if (input.value === 'hello#0#1') {
        return;
      }

      sendAsyncMessage('test:InputMethod:oninput', {
        from: 'input',
        error: true,
        value: 'Unexpected lost of focus on the input frame!'
      });
    };

    input.focus();
  };

  // Inject frame script to receive input.
  let mm = SpecialPowers.getBrowserFrameMessageManager(gInputFrame);
  mm.loadFrameScript('data:,(' + encodeURIComponent(appFrameScript.toString()) + ')();', false);
  mm.addMessageListener("test:InputMethod:oninput", next);

  gInputMethodFrames.forEach((frame) => {
    ok(frame.setInputMethodActive, 'Can access setInputMethodActive.');

    // The frame script running in the input method frames.
    let appFrameScript = function appFrameScript() {
      let im = content.navigator.mozInputMethod;
      im.oninputcontextchange = function() {
        let ctx = im.inputcontext;
        // Report back to parent frame on status of ctx gotten.
        // (A setTimeout() here to ensure this always happens after
        //  DOMRequest succeed.)
        content.setTimeout(() => {
          sendAsyncMessage('test:InputMethod:imFrameMessage', {
            from: 'im',
            value: content.location.hash + !!ctx
          });
        });

        // If there is a context, send out the hash.
        if (ctx) {
          ctx.replaceSurroundingText(content.location.hash);
        }
      };
    };

    // Inject frame script to receive message.
    let mm = SpecialPowers.getBrowserFrameMessageManager(frame);
    mm.loadFrameScript('data:,(' + encodeURIComponent(appFrameScript.toString()) + ')();', false);
    mm.addMessageListener("test:InputMethod:imFrameMessage", next);
  });

   // Set focus to the input field and wait for input methods' inputting.
   SpecialPowers.DOMWindowUtils.focus(gInputFrame);

  let req0 = gInputMethodFrames[0].setInputMethodActive(true);
  req0.onsuccess = function() {
    ok(true, 'setInputMethodActive succeeded (0).');
  };

  req0.onerror = function() {
    ok(false, 'setInputMethodActive failed (0): ' + this.error.name);
  };
}

var gCount = 0;

var gFrameMsgCounts = {
  'input': 0,
  'im0': 0,
  'im1': 0
};

function next(msg) {
  let wrappedMsg = SpecialPowers.wrap(msg);
  let from = wrappedMsg.data.from;
  let value = wrappedMsg.data.value;

  if (wrappedMsg.data.error) {
    ok(false, wrappedMsg.data.value);

    return;
  }

  let fromId = from;
  if (from === 'im') {
    fromId += value[1];
  }
  gFrameMsgCounts[fromId]++;

  // The texts sent from the first and the second input method are '#0' and
  // '#1' respectively.
  switch (gCount) {
    case 0:
      switch (fromId) {
        case 'im0':
          if (gFrameMsgCounts.im0 === 1) {
            is(value, '#0true', 'First frame should get the context first.');
          } else {
            ok(false, 'Unexpected multiple messages from im0.')
          }

          break;

        case 'im1':
          is(false, 'Shouldn\'t be hearing anything from second frame.');

          break;

        case 'input':
          if (gFrameMsgCounts.input === 1) {
            is(value, '#0hello',
              'Failed to get correct input from the first iframe.');
          } else {
            ok(false, 'Unexpected multiple messages from input.')
          }

          break;
      }

      if (gFrameMsgCounts.input !== 1 ||
          gFrameMsgCounts.im0 !== 1 ||
          gFrameMsgCounts.im1 !== 0) {
        return;
      }

      gCount++;

      let req0 = gInputMethodFrames[0].setInputMethodActive(false);
      req0.onsuccess = function() {
        ok(true, 'setInputMethodActive succeeded (0).');
      };
      req0.onerror = function() {
        ok(false, 'setInputMethodActive failed (0): ' + this.error.name);
      };
      let req1 = gInputMethodFrames[1].setInputMethodActive(true);
      req1.onsuccess = function() {
        ok(true, 'setInputMethodActive succeeded (1).');
      };
      req1.onerror = function() {
        ok(false, 'setInputMethodActive failed (1): ' + this.error.name);
      };

      break;

    case 1:
      switch (fromId) {
        case 'im0':
          if (gFrameMsgCounts.im0 === 2) {
            is(value, '#0false', 'First frame should have the context removed.');
          } else {
            ok(false, 'Unexpected multiple messages from im0.')
          }
          break;

        case 'im1':
          if (gFrameMsgCounts.im1 === 1) {
            is(value, '#1true', 'Second frame should get the context.');
          } else {
            ok(false, 'Unexpected multiple messages from im0.')
          }

          break;

        case 'input':
          if (gFrameMsgCounts.input === 2) {
            is(value, '#0#1hello',
               'Failed to get correct input from the second iframe.');
          } else {
            ok(false, 'Unexpected multiple messages from input.')
          }
          break;
      }

      if (gFrameMsgCounts.input !== 2 ||
          gFrameMsgCounts.im0 !== 2 ||
          gFrameMsgCounts.im1 !== 1) {
        return;
      }

      gCount++;

      // Receive the second input from the second iframe.
      // Deactive the second iframe.
      let req3 = gInputMethodFrames[1].setInputMethodActive(false);
      req3.onsuccess = function() {
        ok(true, 'setInputMethodActive(false) succeeded (2).');
      };
      req3.onerror = function() {
        ok(false, 'setInputMethodActive(false) failed (2): ' + this.error.name);
      };
      break;

    case 2:
      is(fromId, 'im1', 'Message sequence unexpected (3).');
      is(value, '#1false', 'Second frame should have the context removed.');

      tearDown();
      break;
  }
}

setup();
addEventListener('testready', runTest);