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.

477 lines
22KB

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