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.

529 lines
25KB

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