1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // Custom binding for the tts API. 6 7 var binding = require('binding').Binding.create('tts'); 8 9 var idGenerator = requireNative('id_generator'); 10 var sendRequest = require('sendRequest').sendRequest; 11 var lazyBG = requireNative('lazy_background_page'); 12 13 binding.registerCustomHook(function(api) { 14 var apiFunctions = api.apiFunctions; 15 var tts = api.compiledApi; 16 var handlers = {}; 17 18 function ttsEventListener(event) { 19 var eventHandler = handlers[event.srcId]; 20 if (eventHandler) { 21 eventHandler({ 22 type: event.type, 23 charIndex: event.charIndex, 24 errorMessage: event.errorMessage 25 }); 26 if (event.isFinalEvent) { 27 delete handlers[event.srcId]; 28 // Balanced in 'speak' handler. 29 lazyBG.DecrementKeepaliveCount(); 30 } 31 } 32 } 33 34 // This file will get run if an extension needs the ttsEngine permission, but 35 // it doesn't necessarily have the tts permission. If it doesn't, trying to 36 // add a listener to chrome.tts.onEvent will fail. 37 // See http://crbug.com/122474. 38 try { 39 tts.onEvent.addListener(ttsEventListener); 40 } catch (e) {} 41 42 apiFunctions.setHandleRequest('speak', function() { 43 var args = arguments; 44 if (args.length > 1 && args[1] && args[1].onEvent) { 45 var id = idGenerator.GetNextId(); 46 args[1].srcId = id; 47 handlers[id] = args[1].onEvent; 48 // Keep the page alive until the event finishes. 49 // Balanced in eventHandler. 50 lazyBG.IncrementKeepaliveCount(); 51 } 52 sendRequest(this.name, args, this.definition.parameters); 53 return id; 54 }); 55 }); 56 57 exports.binding = binding.generate(); 58