The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

507 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class AndroidProjectExporterBase : public ProjectExporter
  18. {
  19. public:
  20. //==========================================================================
  21. AndroidProjectExporterBase (Project& p, const ValueTree& t)
  22. : ProjectExporter (p, t)
  23. {
  24. setEmptyPropertiesToDefaultValues();
  25. }
  26. //==========================================================================
  27. virtual bool isAndroidStudio() = 0;
  28. virtual bool isAndroidAnt() = 0;
  29. //==========================================================================
  30. void setEmptyPropertiesToDefaultValues()
  31. {
  32. if (getVersionCodeString().isEmpty())
  33. getVersionCodeValue() = 1;
  34. if (getActivityClassPath().isEmpty())
  35. getActivityClassPathValue() = createDefaultClassName();
  36. if (getMinimumSDKVersionString().isEmpty())
  37. getMinimumSDKVersionValue() = 23;
  38. if (getInternetNeededValue().toString().isEmpty())
  39. getInternetNeededValue() = true;
  40. if (getBluetoothPermissionsValue().toString().isEmpty())
  41. getBluetoothPermissionsValue() = true;
  42. if (getKeyStoreValue().getValue().isVoid()) getKeyStoreValue() = "${user.home}/.android/debug.keystore";
  43. if (getKeyStorePassValue().getValue().isVoid()) getKeyStorePassValue() = "android";
  44. if (getKeyAliasValue().getValue().isVoid()) getKeyAliasValue() = "androiddebugkey";
  45. if (getKeyAliasPassValue().getValue().isVoid()) getKeyAliasPassValue() = "android";
  46. initialiseDependencyPathValues();
  47. if (getScreenOrientationValue().toString().isEmpty())
  48. getScreenOrientationValue() = "unspecified";
  49. }
  50. //==========================================================================
  51. void create (const OwnedArray<LibraryModule>& modules) const override
  52. {
  53. const String package (getActivityClassPackage());
  54. const String path (package.replaceCharacter ('.', File::separator));
  55. const File target (getTargetFolder().getChildFile ("src").getChildFile (path));
  56. copyActivityJavaFiles (modules, target, package);
  57. }
  58. //==========================================================================
  59. // base properties
  60. Value getScreenOrientationValue() { return getSetting (Ids::androidScreenOrientation); }
  61. String getScreenOrientationString() const { return settings [Ids::androidScreenOrientation]; }
  62. Value getActivityClassPathValue() { return getSetting (Ids::androidActivityClass); }
  63. String getActivityClassPath() const { return settings [Ids::androidActivityClass]; }
  64. Value getActivitySubClassPathValue() { return getSetting (Ids::androidActivitySubClassName); }
  65. String getActivitySubClassPath() const { return settings [Ids::androidActivitySubClassName]; }
  66. Value getVersionCodeValue() { return getSetting (Ids::androidVersionCode); }
  67. String getVersionCodeString() const { return settings [Ids::androidVersionCode]; }
  68. Value getSDKPathValue() { return sdkPath; }
  69. String getSDKPathString() const { return sdkPath.toString(); }
  70. Value getNDKPathValue() { return ndkPath; }
  71. String getNDKPathString() const { return ndkPath.toString(); }
  72. Value getMinimumSDKVersionValue() { return getSetting (Ids::androidMinimumSDK); }
  73. String getMinimumSDKVersionString() const { return settings [Ids::androidMinimumSDK]; }
  74. // manifest properties
  75. Value getInternetNeededValue() { return getSetting (Ids::androidInternetNeeded); }
  76. bool getInternetNeeded() const { return settings [Ids::androidInternetNeeded]; }
  77. Value getAudioRecordNeededValue() { return getSetting (Ids::androidMicNeeded); }
  78. bool getAudioRecordNeeded() const { return settings [Ids::androidMicNeeded]; }
  79. Value getBluetoothPermissionsValue() { return getSetting(Ids::androidBluetoothNeeded); }
  80. bool getBluetoothPermissions() const { return settings[Ids::androidBluetoothNeeded]; }
  81. Value getOtherPermissionsValue() { return getSetting (Ids::androidOtherPermissions); }
  82. String getOtherPermissions() const { return settings [Ids::androidOtherPermissions]; }
  83. // code signing properties
  84. Value getKeyStoreValue() { return getSetting (Ids::androidKeyStore); }
  85. String getKeyStoreString() const { return settings [Ids::androidKeyStore]; }
  86. Value getKeyStorePassValue() { return getSetting (Ids::androidKeyStorePass); }
  87. String getKeyStorePassString() const { return settings [Ids::androidKeyStorePass]; }
  88. Value getKeyAliasValue() { return getSetting (Ids::androidKeyAlias); }
  89. String getKeyAliasString() const { return settings [Ids::androidKeyAlias]; }
  90. Value getKeyAliasPassValue() { return getSetting (Ids::androidKeyAliasPass); }
  91. String getKeyAliasPassString() const { return settings [Ids::androidKeyAliasPass]; }
  92. // other properties
  93. Value getThemeValue() { return getSetting (Ids::androidTheme); }
  94. String getThemeString() const { return settings [Ids::androidTheme]; }
  95. //==========================================================================
  96. void createExporterProperties (PropertyListBuilder& props) override
  97. {
  98. createBaseExporterProperties (props);
  99. createToolchainExporterProperties (props);
  100. createManifestExporterProperties (props);
  101. createLibraryModuleExporterProperties (props);
  102. createCodeSigningExporterProperties (props);
  103. createOtherExporterProperties (props);
  104. }
  105. //==========================================================================
  106. enum ScreenOrientation
  107. {
  108. unspecified = 1,
  109. portrait = 2,
  110. landscape = 3
  111. };
  112. //==============================================================================
  113. void createBaseExporterProperties (PropertyListBuilder& props)
  114. {
  115. static const char* orientations[] = { "Portrait and Landscape", "Portrait", "Landscape", nullptr };
  116. static const char* orientationValues[] = { "unspecified", "portrait", "landscape", nullptr };
  117. props.add (new ChoicePropertyComponent (getScreenOrientationValue(), "Screen orientation", StringArray (orientations), Array<var> (orientationValues)),
  118. "The screen orientation that this app should use");
  119. props.add (new TextPropertyComponent (getActivityClassPathValue(), "Android Activity class name", 256, false),
  120. "The full java class name to use for the app's Activity class.");
  121. props.add (new TextPropertyComponent (getActivitySubClassPathValue(), "Android Activity sub-class name", 256, false),
  122. "If not empty, specifies the Android Activity class name stored in the app's manifest. "
  123. "Use this if you would like to use your own Android Activity sub-class.");
  124. props.add (new TextPropertyComponent (getVersionCodeValue(), "Android Version Code", 32, false),
  125. "An integer value that represents the version of the application code, relative to other versions.");
  126. props.add (new DependencyPathPropertyComponent (getSDKPathValue(), "Android SDK Path"),
  127. "The path to the Android SDK folder on the target build machine");
  128. props.add (new DependencyPathPropertyComponent (getNDKPathValue(), "Android NDK Path"),
  129. "The path to the Android NDK folder on the target build machine");
  130. props.add (new TextPropertyComponent (getMinimumSDKVersionValue(), "Minimum SDK version", 32, false),
  131. "The number of the minimum version of the Android SDK that the app requires");
  132. }
  133. //==========================================================================
  134. virtual void createToolchainExporterProperties (PropertyListBuilder& props) = 0; // different for ant and Android Studio
  135. //==========================================================================
  136. void createManifestExporterProperties (PropertyListBuilder& props)
  137. {
  138. props.add (new BooleanPropertyComponent (getInternetNeededValue(), "Internet Access", "Specify internet access permission in the manifest"),
  139. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  140. props.add (new BooleanPropertyComponent (getAudioRecordNeededValue(), "Audio Input Required", "Specify audio record permission in the manifest"),
  141. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  142. props.add (new BooleanPropertyComponent (getBluetoothPermissionsValue(), "Bluetooth permissions Required", "Specify bluetooth permission (required for Bluetooth MIDI)"),
  143. "If enabled, this will set the android.permission.BLUETOOTH and android.permission.BLUETOOTH_ADMIN flag in the manifest. This is required for Bluetooth MIDI on Android.");
  144. props.add (new TextPropertyComponent (getOtherPermissionsValue(), "Custom permissions", 2048, false),
  145. "A space-separated list of other permission flags that should be added to the manifest.");
  146. }
  147. //==========================================================================
  148. virtual void createLibraryModuleExporterProperties (PropertyListBuilder& props) = 0; // different for ant and Android Studio
  149. //==========================================================================
  150. void createCodeSigningExporterProperties (PropertyListBuilder& props)
  151. {
  152. props.add (new TextPropertyComponent (getKeyStoreValue(), "Key Signing: key.store", 2048, false),
  153. "The key.store value, used when signing the package.");
  154. props.add (new TextPropertyComponent (getKeyStorePassValue(), "Key Signing: key.store.password", 2048, false),
  155. "The key.store password, used when signing the package.");
  156. props.add (new TextPropertyComponent (getKeyAliasValue(), "Key Signing: key.alias", 2048, false),
  157. "The key.alias value, used when signing the package.");
  158. props.add (new TextPropertyComponent (getKeyAliasPassValue(), "Key Signing: key.alias.password", 2048, false),
  159. "The key.alias password, used when signing the package.");
  160. }
  161. //==========================================================================
  162. void createOtherExporterProperties (PropertyListBuilder& props)
  163. {
  164. props.add (new TextPropertyComponent (getThemeValue(), "Android Theme", 256, false),
  165. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  166. }
  167. //==============================================================================
  168. String createDefaultClassName() const
  169. {
  170. String s (project.getBundleIdentifier().toString().toLowerCase());
  171. if (s.length() > 5
  172. && s.containsChar ('.')
  173. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  174. && ! s.startsWithChar ('.'))
  175. {
  176. if (! s.endsWithChar ('.'))
  177. s << ".";
  178. }
  179. else
  180. {
  181. s = "com.yourcompany.";
  182. }
  183. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRoot(), false, true, false);
  184. }
  185. void initialiseDependencyPathValues()
  186. {
  187. sdkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidSDKPath),
  188. Ids::androidSDKPath, TargetOS::getThisOS())));
  189. ndkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidNDKPath),
  190. Ids::androidNDKPath, TargetOS::getThisOS())));
  191. }
  192. void copyActivityJavaFiles (const OwnedArray<LibraryModule>& modules, const File& targetFolder, const String& package) const
  193. {
  194. const String className (getActivityName());
  195. if (className.isEmpty())
  196. throw SaveError ("Invalid Android Activity class name: " + getActivityClassPath());
  197. createDirectoryOrThrow (targetFolder);
  198. LibraryModule* const coreModule = getCoreModule (modules);
  199. if (coreModule != nullptr)
  200. {
  201. File javaDestFile (targetFolder.getChildFile (className + ".java"));
  202. File javaSourceFolder (coreModule->getFolder().getChildFile ("native")
  203. .getChildFile ("java"));
  204. String juceMidiCode, juceMidiImports, juceRuntimePermissionsCode;
  205. juceMidiImports << newLine;
  206. if (getMinimumSDKVersionString().getIntValue() >= 23)
  207. {
  208. File javaAndroidMidi (javaSourceFolder.getChildFile ("AndroidMidi.java"));
  209. File javaRuntimePermissions (javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java"));
  210. juceMidiImports << "import android.media.midi.*;" << newLine
  211. << "import android.bluetooth.*;" << newLine
  212. << "import android.bluetooth.le.*;" << newLine;
  213. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  214. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  215. }
  216. else
  217. {
  218. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  219. .loadFileAsString()
  220. .replace ("JuceAppActivity", className);
  221. }
  222. File javaSourceFile (javaSourceFolder.getChildFile ("JuceAppActivity.java"));
  223. StringArray javaSourceLines (StringArray::fromLines (javaSourceFile.loadFileAsString()));
  224. {
  225. MemoryOutputStream newFile;
  226. for (int i = 0; i < javaSourceLines.size(); ++i)
  227. {
  228. const String& line = javaSourceLines[i];
  229. if (line.contains ("$$JuceAndroidMidiImports$$"))
  230. newFile << juceMidiImports;
  231. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  232. newFile << juceMidiCode;
  233. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  234. newFile << juceRuntimePermissionsCode;
  235. else
  236. newFile << line.replace ("JuceAppActivity", className)
  237. .replace ("package com.juce;", "package " + package + ";") << newLine;
  238. }
  239. javaSourceLines = StringArray::fromLines (newFile.toString());
  240. }
  241. while (javaSourceLines.size() > 2
  242. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  243. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  244. javaSourceLines.remove (javaSourceLines.size() - 1);
  245. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  246. }
  247. }
  248. String getActivityName() const
  249. {
  250. return getActivityClassPath().fromLastOccurrenceOf (".", false, false);
  251. }
  252. String getActivitySubClassName() const
  253. {
  254. String activityPath = getActivitySubClassPath();
  255. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  256. }
  257. String getActivityClassPackage() const
  258. {
  259. return getActivityClassPath().upToLastOccurrenceOf (".", false, false);
  260. }
  261. String getJNIActivityClassName() const
  262. {
  263. return getActivityClassPath().replaceCharacter ('.', '/');
  264. }
  265. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  266. {
  267. for (int i = modules.size(); --i >= 0;)
  268. if (modules.getUnchecked(i)->getID() == "juce_core")
  269. return modules.getUnchecked(i);
  270. return nullptr;
  271. }
  272. StringArray getPermissionsRequired() const
  273. {
  274. StringArray s;
  275. s.addTokens (getOtherPermissions(), ", ", "");
  276. if (getInternetNeeded())
  277. s.add ("android.permission.INTERNET");
  278. if (getAudioRecordNeeded())
  279. s.add ("android.permission.RECORD_AUDIO");
  280. if (getBluetoothPermissions())
  281. {
  282. s.add ("android.permission.BLUETOOTH");
  283. s.add ("android.permission.BLUETOOTH_ADMIN");
  284. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  285. }
  286. return getCleanedStringArray (s);
  287. }
  288. template <typename PredicateT>
  289. void findAllProjectItemsWithPredicate (const Project::Item& projectItem, Array<RelativePath>& results, const PredicateT& predicate) const
  290. {
  291. if (projectItem.isGroup())
  292. {
  293. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  294. findAllProjectItemsWithPredicate (projectItem.getChild(i), results, predicate);
  295. }
  296. else
  297. {
  298. if (predicate (projectItem))
  299. results.add (RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder));
  300. }
  301. }
  302. void writeIcon (const File& file, const Image& im) const
  303. {
  304. if (im.isValid())
  305. {
  306. createDirectoryOrThrow (file.getParentDirectory());
  307. PNGImageFormat png;
  308. MemoryOutputStream mo;
  309. if (! png.writeImageToStream (im, mo))
  310. throw SaveError ("Can't generate Android icon file");
  311. overwriteFileIfDifferentOrThrow (file, mo);
  312. }
  313. }
  314. void writeIcons (const File& folder) const
  315. {
  316. ScopedPointer<Drawable> bigIcon (getBigIcon());
  317. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  318. if (bigIcon != nullptr && smallIcon != nullptr)
  319. {
  320. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  321. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  322. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  323. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  324. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  325. }
  326. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  327. {
  328. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  329. }
  330. }
  331. template <typename BuildConfigType>
  332. String getABIs (bool forDebug) const
  333. {
  334. for (ConstConfigIterator config (*this); config.next();)
  335. {
  336. const BuildConfigType& androidConfig = dynamic_cast<const BuildConfigType&> (*config);
  337. if (config->isDebug() == forDebug)
  338. return androidConfig.getArchitectures();
  339. }
  340. return String();
  341. }
  342. //==============================================================================
  343. XmlElement* createManifestXML() const
  344. {
  345. XmlElement* manifest = new XmlElement ("manifest");
  346. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  347. manifest->setAttribute ("android:versionCode", getVersionCodeString());
  348. manifest->setAttribute ("android:versionName", project.getVersionString());
  349. manifest->setAttribute ("package", getActivityClassPackage());
  350. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  351. screens->setAttribute ("android:smallScreens", "true");
  352. screens->setAttribute ("android:normalScreens", "true");
  353. screens->setAttribute ("android:largeScreens", "true");
  354. //screens->setAttribute ("android:xlargeScreens", "true");
  355. screens->setAttribute ("android:anyDensity", "true");
  356. XmlElement* sdk = manifest->createNewChildElement ("uses-sdk");
  357. sdk->setAttribute ("android:minSdkVersion", getMinimumSDKVersionString());
  358. sdk->setAttribute ("android:targetSdkVersion", "11");
  359. {
  360. const StringArray permissions (getPermissionsRequired());
  361. for (int i = permissions.size(); --i >= 0;)
  362. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  363. }
  364. if (project.getModules().isModuleEnabled ("juce_opengl"))
  365. {
  366. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  367. feature->setAttribute ("android:glEsVersion", "0x00020000");
  368. feature->setAttribute ("android:required", "true");
  369. }
  370. XmlElement* app = manifest->createNewChildElement ("application");
  371. app->setAttribute ("android:label", "@string/app_name");
  372. String androidThemeString (getThemeString());
  373. if (androidThemeString.isNotEmpty())
  374. app->setAttribute ("android:theme", androidThemeString);
  375. {
  376. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  377. if (bigIcon != nullptr || smallIcon != nullptr)
  378. app->setAttribute ("android:icon", "@drawable/icon");
  379. }
  380. if (getMinimumSDKVersionString().getIntValue() >= 11)
  381. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  382. XmlElement* act = app->createNewChildElement ("activity");
  383. act->setAttribute ("android:name", getActivitySubClassName());
  384. act->setAttribute ("android:label", "@string/app_name");
  385. act->setAttribute ("android:configChanges", "keyboardHidden|orientation|screenSize");
  386. act->setAttribute ("android:screenOrientation", getScreenOrientationString());
  387. XmlElement* intent = act->createNewChildElement ("intent-filter");
  388. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  389. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  390. return manifest;
  391. }
  392. //==============================================================================
  393. Value sdkPath, ndkPath;
  394. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidProjectExporterBase)
  395. };