android.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. var mappings = require("./mappings"),
  2. platformName = "android";
  3. module.exports = function (context) {
  4. var
  5. req = context ? context.requireCordovaModule : require,
  6. Q = req('q'),
  7. path = req('path'),
  8. ET = req('elementtree'),
  9. cordova = req('cordova'),
  10. cordova_lib = cordova.cordova_lib,
  11. ConfigParser = cordova_lib.configparser,
  12. cordova_util = req('cordova-lib/src/cordova/util'),
  13. fs = require("./filesystem")(Q, req('fs'), path),
  14. platforms = {};
  15. // fs, path, ET, cordova_util, ConfigParser
  16. function mapConfig(config) {
  17. var element = {
  18. attrs: {},
  19. children: []
  20. };
  21. if (!config.type) {
  22. throw "no type defined for "+JSON.stringify (config, null, "\t");
  23. }
  24. var mapping = mappings[config.type];
  25. if (!mapping)
  26. throw "no mapping for "+ config.type;
  27. element.tagname = mapping[platformName];
  28. if (mapping.required) {
  29. mapping.required.forEach (function (k) {
  30. if (!(k in config)) {
  31. throw ['attribute', k, 'not found for', config.title, '(' + config.type + ')'].join (" ");
  32. }
  33. });
  34. }
  35. if (mapping.attrs) {
  36. for (var attrName in mapping.attrs) {
  37. if (!config.hasOwnProperty(attrName))
  38. continue;
  39. var attrConfig = mapping.attrs[attrName];
  40. var elementKey = attrConfig[platformName];
  41. var targetCheck = elementKey.split ('@');
  42. var targetAttr;
  43. if (targetCheck.length === 2 && targetCheck[0] === '') {
  44. targetAttr = targetCheck[1];
  45. if (!element.attrs)
  46. element.attrs = {};
  47. element.attrs[targetAttr] = [];
  48. }
  49. if (attrConfig.value) {
  50. if (!attrConfig.value[config[attrName]] || !attrConfig.value[config[attrName]][platformName])
  51. throw "no mapping for type: "+ config.type + ", attr: " + attrName + ", value: " + config[attrName];
  52. if (targetAttr)
  53. element.attrs[targetAttr].push (attrConfig.value[config[attrName]][platformName]);
  54. else
  55. element[elementKey] = attrConfig.value[config[attrName]][platformName]
  56. } else {
  57. if (targetAttr)
  58. element.attrs[targetAttr].push (config[attrName]);
  59. else
  60. element[elementKey] = config[attrName];
  61. }
  62. }
  63. }
  64. if (mapping.fixup && mapping.fixup[platformName]) {
  65. mapping.fixup[platformName] (element, config, mapping);
  66. }
  67. return element;
  68. }
  69. function buildNode(parent, config, stringsArrays) {
  70. for (var attr in config.attrs) {
  71. if (config.attrs[attr] && config.attrs[attr].constructor === Array)
  72. config.attrs[attr] = config.attrs[attr].join ('|');
  73. }
  74. var newNode = new ET.SubElement(parent, config.tagname);
  75. newNode.attrib = config.attrs;
  76. if (config.strings) {
  77. console.log("will push strings array "+JSON.stringify(config.strings));
  78. stringsArrays.push(config.strings);
  79. }
  80. if (config.children) {
  81. config.children.forEach(function(child){
  82. buildNode(newNode, child, stringsArrays);
  83. });
  84. }
  85. }
  86. // build Android settings XML
  87. function buildSettings(configJson) {
  88. var screenNode = new ET.Element('PreferenceScreen'),
  89. resourcesNode = new ET.Element('resources'),
  90. stringsArrays = [];
  91. screenNode.set('xmlns:android', 'http://schemas.android.com/apk/res/android');
  92. // Generate base settings file
  93. configJson.forEach(function (preference) {
  94. var node = mapConfig(preference);
  95. if (preference.type === 'group' && preference.items && preference.items.length) {
  96. preference.items.forEach(function(childNode) {
  97. node.children.push(mapConfig(childNode));
  98. });
  99. }
  100. buildNode(screenNode, node, stringsArrays);
  101. });
  102. // Generate resource file
  103. stringsArrays.forEach(function (stringsArray) {
  104. var titlesXml = new ET.SubElement(resourcesNode, 'string-array'),
  105. valuesXml = new ET.SubElement(resourcesNode, 'string-array');
  106. titlesXml.set("name", "apppreferences_" + stringsArray.name);
  107. valuesXml.set("name", "apppreferences_" + stringsArray.name + 'Values');
  108. for (var i=0, l=stringsArray.titles.length; i<l; i++) {
  109. var titleItemXml = new ET.SubElement(titlesXml, "item"),
  110. valueItemXml = new ET.SubElement(valuesXml, "item");
  111. titleItemXml.text = stringsArray.titles[i];
  112. valueItemXml.text = stringsArray.values[i];
  113. }
  114. });
  115. return {
  116. preferencesDocument: new ET.ElementTree(screenNode),
  117. preferencesStringDocument: new ET.ElementTree(resourcesNode)
  118. };
  119. }
  120. function build(config) {
  121. var settingsDocuments = buildSettings(config),
  122. preferencesDocument = settingsDocuments.preferencesDocument,
  123. preferencesStringDocument = settingsDocuments.preferencesStringDocument;
  124. return fs.exists('platforms/android')
  125. // Write preferences xml file
  126. .then(function () { return fs.mkdir('platforms/android/res/xml'); })
  127. .then(function () { return fs.writeFile('platforms/android/res/xml/apppreferences.xml', preferencesDocument.write()); })
  128. // Write localization resource file
  129. .then(function () { return fs.mkdir('platforms/android/res/values'); })
  130. .then(function (prefs) { return fs.writeFile('platforms/android/res/values/apppreferences.xml', preferencesStringDocument.write()); })
  131. .then(function () { console.log('android preferences file was successfully generated'); })
  132. .catch(function (err) {
  133. if (err.code === 'NEXIST') {
  134. console.log("Platform android not found: skipping");
  135. return;
  136. }
  137. throw err;
  138. });
  139. }
  140. function afterPluginInstall () {
  141. return fs.exists('platforms/android')
  142. // Import preferences into native android project
  143. .then(function () { return fs.readFile(path.resolve(__dirname, '../../src/android/AppPreferencesActivity.template')); })
  144. .then(function (tmpl) {
  145. var projectRoot = cordova_lib.cordova.findProjectRoot(process.cwd()),
  146. projectXml = cordova_util.projectConfig(projectRoot),
  147. projectConfig = new ConfigParser(projectXml);
  148. var packageName = projectConfig.android_packageName() || projectConfig.packageName();
  149. return (
  150. //'package me.apla.cordova;\n\n' +
  151. //'import ' + packageName + '.R;\n\n' +
  152. tmpl.toString ('utf8').replace (/ANDROID_PACKAGE_NAME/g, packageName)
  153. );
  154. })
  155. .then(function (data) {
  156. var androidPackagePath = "me.apla.cordova".replace (/\./g, '/');
  157. var activityFileName= path.join ('platforms/android/src', androidPackagePath, 'AppPreferencesActivity.java');
  158. return fs.writeFile(activityFileName, data);
  159. })
  160. .catch(function (err) {
  161. if (err.code === 'NEXIST') {
  162. console.log("Platform android not found: skipping");
  163. return;
  164. }
  165. throw err;
  166. });
  167. }
  168. function clean(config) {
  169. var androidPackagePath = "me.apla.cordova".replace (/\./g, '/');
  170. var activityFileName = path.join ('platforms/android/src', androidPackagePath, 'AppPreferencesActivity.java');
  171. return fs.exists('platforms/android')
  172. // Remove preferences xml file
  173. .then(function () { return fs.unlink('platforms/android/res/xml/apppreferences.xml'); })
  174. // Remove localization resource file
  175. .then(function (prefs) { return fs.unlink('platforms/android/res/values/apppreferences.xml'); })
  176. // Remove preferences from native android project
  177. .then(function (data) {
  178. return fs.unlink(activityFileName);
  179. })
  180. .then(function () { console.log('android preferences file was successfully cleaned'); })
  181. .catch(function (err) {
  182. if (err.code === 'NEXIST') {
  183. console.log("Platform android not found: skipping");
  184. return;
  185. } else if (err.code === 'ENOENT' && err.path === activityFileName) {
  186. // Activity not generated, that's fine
  187. return;
  188. }
  189. throw err;
  190. });
  191. }
  192. return {
  193. mapConfig: mapConfig,
  194. buildSettings: buildSettings,
  195. build: build,
  196. afterPluginInstall: afterPluginInstall,
  197. clean: clean
  198. };
  199. };