[email protected] | a5380cc7 | 2012-03-28 04:59:52 | [diff] [blame^] | 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 | var SetIconCommon = requireNative('schema_generated_bindings').SetIconCommon; |
| 6 | var sendRequest = require('sendRequest').sendRequest; |
| 7 | |
| 8 | function setIcon(details, name, parameters, actionType) { |
| 9 | var iconSize = 19; |
| 10 | if ("iconIndex" in details) { |
| 11 | sendRequest(name, [details], parameters); |
| 12 | } else if ("imageData" in details) { |
| 13 | // Verify that this at least looks like an ImageData element. |
| 14 | // Unfortunately, we cannot use instanceof because the ImageData |
| 15 | // constructor is not public. |
| 16 | // |
| 17 | // We do this manually instead of using JSONSchema to avoid having these |
| 18 | // properties show up in the doc. |
| 19 | if (!("width" in details.imageData) || |
| 20 | !("height" in details.imageData) || |
| 21 | !("data" in details.imageData)) { |
| 22 | throw new Error( |
| 23 | "The imageData property must contain an ImageData object."); |
| 24 | } |
| 25 | |
| 26 | if (details.imageData.width > iconSize || |
| 27 | details.imageData.height > iconSize) { |
| 28 | throw new Error( |
| 29 | "The imageData property must contain an ImageData object that " + |
| 30 | "is no larger than " + iconSize + " pixels square."); |
| 31 | } |
| 32 | |
| 33 | sendRequest(name, [details], parameters, |
| 34 | {noStringify: true, nativeFunction: SetIconCommon}); |
| 35 | } else if ("path" in details) { |
| 36 | var img = new Image(); |
| 37 | img.onerror = function() { |
| 38 | console.error("Could not load " + actionType + " icon '" + |
| 39 | details.path + "'."); |
| 40 | }; |
| 41 | img.onload = function() { |
| 42 | var canvas = document.createElement("canvas"); |
| 43 | canvas.width = img.width > iconSize ? iconSize : img.width; |
| 44 | canvas.height = img.height > iconSize ? iconSize : img.height; |
| 45 | |
| 46 | var canvas_context = canvas.getContext('2d'); |
| 47 | canvas_context.clearRect(0, 0, canvas.width, canvas.height); |
| 48 | canvas_context.drawImage(img, 0, 0, canvas.width, canvas.height); |
| 49 | delete details.path; |
| 50 | details.imageData = canvas_context.getImageData(0, 0, canvas.width, |
| 51 | canvas.height); |
| 52 | sendRequest(name, [details], parameters, |
| 53 | {noStringify: true, nativeFunction: SetIconCommon}); |
| 54 | }; |
| 55 | img.src = details.path; |
| 56 | } else { |
| 57 | throw new Error( |
| 58 | "Either the path or imageData property must be specified."); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | exports.setIcon = setIcon; |