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.

1881 lines
89KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #pragma once
  19. //==============================================================================
  20. class AndroidProjectExporter : public ProjectExporter
  21. {
  22. public:
  23. //==============================================================================
  24. bool isXcode() const override { return false; }
  25. bool isVisualStudio() const override { return false; }
  26. bool isCodeBlocks() const override { return false; }
  27. bool isMakefile() const override { return false; }
  28. bool isAndroidStudio() const override { return true; }
  29. bool isCLion() const override { return false; }
  30. bool isAndroid() const override { return true; }
  31. bool isWindows() const override { return false; }
  32. bool isLinux() const override { return false; }
  33. bool isOSX() const override { return false; }
  34. bool isiOS() const override { return false; }
  35. bool usesMMFiles() const override { return false; }
  36. bool canCopeWithDuplicateFiles() override { return false; }
  37. bool supportsUserDefinedConfigurations() const override { return true; }
  38. String getNewLineString() const override { return "\n"; }
  39. bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
  40. {
  41. return type == build_tools::ProjectType::Target::GUIApp || type == build_tools::ProjectType::Target::StaticLibrary
  42. || type == build_tools::ProjectType::Target::DynamicLibrary || type == build_tools::ProjectType::Target::StandalonePlugIn;
  43. }
  44. //==============================================================================
  45. void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType&) override
  46. {
  47. // no-op.
  48. }
  49. //==============================================================================
  50. void createExporterProperties (PropertyListBuilder& props) override
  51. {
  52. createBaseExporterProperties (props);
  53. createToolchainExporterProperties (props);
  54. createManifestExporterProperties (props);
  55. createCodeSigningExporterProperties (props);
  56. createOtherExporterProperties (props);
  57. }
  58. static String getDisplayName() { return "Android"; }
  59. static String getValueTreeTypeName() { return "ANDROIDSTUDIO"; }
  60. static String getTargetFolderName() { return "Android"; }
  61. Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }
  62. static const char* getDefaultActivityClass() { return "com.rmsl.juce.JuceActivity"; }
  63. static const char* getDefaultApplicationClass() { return "com.rmsl.juce.JuceApp"; }
  64. static AndroidProjectExporter* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
  65. {
  66. if (settingsToUse.hasType (getValueTreeTypeName()))
  67. return new AndroidProjectExporter (projectToUse, settingsToUse);
  68. return {};
  69. }
  70. //==============================================================================
  71. ValueTreePropertyWithDefault androidJavaLibs, androidAdditionalJavaFolders, androidAdditionalResourceFolders, androidProjectRepositories,
  72. androidRepositories, androidDependencies, androidCustomAppBuildGradleContent, androidScreenOrientation,
  73. androidCustomActivityClass, androidCustomApplicationClass, androidManifestCustomXmlElements,
  74. androidGradleSettingsContent, androidVersionCode, androidMinimumSDK, androidTargetSDK, androidTheme,
  75. androidExtraAssetsFolder, androidOboeRepositoryPath, androidInternetNeeded, androidMicNeeded, androidCameraNeeded,
  76. androidBluetoothNeeded, androidExternalReadPermission, androidExternalWritePermission,
  77. androidInAppBillingPermission, androidVibratePermission, androidOtherPermissions, androidPushNotifications,
  78. androidEnableRemoteNotifications, androidRemoteNotificationsConfigFile, androidEnableContentSharing, androidKeyStore,
  79. androidKeyStorePass, androidKeyAlias, androidKeyAliasPass, gradleVersion, gradleToolchain, androidPluginVersion;
  80. //==============================================================================
  81. AndroidProjectExporter (Project& p, const ValueTree& t)
  82. : ProjectExporter (p, t),
  83. androidJavaLibs (settings, Ids::androidJavaLibs, getUndoManager()),
  84. androidAdditionalJavaFolders (settings, Ids::androidAdditionalJavaFolders, getUndoManager()),
  85. androidAdditionalResourceFolders (settings, Ids::androidAdditionalResourceFolders, getUndoManager()),
  86. androidProjectRepositories (settings, Ids::androidProjectRepositories, getUndoManager(), "google()\nmavenCentral()"),
  87. androidRepositories (settings, Ids::androidRepositories, getUndoManager()),
  88. androidDependencies (settings, Ids::androidDependencies, getUndoManager()),
  89. androidCustomAppBuildGradleContent (settings, Ids::androidCustomAppBuildGradleContent, getUndoManager()),
  90. androidScreenOrientation (settings, Ids::androidScreenOrientation, getUndoManager(), "unspecified"),
  91. androidCustomActivityClass (settings, Ids::androidCustomActivityClass, getUndoManager()),
  92. androidCustomApplicationClass (settings, Ids::androidCustomApplicationClass, getUndoManager(), getDefaultApplicationClass()),
  93. androidManifestCustomXmlElements (settings, Ids::androidManifestCustomXmlElements, getUndoManager()),
  94. androidGradleSettingsContent (settings, Ids::androidGradleSettingsContent, getUndoManager()),
  95. androidVersionCode (settings, Ids::androidVersionCode, getUndoManager(), "1"),
  96. androidMinimumSDK (settings, Ids::androidMinimumSDK, getUndoManager(), "16"),
  97. androidTargetSDK (settings, Ids::androidTargetSDK, getUndoManager(), "30"),
  98. androidTheme (settings, Ids::androidTheme, getUndoManager()),
  99. androidExtraAssetsFolder (settings, Ids::androidExtraAssetsFolder, getUndoManager()),
  100. androidOboeRepositoryPath (settings, Ids::androidOboeRepositoryPath, getUndoManager()),
  101. androidInternetNeeded (settings, Ids::androidInternetNeeded, getUndoManager(), true),
  102. androidMicNeeded (settings, Ids::microphonePermissionNeeded, getUndoManager(), false),
  103. androidCameraNeeded (settings, Ids::cameraPermissionNeeded, getUndoManager(), false),
  104. androidBluetoothNeeded (settings, Ids::androidBluetoothNeeded, getUndoManager(), true),
  105. androidExternalReadPermission (settings, Ids::androidExternalReadNeeded, getUndoManager(), true),
  106. androidExternalWritePermission (settings, Ids::androidExternalWriteNeeded, getUndoManager(), true),
  107. androidInAppBillingPermission (settings, Ids::androidInAppBilling, getUndoManager(), false),
  108. androidVibratePermission (settings, Ids::androidVibratePermissionNeeded, getUndoManager(), false),
  109. androidOtherPermissions (settings, Ids::androidOtherPermissions, getUndoManager()),
  110. androidPushNotifications (settings, Ids::androidPushNotifications, getUndoManager(), ! isLibrary()),
  111. androidEnableRemoteNotifications (settings, Ids::androidEnableRemoteNotifications, getUndoManager(), false),
  112. androidRemoteNotificationsConfigFile (settings, Ids::androidRemoteNotificationsConfigFile, getUndoManager()),
  113. androidEnableContentSharing (settings, Ids::androidEnableContentSharing, getUndoManager(), false),
  114. androidKeyStore (settings, Ids::androidKeyStore, getUndoManager(), "${user.home}/.android/debug.keystore"),
  115. androidKeyStorePass (settings, Ids::androidKeyStorePass, getUndoManager(), "android"),
  116. androidKeyAlias (settings, Ids::androidKeyAlias, getUndoManager(), "androiddebugkey"),
  117. androidKeyAliasPass (settings, Ids::androidKeyAliasPass, getUndoManager(), "android"),
  118. gradleVersion (settings, Ids::gradleVersion, getUndoManager(), "7.0.2"),
  119. gradleToolchain (settings, Ids::gradleToolchain, getUndoManager(), "clang"),
  120. androidPluginVersion (settings, Ids::androidPluginVersion, getUndoManager(), "7.0.0"),
  121. AndroidExecutable (getAppSettings().getStoredPath (Ids::androidStudioExePath, TargetOS::getThisOS()).get().toString())
  122. {
  123. name = getDisplayName();
  124. targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderName());
  125. }
  126. //==============================================================================
  127. void createToolchainExporterProperties (PropertyListBuilder& props)
  128. {
  129. props.add (new TextPropertyComponent (gradleVersion, "Gradle Version", 32, false),
  130. "The version of gradle that is used to build this app (4.10 is fine for JUCE)");
  131. props.add (new TextPropertyComponent (androidPluginVersion, "Android Plug-in Version", 32, false),
  132. "The version of the android build plugin for gradle that is used to build this app");
  133. props.add (new ChoicePropertyComponent (gradleToolchain, "NDK Toolchain",
  134. { "clang", "gcc" },
  135. { "clang", "gcc" }),
  136. "The toolchain that gradle should invoke for NDK compilation (variable model.android.ndk.tooclhain in app/build.gradle)");
  137. }
  138. //==============================================================================
  139. bool canLaunchProject() override
  140. {
  141. return AndroidExecutable.exists();
  142. }
  143. bool launchProject() override
  144. {
  145. if (! AndroidExecutable.exists())
  146. {
  147. jassertfalse;
  148. return false;
  149. }
  150. auto targetFolder = getTargetFolder();
  151. // we have to surround the path with extra quotes, otherwise Android Studio
  152. // will choke if there are any space characters in the path.
  153. return AndroidExecutable.startAsProcess ("\"" + targetFolder.getFullPathName() + "\"");
  154. }
  155. //==============================================================================
  156. void create (const OwnedArray<LibraryModule>& modules) const override
  157. {
  158. auto targetFolder = getTargetFolder();
  159. auto appFolder = targetFolder.getChildFile (isLibrary() ? "lib" : "app");
  160. removeOldFiles (targetFolder);
  161. copyExtraResourceFiles();
  162. writeFile (targetFolder, "settings.gradle", getGradleSettingsFileContent());
  163. writeFile (targetFolder, "build.gradle", getProjectBuildGradleFileContent());
  164. writeFile (appFolder, "build.gradle", getAppBuildGradleFileContent (modules));
  165. writeFile (targetFolder, "local.properties", getLocalPropertiesFileContent());
  166. writeFile (targetFolder, "gradle/wrapper/gradle-wrapper.properties", getGradleWrapperPropertiesFileContent());
  167. writeBinaryFile (targetFolder, "gradle/wrapper/LICENSE-for-gradlewrapper.txt", BinaryData::LICENSE, BinaryData::LICENSESize);
  168. writeBinaryFile (targetFolder, "gradle/wrapper/gradle-wrapper.jar", BinaryData::gradlewrapper_jar, BinaryData::gradlewrapper_jarSize);
  169. writeBinaryFile (targetFolder, "gradlew", BinaryData::gradlew, BinaryData::gradlewSize);
  170. writeBinaryFile (targetFolder, "gradlew.bat", BinaryData::gradlew_bat, BinaryData::gradlew_batSize);
  171. targetFolder.getChildFile ("gradlew").setExecutePermission (true);
  172. writeAndroidManifest (appFolder);
  173. if (! isLibrary())
  174. {
  175. copyAdditionalJavaLibs (appFolder);
  176. writeStringsXML (targetFolder);
  177. writeAppIcons (targetFolder);
  178. }
  179. writeCmakeFile (appFolder.getChildFile ("CMakeLists.txt"));
  180. auto androidExtraAssetsFolderValue = androidExtraAssetsFolder.get().toString();
  181. if (androidExtraAssetsFolderValue.isNotEmpty())
  182. {
  183. auto extraAssets = getProject().getFile().getParentDirectory().getChildFile (androidExtraAssetsFolderValue);
  184. if (extraAssets.exists() && extraAssets.isDirectory())
  185. {
  186. auto assetsFolder = appFolder.getChildFile ("src/main/assets");
  187. if (assetsFolder.deleteRecursively())
  188. extraAssets.copyDirectoryTo (assetsFolder);
  189. }
  190. }
  191. }
  192. void removeOldFiles (const File& targetFolder) const
  193. {
  194. targetFolder.getChildFile ("app/build").deleteRecursively();
  195. targetFolder.getChildFile ("app/build.gradle").deleteFile();
  196. targetFolder.getChildFile ("gradle").deleteRecursively();
  197. targetFolder.getChildFile ("local.properties").deleteFile();
  198. targetFolder.getChildFile ("settings.gradle").deleteFile();
  199. }
  200. void writeFile (const File& gradleProjectFolder, const String& filePath, const String& fileContent) const
  201. {
  202. build_tools::writeStreamToFile (gradleProjectFolder.getChildFile (filePath), [&] (MemoryOutputStream& mo)
  203. {
  204. mo.setNewLineString (getNewLineString());
  205. mo << fileContent;
  206. });
  207. }
  208. void writeBinaryFile (const File& gradleProjectFolder, const String& filePath, const char* binaryData, const int binarySize) const
  209. {
  210. build_tools::writeStreamToFile (gradleProjectFolder.getChildFile (filePath), [&] (MemoryOutputStream& mo)
  211. {
  212. mo.setNewLineString (getNewLineString());
  213. mo.write (binaryData, static_cast<size_t> (binarySize));
  214. });
  215. }
  216. protected:
  217. //==============================================================================
  218. class AndroidBuildConfiguration : public BuildConfiguration
  219. {
  220. public:
  221. AndroidBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
  222. : BuildConfiguration (p, settings, e),
  223. androidArchitectures (config, Ids::androidArchitectures, getUndoManager(), isDebug() ? "armeabi-v7a x86 arm64-v8a x86_64" : ""),
  224. androidBuildConfigRemoteNotifsConfigFile (config, Ids::androidBuildConfigRemoteNotifsConfigFile, getUndoManager()),
  225. androidAdditionalXmlValueResources (config, Ids::androidAdditionalXmlValueResources, getUndoManager()),
  226. androidAdditionalDrawableResources (config, Ids::androidAdditionalDrawableResources, getUndoManager()),
  227. androidAdditionalRawValueResources (config, Ids::androidAdditionalRawValueResources, getUndoManager()),
  228. androidCustomStringXmlElements (config, Ids::androidCustomStringXmlElements, getUndoManager())
  229. {
  230. linkTimeOptimisationValue.setDefault (false);
  231. optimisationLevelValue.setDefault (isDebug() ? gccO0 : gccO3);
  232. }
  233. String getArchitectures() const { return androidArchitectures.get().toString(); }
  234. String getRemoteNotifsConfigFile() const { return androidBuildConfigRemoteNotifsConfigFile.get().toString(); }
  235. String getAdditionalXmlResources() const { return androidAdditionalXmlValueResources.get().toString(); }
  236. String getAdditionalDrawableResources() const { return androidAdditionalDrawableResources.get().toString(); }
  237. String getAdditionalRawResources() const { return androidAdditionalRawValueResources.get().toString();}
  238. String getCustomStringsXml() const { return androidCustomStringXmlElements.get().toString(); }
  239. void createConfigProperties (PropertyListBuilder& props) override
  240. {
  241. addRecommendedLLVMCompilerWarningsProperty (props);
  242. addGCCOptimisationProperty (props);
  243. props.add (new TextPropertyComponent (androidArchitectures, "Architectures", 256, false),
  244. "A list of the architectures to build (for a fat binary). Leave empty to build for all possible android architectures.");
  245. props.add (new TextPropertyComponent (androidBuildConfigRemoteNotifsConfigFile.getPropertyAsValue(), "Remote Notifications Config File", 2048, false),
  246. "Path to google-services.json file. This will be the file provided by Firebase when creating a new app in Firebase console. "
  247. "This will override the setting from the main Android exporter node.");
  248. props.add (new TextPropertyComponent (androidAdditionalXmlValueResources, "Extra Android XML Value Resources", 8192, true),
  249. "Paths to additional \"value resource\" files in XML format that should be included in the app (one per line). "
  250. "If you have additional XML resources that should be treated as value resources, add them here.");
  251. props.add (new TextPropertyComponent (androidAdditionalDrawableResources, "Extra Android Drawable Resources", 8192, true),
  252. "Paths to additional \"drawable resource\" directories that should be included in the app (one per line). "
  253. "They will be added to \"res\" directory of Android project. "
  254. "Each path should point to a directory named \"drawable\" or \"drawable-<size>\" where <size> should be "
  255. "something like \"hdpi\", \"ldpi\", \"xxxhdpi\" etc, for instance \"drawable-xhdpi\". "
  256. "Refer to Android Studio documentation for available sizes.");
  257. props.add (new TextPropertyComponent (androidAdditionalRawValueResources, "Extra Android Raw Resources", 8192, true),
  258. "Paths to additional \"raw resource\" files that should be included in the app (one per line). "
  259. "Resource file names must contain only lowercase a-z, 0-9 or underscore.");
  260. props.add (new TextPropertyComponent (androidCustomStringXmlElements, "Custom String Resources", 8192, true),
  261. "Custom XML resources that will be added to string.xml as children of <resources> element. "
  262. "Example: \n<string name=\"value\">text</string>\n"
  263. "<string name2=\"value2\">text2</string>\n");
  264. }
  265. String getProductFlavourNameIdentifier() const
  266. {
  267. return getName().toLowerCase().replaceCharacter (L' ', L'_') + String ("_");
  268. }
  269. String getProductFlavourCMakeIdentifier() const
  270. {
  271. return getName().toUpperCase().replaceCharacter (L' ', L'_');
  272. }
  273. String getModuleLibraryArchName() const override
  274. {
  275. return "${ANDROID_ABI}";
  276. }
  277. ValueTreePropertyWithDefault androidArchitectures, androidBuildConfigRemoteNotifsConfigFile,
  278. androidAdditionalXmlValueResources, androidAdditionalDrawableResources,
  279. androidAdditionalRawValueResources, androidCustomStringXmlElements;
  280. };
  281. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  282. {
  283. return *new AndroidBuildConfiguration (project, v, *this);
  284. }
  285. private:
  286. void writeCmakeFile (const File& file) const
  287. {
  288. build_tools::writeStreamToFile (file, [&] (MemoryOutputStream& mo)
  289. {
  290. mo.setNewLineString (getNewLineString());
  291. mo << "# Automatically generated makefile, created by the Projucer" << newLine
  292. << "# Don't edit this file! Your changes will be overwritten when you re-save the Projucer project!" << newLine
  293. << newLine;
  294. mo << "cmake_minimum_required(VERSION 3.4.1)" << newLine << newLine;
  295. if (! isLibrary())
  296. mo << "set(BINARY_NAME \"juce_jni\")" << newLine << newLine;
  297. auto useOboe = project.getEnabledModules().isModuleEnabled ("juce_audio_devices")
  298. && project.isConfigFlagEnabled ("JUCE_USE_ANDROID_OBOE", true);
  299. if (useOboe)
  300. {
  301. auto oboePath = [&]
  302. {
  303. auto oboeDir = androidOboeRepositoryPath.get().toString().trim();
  304. if (oboeDir.isEmpty())
  305. oboeDir = getModuleFolderRelativeToProject ("juce_audio_devices").getChildFile ("native")
  306. .getChildFile ("oboe")
  307. .rebased (getProject().getProjectFolder(), getTargetFolder(),
  308. build_tools::RelativePath::buildTargetFolder)
  309. .toUnixStyle();
  310. // CMakeLists.txt is in the "app" subfolder
  311. if (! build_tools::isAbsolutePath (oboeDir))
  312. oboeDir = "../" + oboeDir;
  313. return expandHomeFolderToken (oboeDir);
  314. }();
  315. mo << "set(OBOE_DIR " << oboePath.quoted() << ")" << newLine << newLine;
  316. mo << "add_subdirectory (${OBOE_DIR} ./oboe)" << newLine << newLine;
  317. }
  318. String cpufeaturesPath ("${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c");
  319. mo << "add_library(\"cpufeatures\" STATIC \"" << cpufeaturesPath << "\")" << newLine
  320. << "set_source_files_properties(\"" << cpufeaturesPath << "\" PROPERTIES COMPILE_FLAGS \"-Wno-sign-conversion -Wno-gnu-statement-expression\")" << newLine << newLine;
  321. {
  322. auto projectDefines = getEscapedPreprocessorDefs (getProjectPreprocessorDefs());
  323. if (projectDefines.size() > 0)
  324. mo << "add_definitions(" << projectDefines.joinIntoString (" ") << ")" << newLine << newLine;
  325. }
  326. {
  327. mo << "include_directories( AFTER" << newLine;
  328. for (auto& path : extraSearchPaths)
  329. mo << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  330. mo << " \"${ANDROID_NDK}/sources/android/cpufeatures\"" << newLine;
  331. mo << ")" << newLine << newLine;
  332. }
  333. auto cfgExtraLinkerFlags = getExtraLinkerFlagsString();
  334. if (cfgExtraLinkerFlags.isNotEmpty())
  335. {
  336. mo << "set( JUCE_LDFLAGS \"" << cfgExtraLinkerFlags.replace ("\"", "\\\"") << "\")" << newLine;
  337. mo << "set( CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${JUCE_LDFLAGS}\")" << newLine << newLine;
  338. }
  339. mo << "enable_language(ASM)" << newLine << newLine;
  340. const auto userLibraries = getUserLibraries();
  341. if (getNumConfigurations() > 0)
  342. {
  343. bool first = true;
  344. for (ConstConfigIterator config (*this); config.next();)
  345. {
  346. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  347. auto libSearchPaths = cfg.getLibrarySearchPaths();
  348. auto cfgDefines = getConfigPreprocessorDefs (cfg);
  349. auto cfgHeaderPaths = cfg.getHeaderSearchPaths();
  350. auto cfgLibraryPaths = cfg.getLibrarySearchPaths();
  351. if (! isLibrary() && libSearchPaths.size() == 0 && cfgDefines.size() == 0
  352. && cfgHeaderPaths.size() == 0 && cfgLibraryPaths.size() == 0)
  353. continue;
  354. mo << (first ? "if" : "elseif") << "(JUCE_BUILD_CONFIGURATION MATCHES \"" << cfg.getProductFlavourCMakeIdentifier() <<"\")" << newLine;
  355. if (isLibrary())
  356. {
  357. mo << " set(BINARY_NAME \"" << getNativeModuleBinaryName (cfg) << "\")" << newLine;
  358. auto binaryLocation = cfg.getTargetBinaryRelativePathString();
  359. if (binaryLocation.isNotEmpty())
  360. {
  361. auto locationRelativeToCmake = build_tools::RelativePath (binaryLocation, build_tools::RelativePath::projectFolder)
  362. .rebased (getProject().getFile().getParentDirectory(),
  363. file.getParentDirectory(), build_tools::RelativePath::buildTargetFolder);
  364. mo << " set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"" << "../../../../" << locationRelativeToCmake.toUnixStyle() << "\")" << newLine;
  365. }
  366. }
  367. writeCmakePathLines (mo, " ", "link_directories(", libSearchPaths);
  368. if (cfgDefines.size() > 0)
  369. mo << " add_definitions(" << getEscapedPreprocessorDefs (cfgDefines).joinIntoString (" ") << ")" << newLine;
  370. writeCmakePathLines (mo, " ", "include_directories( AFTER", cfgHeaderPaths);
  371. if (userLibraries.size() > 0)
  372. {
  373. for (auto& lib : userLibraries)
  374. {
  375. String findLibraryCmd;
  376. findLibraryCmd << "find_library(" << lib.toLowerCase().replaceCharacter (L' ', L'_')
  377. << " \"" << lib << "\" PATHS";
  378. writeCmakePathLines (mo, " ", findLibraryCmd, cfgLibraryPaths, " NO_CMAKE_FIND_ROOT_PATH)");
  379. }
  380. mo << newLine;
  381. }
  382. if (cfg.isLinkTimeOptimisationEnabled())
  383. {
  384. // There's no MIPS support for LTO
  385. String mipsCondition ("NOT (ANDROID_ABI STREQUAL \"mips\" OR ANDROID_ABI STREQUAL \"mips64\")");
  386. mo << " if(" << mipsCondition << ")" << newLine;
  387. StringArray cmakeVariables ("CMAKE_C_FLAGS", "CMAKE_CXX_FLAGS", "CMAKE_EXE_LINKER_FLAGS");
  388. for (auto& variable : cmakeVariables)
  389. {
  390. auto configVariable = variable + "_" + cfg.getProductFlavourCMakeIdentifier();
  391. mo << " set(" << configVariable << " \"${" << configVariable << "} -flto\")" << newLine;
  392. }
  393. mo << " endif()" << newLine;
  394. }
  395. first = false;
  396. }
  397. if (! first)
  398. {
  399. ProjectExporter::BuildConfiguration::Ptr config (getConfiguration(0));
  400. if (config)
  401. {
  402. if (dynamic_cast<const AndroidBuildConfiguration*> (config.get()) != nullptr)
  403. {
  404. mo << "else()" << newLine;
  405. mo << " message( FATAL_ERROR \"No matching build-configuration found.\" )" << newLine;
  406. mo << "endif()" << newLine << newLine;
  407. }
  408. }
  409. }
  410. }
  411. Array<build_tools::RelativePath> excludeFromBuild;
  412. Array<std::pair<build_tools::RelativePath, String>> extraCompilerFlags;
  413. mo << "add_library( ${BINARY_NAME}" << newLine;
  414. mo << newLine;
  415. mo << " " << (getProject().getProjectType().isStaticLibrary() ? "STATIC" : "SHARED") << newLine;
  416. mo << newLine;
  417. addCompileUnits (mo, excludeFromBuild, extraCompilerFlags);
  418. mo << ")" << newLine << newLine;
  419. if (excludeFromBuild.size() > 0)
  420. {
  421. for (auto& exclude : excludeFromBuild)
  422. mo << "set_source_files_properties(\"" << exclude.toUnixStyle() << "\" PROPERTIES HEADER_FILE_ONLY TRUE)" << newLine;
  423. mo << newLine;
  424. }
  425. if (! extraCompilerFlags.isEmpty())
  426. {
  427. for (auto& extra : extraCompilerFlags)
  428. mo << "set_source_files_properties(\"" << extra.first.toUnixStyle() << "\" PROPERTIES COMPILE_FLAGS " << extra.second << " )" << newLine;
  429. mo << newLine;
  430. }
  431. auto flags = getProjectCompilerFlags();
  432. if (flags.size() > 0)
  433. mo << "target_compile_options( ${BINARY_NAME} PRIVATE " << flags.joinIntoString (" ") << " )" << newLine << newLine;
  434. for (ConstConfigIterator config (*this); config.next();)
  435. {
  436. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  437. mo << "if( JUCE_BUILD_CONFIGURATION MATCHES \"" << cfg.getProductFlavourCMakeIdentifier() << "\" )" << newLine;
  438. mo << " target_compile_options( ${BINARY_NAME} PRIVATE";
  439. auto recommendedFlags = cfg.getRecommendedCompilerWarningFlags();
  440. for (auto& recommendedFlagsType : { recommendedFlags.common, recommendedFlags.cpp })
  441. for (auto& flag : recommendedFlagsType)
  442. mo << " " << flag;
  443. mo << ")" << newLine;
  444. mo << "endif()" << newLine << newLine;
  445. }
  446. auto libraries = getAndroidLibraries();
  447. if (libraries.size() > 0)
  448. {
  449. for (auto& lib : libraries)
  450. mo << "find_library(" << lib.toLowerCase().replaceCharacter (L' ', L'_') << " \"" << lib << "\")" << newLine;
  451. mo << newLine;
  452. }
  453. libraries.addArray (userLibraries);
  454. mo << "target_link_libraries( ${BINARY_NAME}";
  455. if (libraries.size() > 0)
  456. {
  457. mo << newLine << newLine;
  458. for (auto& lib : libraries)
  459. mo << " ${" << lib.toLowerCase().replaceCharacter (L' ', L'_') << "}" << newLine;
  460. mo << " \"cpufeatures\"" << newLine;
  461. }
  462. if (useOboe)
  463. mo << " \"oboe\"" << newLine;
  464. mo << ")" << newLine;
  465. });
  466. }
  467. //==============================================================================
  468. String getGradleSettingsFileContent() const
  469. {
  470. MemoryOutputStream mo;
  471. mo.setNewLineString (getNewLineString());
  472. mo << "rootProject.name = " << "\'" << escapeQuotes (projectName) << "\'" << newLine;
  473. mo << (isLibrary() ? "include ':lib'" : "include ':app'");
  474. auto extraContent = androidGradleSettingsContent.get().toString();
  475. if (extraContent.isNotEmpty())
  476. mo << newLine << extraContent << newLine;
  477. return mo.toString();
  478. }
  479. String getProjectBuildGradleFileContent() const
  480. {
  481. MemoryOutputStream mo;
  482. mo.setNewLineString (getNewLineString());
  483. mo << "buildscript {" << newLine;
  484. mo << " repositories {" << newLine;
  485. mo << " google()" << newLine;
  486. mo << " mavenCentral()" << newLine;
  487. mo << " }" << newLine;
  488. mo << " dependencies {" << newLine;
  489. mo << " classpath 'com.android.tools.build:gradle:" << androidPluginVersion.get().toString() << "'" << newLine;
  490. if (areRemoteNotificationsEnabled())
  491. mo << " classpath 'com.google.gms:google-services:4.0.1'" << newLine;
  492. mo << " }" << newLine;
  493. mo << "}" << newLine;
  494. mo << "" << newLine;
  495. mo << "allprojects {" << newLine;
  496. mo << getAndroidProjectRepositories();
  497. mo << "}" << newLine;
  498. return mo.toString();
  499. }
  500. //==============================================================================
  501. String getAppBuildGradleFileContent (const OwnedArray<LibraryModule>& modules) const
  502. {
  503. MemoryOutputStream mo;
  504. mo.setNewLineString (getNewLineString());
  505. mo << "apply plugin: 'com.android." << (isLibrary() ? "library" : "application") << "'" << newLine << newLine;
  506. mo << "android {" << newLine;
  507. mo << " compileSdkVersion " << static_cast<int> (androidTargetSDK.get()) << newLine;
  508. mo << " externalNativeBuild {" << newLine;
  509. mo << " cmake {" << newLine;
  510. mo << " path \"CMakeLists.txt\"" << newLine;
  511. mo << " }" << newLine;
  512. mo << " }" << newLine;
  513. mo << getAndroidSigningConfig() << newLine;
  514. mo << getAndroidDefaultConfig() << newLine;
  515. mo << getAndroidBuildTypes() << newLine;
  516. mo << getAndroidProductFlavours() << newLine;
  517. mo << getAndroidVariantFilter() << newLine;
  518. mo << getAndroidJavaSourceSets (modules) << newLine;
  519. mo << getAndroidRepositories() << newLine;
  520. mo << getAndroidDependencies() << newLine;
  521. mo << androidCustomAppBuildGradleContent.get().toString() << newLine;
  522. mo << getApplyPlugins() << newLine;
  523. mo << "}" << newLine << newLine;
  524. return mo.toString();
  525. }
  526. String getAndroidProductFlavours() const
  527. {
  528. MemoryOutputStream mo;
  529. mo.setNewLineString (getNewLineString());
  530. mo << " flavorDimensions \"default\"" << newLine;
  531. mo << " productFlavors {" << newLine;
  532. for (ConstConfigIterator config (*this); config.next();)
  533. {
  534. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  535. mo << " " << cfg.getProductFlavourNameIdentifier() << " {" << newLine;
  536. if (cfg.getArchitectures().isNotEmpty())
  537. {
  538. mo << " ndk {" << newLine;
  539. mo << " abiFilters " << toGradleList (StringArray::fromTokens (cfg.getArchitectures(), " ", "")) << newLine;
  540. mo << " }" << newLine;
  541. }
  542. mo << " externalNativeBuild {" << newLine;
  543. mo << " cmake {" << newLine;
  544. if (getProject().getProjectType().isStaticLibrary())
  545. mo << " targets \"" << getNativeModuleBinaryName (cfg) << "\"" << newLine;
  546. mo << " arguments "
  547. << "\"-DJUCE_BUILD_CONFIGURATION=" << cfg.getProductFlavourCMakeIdentifier() << "\"";
  548. mo << ", \"-DCMAKE_CXX_FLAGS_" << (cfg.isDebug() ? "DEBUG" : "RELEASE")
  549. << "=-O" << cfg.getGCCOptimisationFlag();
  550. mo << "\""
  551. << ", \"-DCMAKE_C_FLAGS_" << (cfg.isDebug() ? "DEBUG" : "RELEASE")
  552. << "=-O" << cfg.getGCCOptimisationFlag()
  553. << "\"" << newLine;
  554. mo << " }" << newLine;
  555. mo << " }" << newLine << newLine;
  556. mo << " dimension \"default\"" << newLine;
  557. mo << " }" << newLine;
  558. }
  559. mo << " }" << newLine;
  560. return mo.toString();
  561. }
  562. String getAndroidSigningConfig() const
  563. {
  564. MemoryOutputStream mo;
  565. mo.setNewLineString (getNewLineString());
  566. auto keyStoreFilePath = androidKeyStore.get().toString().replace ("${user.home}", "${System.properties['user.home']}")
  567. .replace ("/", "${File.separator}");
  568. mo << " signingConfigs {" << newLine;
  569. mo << " juceSigning {" << newLine;
  570. mo << " storeFile file(\"" << keyStoreFilePath << "\")" << newLine;
  571. mo << " storePassword \"" << androidKeyStorePass.get().toString() << "\"" << newLine;
  572. mo << " keyAlias \"" << androidKeyAlias.get().toString() << "\"" << newLine;
  573. mo << " keyPassword \"" << androidKeyAliasPass.get().toString() << "\"" << newLine;
  574. mo << " storeType \"jks\"" << newLine;
  575. mo << " }" << newLine;
  576. mo << " }" << newLine;
  577. return mo.toString();
  578. }
  579. String getAndroidDefaultConfig() const
  580. {
  581. auto bundleIdentifier = project.getBundleIdentifierString().toLowerCase();
  582. auto cmakeDefs = getCmakeDefinitions();
  583. auto minSdkVersion = static_cast<int> (androidMinimumSDK.get());
  584. auto targetSdkVersion = static_cast<int> (androidTargetSDK.get());
  585. MemoryOutputStream mo;
  586. mo.setNewLineString (getNewLineString());
  587. mo << " defaultConfig {" << newLine;
  588. if (! isLibrary())
  589. mo << " applicationId \"" << bundleIdentifier << "\"" << newLine;
  590. mo << " minSdkVersion " << minSdkVersion << newLine;
  591. mo << " targetSdkVersion " << targetSdkVersion << newLine;
  592. mo << " externalNativeBuild {" << newLine;
  593. mo << " cmake {" << newLine;
  594. mo << " arguments " << cmakeDefs.joinIntoString (", ") << newLine;
  595. mo << " }" << newLine;
  596. mo << " }" << newLine;
  597. mo << " }" << newLine;
  598. return mo.toString();
  599. }
  600. String getAndroidBuildTypes() const
  601. {
  602. MemoryOutputStream mo;
  603. mo.setNewLineString (getNewLineString());
  604. mo << " buildTypes {" << newLine;
  605. int numDebugConfigs = 0;
  606. auto numConfigs = getNumConfigurations();
  607. for (int i = 0; i < numConfigs; ++i)
  608. {
  609. auto config = getConfiguration(i);
  610. if (config->isDebug()) numDebugConfigs++;
  611. if (numDebugConfigs > 1 || ((numConfigs - numDebugConfigs) > 1))
  612. continue;
  613. mo << " " << (config->isDebug() ? "debug" : "release") << " {" << newLine;
  614. mo << " initWith " << (config->isDebug() ? "debug" : "release") << newLine;
  615. mo << " debuggable " << (config->isDebug() ? "true" : "false") << newLine;
  616. mo << " jniDebuggable " << (config->isDebug() ? "true" : "false") << newLine;
  617. mo << " signingConfig signingConfigs.juceSigning" << newLine;
  618. mo << " }" << newLine;
  619. }
  620. mo << " }" << newLine;
  621. return mo.toString();
  622. }
  623. String getAndroidVariantFilter() const
  624. {
  625. MemoryOutputStream mo;
  626. mo.setNewLineString (getNewLineString());
  627. mo << " variantFilter { variant ->" << newLine;
  628. mo << " def names = variant.flavors*.name" << newLine;
  629. for (ConstConfigIterator config (*this); config.next();)
  630. {
  631. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  632. mo << " if (names.contains (\"" << cfg.getProductFlavourNameIdentifier() << "\")" << newLine;
  633. mo << " && variant.buildType.name != \"" << (cfg.isDebug() ? "debug" : "release") << "\") {" << newLine;
  634. mo << " setIgnore(true)" << newLine;
  635. mo << " }" << newLine;
  636. }
  637. mo << " }" << newLine;
  638. return mo.toString();
  639. }
  640. String getAndroidProjectRepositories() const
  641. {
  642. MemoryOutputStream mo;
  643. mo.setNewLineString (getNewLineString());
  644. auto repositories = StringArray::fromLines (androidProjectRepositories.get().toString());
  645. if (areRemoteNotificationsEnabled())
  646. repositories.add ("maven { url \"https://maven.google.com\" }");
  647. mo << " repositories {" << newLine;
  648. for (auto& r : repositories)
  649. mo << " " << r << newLine;
  650. mo << " }" << newLine;
  651. return mo.toString();
  652. }
  653. String getAndroidRepositories() const
  654. {
  655. MemoryOutputStream mo;
  656. mo.setNewLineString (getNewLineString());
  657. auto repositories = StringArray::fromLines (androidRepositories.get().toString());
  658. mo << " repositories {" << newLine;
  659. for (auto& r : repositories)
  660. mo << " " << r << newLine;
  661. mo << " }" << newLine;
  662. return mo.toString();
  663. }
  664. String getAndroidDependencies() const
  665. {
  666. MemoryOutputStream mo;
  667. mo.setNewLineString (getNewLineString());
  668. mo << " dependencies {" << newLine;
  669. for (auto& d : StringArray::fromLines (androidDependencies.get().toString()))
  670. mo << " " << d << newLine;
  671. for (auto& d : StringArray::fromLines (androidJavaLibs.get().toString()))
  672. mo << " implementation files('libs/" << File (d).getFileName() << "')" << newLine;
  673. if (isInAppBillingEnabled())
  674. mo << " implementation 'com.android.billingclient:billing:2.1.0'" << newLine;
  675. if (areRemoteNotificationsEnabled())
  676. {
  677. mo << " implementation 'com.google.firebase:firebase-core:16.0.1'" << newLine;
  678. mo << " implementation 'com.google.firebase:firebase-messaging:17.6.0'" << newLine;
  679. }
  680. mo << " }" << newLine;
  681. return mo.toString();
  682. }
  683. String getApplyPlugins() const
  684. {
  685. MemoryOutputStream mo;
  686. mo.setNewLineString (getNewLineString());
  687. if (areRemoteNotificationsEnabled())
  688. mo << "apply plugin: 'com.google.gms.google-services'" << newLine;
  689. return mo.toString();
  690. }
  691. void addModuleJavaFolderToSourceSet(StringArray& javaSourceSets, const File& source) const
  692. {
  693. if (source.isDirectory())
  694. {
  695. auto appFolder = getTargetFolder().getChildFile ("app");
  696. build_tools::RelativePath relativePath (source, appFolder, build_tools::RelativePath::buildTargetFolder);
  697. javaSourceSets.add (relativePath.toUnixStyle());
  698. }
  699. }
  700. void addOptJavaFolderToSourceSetsForModule (StringArray& javaSourceSets,
  701. const OwnedArray<LibraryModule>& modules,
  702. const String& moduleID) const
  703. {
  704. for (auto& m : modules)
  705. {
  706. if (m->getID() == moduleID)
  707. {
  708. auto javaFolder = m->getFolder().getChildFile ("native").getChildFile ("javaopt");
  709. addModuleJavaFolderToSourceSet (javaSourceSets, javaFolder.getChildFile ("app"));
  710. return;
  711. }
  712. }
  713. }
  714. String getAndroidJavaSourceSets (const OwnedArray<LibraryModule>& modules) const
  715. {
  716. auto javaSourceSets = getSourceSetArrayFor (androidAdditionalJavaFolders.get().toString());
  717. auto resourceSets = getSourceSetArrayFor (androidAdditionalResourceFolders.get().toString());
  718. for (auto* module : modules)
  719. {
  720. auto javaFolder = module->getFolder().getChildFile ("native").getChildFile ("javacore");
  721. addModuleJavaFolderToSourceSet (javaSourceSets, javaFolder.getChildFile ("init"));
  722. if (! isLibrary())
  723. addModuleJavaFolderToSourceSet (javaSourceSets, javaFolder.getChildFile ("app"));
  724. }
  725. if (isUsingDefaultActivityClass() || isContentSharingEnabled())
  726. addOptJavaFolderToSourceSetsForModule (javaSourceSets, modules, "juce_gui_basics");
  727. if (areRemoteNotificationsEnabled())
  728. addOptJavaFolderToSourceSetsForModule (javaSourceSets, modules, "juce_gui_extra");
  729. if (isInAppBillingEnabled())
  730. addOptJavaFolderToSourceSetsForModule (javaSourceSets, modules, "juce_product_unlocking");
  731. MemoryOutputStream mo;
  732. mo.setNewLineString (getNewLineString());
  733. mo << " sourceSets {" << newLine;
  734. mo << getSourceSetStringFor ("main.java.srcDirs", javaSourceSets, getNewLineString());
  735. mo << newLine;
  736. mo << getSourceSetStringFor ("main.res.srcDirs", resourceSets, getNewLineString());
  737. mo << " }" << newLine;
  738. return mo.toString();
  739. }
  740. StringArray getSourceSetArrayFor (const String& srcDirs) const
  741. {
  742. StringArray sourceSets;
  743. for (auto folder : StringArray::fromLines (srcDirs))
  744. {
  745. if (File::isAbsolutePath (folder))
  746. {
  747. sourceSets.add (folder);
  748. }
  749. else
  750. {
  751. auto appFolder = getTargetFolder().getChildFile ("app");
  752. auto relativePath = build_tools::RelativePath (folder, build_tools::RelativePath::projectFolder)
  753. .rebased (getProject().getProjectFolder(), appFolder,
  754. build_tools::RelativePath::buildTargetFolder);
  755. sourceSets.add (relativePath.toUnixStyle());
  756. }
  757. }
  758. return sourceSets;
  759. }
  760. static String getSourceSetStringFor (const String& type, const StringArray& srcDirs, const String& newLineString)
  761. {
  762. String s;
  763. s << " " << type << " +=" << newLine;
  764. s << " [";
  765. bool isFirst = true;
  766. for (auto sourceSet : srcDirs)
  767. {
  768. if (! isFirst)
  769. s << "," << newLine << " ";
  770. isFirst = false;
  771. s << "\"" << sourceSet << "\"";
  772. }
  773. s << "]" << newLine;
  774. return replaceLineFeeds (s, newLineString);
  775. }
  776. //==============================================================================
  777. String getLocalPropertiesFileContent() const
  778. {
  779. String props;
  780. props << "sdk.dir=" << sanitisePath (getAppSettings().getStoredPath (Ids::androidSDKPath, TargetOS::getThisOS()).get().toString()) << newLine;
  781. return replaceLineFeeds (props, getNewLineString());
  782. }
  783. String getGradleWrapperPropertiesFileContent() const
  784. {
  785. String props;
  786. props << "distributionUrl=https\\://services.gradle.org/distributions/gradle-"
  787. << gradleVersion.get().toString() << "-all.zip";
  788. return props;
  789. }
  790. //==============================================================================
  791. void createBaseExporterProperties (PropertyListBuilder& props)
  792. {
  793. props.add (new TextPropertyComponent (androidAdditionalJavaFolders, "Java Source code folders", 32768, true),
  794. "Folders inside which additional java source files can be found (one per line). For example, if you "
  795. "are using your own Activity you should place the java files for this into a folder and add the folder "
  796. "path to this field.");
  797. props.add (new TextPropertyComponent (androidAdditionalResourceFolders, "Resource folders", 32768, true),
  798. "Folders inside which additional resource files can be found (one per line). For example, if you "
  799. "want to add your own layout xml files then you should place a layout xml file inside a folder and add "
  800. "the folder path to this field.");
  801. props.add (new TextPropertyComponent (androidJavaLibs, "Java libraries to include", 32768, true),
  802. "Java libs (JAR files) (one per line). These will be copied to app/libs folder and \"implementation files\" "
  803. "dependency will be automatically added to module \"dependencies\" section for each library, so do "
  804. "not add the dependency yourself.");
  805. props.add (new TextPropertyComponent (androidProjectRepositories, "Project Repositories", 32768, true),
  806. "Custom project repositories (one per line). These will be used in project-level gradle file "
  807. "\"allprojects { repositories {\" section instead of default ones.");
  808. props.add (new TextPropertyComponent (androidRepositories, "Module Repositories", 32768, true),
  809. "Module repositories (one per line). These will be added to module-level gradle file repositories section. ");
  810. props.add (new TextPropertyComponent (androidDependencies, "Module Dependencies", 32768, true),
  811. "Module dependencies (one per line). These will be added to module-level gradle file \"dependencies\" section. "
  812. "If adding any java libs in \"Java libraries to include\" setting, do not add them here as "
  813. "they will be added automatically.");
  814. props.add (new TextPropertyComponent (androidCustomAppBuildGradleContent, "Extra module's build.gradle content", 32768, true),
  815. "Additional content to be appended to module's build.gradle inside android { section. ");
  816. props.add (new TextPropertyComponent (androidGradleSettingsContent, "Custom gradle.settings content", 32768, true),
  817. "You can customize the content of settings.gradle here");
  818. props.add (new ChoicePropertyComponent (androidScreenOrientation, "Screen Orientation",
  819. { "Portrait and Landscape", "Portrait", "Landscape" },
  820. { "unspecified", "portrait", "landscape" }),
  821. "The screen orientations that this app should support");
  822. props.add (new TextPropertyComponent (androidCustomActivityClass, "Custom Android Activity", 256, false),
  823. "If not empty, specifies the Android Activity class name stored in the app's manifest which "
  824. "should be used instead of Android's default Activity. If you specify a custom Activity "
  825. "then you should implement onNewIntent() function like the one in com.rmsl.juce.JuceActivity, if "
  826. "you wish to be able to handle push notification events.");
  827. props.add (new TextPropertyComponent (androidCustomApplicationClass, "Custom Android Application", 256, false),
  828. "If not empty, specifies the Android Application class name stored in the app's manifest which "
  829. "should be used instead of JUCE's default JuceApp class. If you specify a custom App then you must "
  830. "call com.rmsl.juce.Java.initialiseJUCE somewhere in your code before calling any JUCE functions.");
  831. props.add (new TextPropertyComponent (androidVersionCode, "Android Version Code", 32, false),
  832. "An integer value that represents the version of the application code, relative to other versions.");
  833. props.add (new TextPropertyComponent (androidMinimumSDK, "Minimum SDK Version", 32, false),
  834. "The number of the minimum version of the Android SDK that the app requires (must be 16 or higher).");
  835. props.add (new TextPropertyComponent (androidTargetSDK, "Target SDK Version", 32, false),
  836. "The number of the version of the Android SDK that the app is targeting.");
  837. props.add (new TextPropertyComponent (androidExtraAssetsFolder, "Extra Android Assets", 256, false),
  838. "A path to a folder (relative to the project folder) which contains extra android assets.");
  839. }
  840. //==============================================================================
  841. void createManifestExporterProperties (PropertyListBuilder& props)
  842. {
  843. props.add (new TextPropertyComponent (androidOboeRepositoryPath, "Custom Oboe Repository", 2048, false),
  844. "Path to the root of Oboe repository. This path can be absolute, or relative to the build directory. "
  845. "Make sure to point Oboe repository to commit with SHA c5c3cc17f78974bf005bf33a2de1a093ac55cc07 before building. "
  846. "Leave blank to use the version of Oboe distributed with JUCE.");
  847. props.add (new ChoicePropertyComponent (androidInternetNeeded, "Internet Access"),
  848. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  849. props.add (new ChoicePropertyComponent (androidMicNeeded, "Audio Input Required"),
  850. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  851. props.add (new ChoicePropertyComponent (androidCameraNeeded, "Camera Required"),
  852. "If enabled, this will set the android.permission.CAMERA flag in the manifest.");
  853. props.add (new ChoicePropertyComponent (androidBluetoothNeeded, "Bluetooth Permissions Required"),
  854. "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.");
  855. props.add (new ChoicePropertyComponent (androidExternalReadPermission, "Read From External Storage"),
  856. "If enabled, this will set the android.permission.READ_EXTERNAL_STORAGE flag in the manifest.");
  857. props.add (new ChoicePropertyComponent (androidExternalWritePermission, "Write to External Storage"),
  858. "If enabled, this will set the android.permission.WRITE_EXTERNAL_STORAGE flag in the manifest.");
  859. props.add (new ChoicePropertyComponent (androidInAppBillingPermission, "In-App Billing"),
  860. "If enabled, this will set the com.android.vending.BILLING flag in the manifest.");
  861. props.add (new ChoicePropertyComponent (androidVibratePermission, "Vibrate"),
  862. "If enabled, this will set the android.permission.VIBRATE flag in the manifest.");
  863. props.add (new ChoicePropertyComponent (androidEnableContentSharing, "Content Sharing"),
  864. "If enabled, your app will be able to share content with other apps.");
  865. props.add (new TextPropertyComponent (androidOtherPermissions, "Custom Permissions", 2048, false),
  866. "A space-separated list of other permission flags that should be added to the manifest.");
  867. props.add (new ChoicePropertyComponent (androidPushNotifications, "Push Notifications Capability"),
  868. "Enable this to grant your app the capability to receive push notifications.");
  869. props.add (new ChoicePropertyComponentWithEnablement (androidEnableRemoteNotifications, androidPushNotifications, "Remote Notifications"),
  870. "Enable to be able to send remote notifications to devices running your app (min API level 14). Enable the \"Push Notifications Capability\" "
  871. "setting, provide Remote Notifications Config File, configure your app in Firebase Console and ensure you have the latest Google Repository "
  872. "in Android Studio's SDK Manager.");
  873. props.add (new TextPropertyComponent (androidRemoteNotificationsConfigFile.getPropertyAsValue(), "Remote Notifications Config File", 2048, false),
  874. "Path to google-services.json file. This will be the file provided by Firebase when creating a new app in Firebase console.");
  875. props.add (new TextPropertyComponent (androidManifestCustomXmlElements, "Custom Manifest XML Content", 8192, true),
  876. "You can specify custom AndroidManifest.xml content overriding the default one generated by Projucer. "
  877. "Projucer will automatically create any missing and required XML elements and attributes "
  878. "and merge them into your custom content.");
  879. }
  880. //==============================================================================
  881. void createCodeSigningExporterProperties (PropertyListBuilder& props)
  882. {
  883. props.add (new TextPropertyComponent (androidKeyStore, "Key Signing: key.store", 2048, false),
  884. "The key.store value, used when signing the release package.");
  885. props.add (new TextPropertyComponent (androidKeyStorePass, "Key Signing: key.store.password", 2048, false),
  886. "The key.store password, used when signing the release package.");
  887. props.add (new TextPropertyComponent (androidKeyAlias, "Key Signing: key.alias", 2048, false),
  888. "The key.alias value, used when signing the release package.");
  889. props.add (new TextPropertyComponent (androidKeyAliasPass, "Key Signing: key.alias.password", 2048, false),
  890. "The key.alias password, used when signing the release package.");
  891. }
  892. //==============================================================================
  893. void createOtherExporterProperties (PropertyListBuilder& props)
  894. {
  895. props.add (new TextPropertyComponent (androidTheme, "Android Theme", 256, false),
  896. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  897. }
  898. //==============================================================================
  899. void copyAdditionalJavaLibs (const File& targetFolder) const
  900. {
  901. auto libFolder = targetFolder.getChildFile ("libs");
  902. libFolder.createDirectory();
  903. auto libPaths = StringArray::fromLines (androidJavaLibs.get().toString());
  904. for (auto& p : libPaths)
  905. {
  906. auto f = getTargetFolder().getChildFile (p);
  907. // Is the path to the java lib correct?
  908. jassert (f.existsAsFile());
  909. f.copyFileTo (libFolder.getChildFile (f.getFileName()));
  910. }
  911. }
  912. void copyExtraResourceFiles() const
  913. {
  914. for (ConstConfigIterator config (*this); config.next();)
  915. {
  916. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  917. String cfgPath = cfg.isDebug() ? "app/src/debug" : "app/src/release";
  918. String xmlValuesPath = cfg.isDebug() ? "app/src/debug/res/values" : "app/src/release/res/values";
  919. String drawablesPath = cfg.isDebug() ? "app/src/debug/res" : "app/src/release/res";
  920. String rawPath = cfg.isDebug() ? "app/src/debug/res/raw" : "app/src/release/res/raw";
  921. copyExtraResourceFiles (cfg.getAdditionalXmlResources(), xmlValuesPath);
  922. copyExtraResourceFiles (cfg.getAdditionalDrawableResources(), drawablesPath);
  923. copyExtraResourceFiles (cfg.getAdditionalRawResources(), rawPath);
  924. if (areRemoteNotificationsEnabled())
  925. {
  926. auto remoteNotifsConfigFilePath = cfg.getRemoteNotifsConfigFile();
  927. if (remoteNotifsConfigFilePath.isEmpty())
  928. remoteNotifsConfigFilePath = androidRemoteNotificationsConfigFile.get().toString();
  929. File file (getProject().getFile().getChildFile (remoteNotifsConfigFilePath));
  930. // Settings file must be present for remote notifications to work and it must be called google-services.json.
  931. jassert (file.existsAsFile() && file.getFileName() == "google-services.json");
  932. copyExtraResourceFiles (remoteNotifsConfigFilePath, cfgPath);
  933. }
  934. }
  935. }
  936. void copyExtraResourceFiles (const String& resources, const String& dstRelativePath) const
  937. {
  938. auto resourcePaths = StringArray::fromTokens (resources, true);
  939. auto parentFolder = getTargetFolder().getChildFile (dstRelativePath);
  940. parentFolder.createDirectory();
  941. for (auto& path : resourcePaths)
  942. {
  943. auto file = getProject().getFile().getChildFile (path);
  944. jassert (file.exists());
  945. if (file.exists())
  946. file.copyFileTo (parentFolder.getChildFile (file.getFileName()));
  947. }
  948. }
  949. //==============================================================================
  950. String getActivityClassString() const
  951. {
  952. auto customActivityClass = androidCustomActivityClass.get().toString();
  953. if (customActivityClass.isNotEmpty())
  954. return customActivityClass;
  955. return arePushNotificationsEnabled() ? getDefaultActivityClass() : "android.app.Activity";
  956. }
  957. String getApplicationClassString() const { return androidCustomApplicationClass.get(); }
  958. String getJNIActivityClassName() const { return getActivityClassString().replaceCharacter ('.', '/'); }
  959. bool isUsingDefaultActivityClass() const { return getActivityClassString() == getDefaultActivityClass(); }
  960. //==============================================================================
  961. bool arePushNotificationsEnabled() const
  962. {
  963. return project.getEnabledModules().isModuleEnabled ("juce_gui_extra")
  964. && androidPushNotifications.get();
  965. }
  966. bool areRemoteNotificationsEnabled() const
  967. {
  968. return arePushNotificationsEnabled()
  969. && androidEnableRemoteNotifications.get();
  970. }
  971. bool isInAppBillingEnabled() const
  972. {
  973. return project.getEnabledModules().isModuleEnabled ("juce_product_unlocking")
  974. && androidInAppBillingPermission.get();
  975. }
  976. bool isContentSharingEnabled() const
  977. {
  978. return project.getEnabledModules().isModuleEnabled ("juce_gui_basics")
  979. && androidEnableContentSharing.get();
  980. }
  981. //==============================================================================
  982. String getNativeModuleBinaryName (const AndroidBuildConfiguration& config) const
  983. {
  984. return (isLibrary() ? File::createLegalFileName (config.getTargetBinaryNameString().trim()) : "juce_jni");
  985. }
  986. String getAppPlatform() const
  987. {
  988. return "android-" + androidMinimumSDK.get().toString();
  989. }
  990. static String escapeQuotes (const String& str)
  991. {
  992. return str.replace ("'", "\\'").replace ("\"", "\\\"");
  993. }
  994. //==============================================================================
  995. void writeStringsXML (const File& folder) const
  996. {
  997. for (ConstConfigIterator config (*this); config.next();)
  998. {
  999. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  1000. String customStringsXmlContent ("<resources>\n");
  1001. customStringsXmlContent << "<string name=\"app_name\">" << escapeQuotes (projectName) << "</string>\n";
  1002. customStringsXmlContent << cfg.getCustomStringsXml();
  1003. customStringsXmlContent << "\n</resources>";
  1004. if (auto strings = parseXML (customStringsXmlContent))
  1005. {
  1006. String dir = cfg.isDebug() ? "debug" : "release";
  1007. String subPath = "app/src/" + dir + "/res/values/string.xml";
  1008. writeXmlOrThrow (*strings, folder.getChildFile (subPath), "utf-8", 100, true);
  1009. }
  1010. else
  1011. {
  1012. jassertfalse; // needs handling?
  1013. }
  1014. }
  1015. }
  1016. void writeAndroidManifest (const File& folder) const
  1017. {
  1018. std::unique_ptr<XmlElement> manifest (createManifestXML());
  1019. writeXmlOrThrow (*manifest, folder.getChildFile ("src/main/AndroidManifest.xml"), "utf-8", 100, true);
  1020. }
  1021. void writeIcon (const File& file, const Image& im) const
  1022. {
  1023. if (im.isValid())
  1024. {
  1025. createDirectoryOrThrow (file.getParentDirectory());
  1026. build_tools::writeStreamToFile (file, [&] (MemoryOutputStream& mo)
  1027. {
  1028. mo.setNewLineString (getNewLineString());
  1029. PNGImageFormat png;
  1030. if (! png.writeImageToStream (im, mo))
  1031. throw build_tools::SaveError ("Can't generate Android icon file");
  1032. });
  1033. }
  1034. }
  1035. void writeIcons (const File& folder) const
  1036. {
  1037. const auto icons = getIcons();
  1038. if (icons.big != nullptr && icons.small != nullptr)
  1039. {
  1040. auto step = jmax (icons.big->getWidth(), icons.big->getHeight()) / 8;
  1041. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), build_tools::getBestIconForSize (icons, step * 8, false));
  1042. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), build_tools::getBestIconForSize (icons, step * 6, false));
  1043. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), build_tools::getBestIconForSize (icons, step * 4, false));
  1044. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), build_tools::getBestIconForSize (icons, step * 3, false));
  1045. }
  1046. else if (auto* icon = (icons.big != nullptr ? icons.big.get() : icons.small.get()))
  1047. {
  1048. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), build_tools::rescaleImageForIcon (*icon, icon->getWidth()));
  1049. }
  1050. }
  1051. void writeAppIcons (const File& folder) const
  1052. {
  1053. writeIcons (folder.getChildFile ("app/src/main/res/"));
  1054. }
  1055. static String sanitisePath (String path)
  1056. {
  1057. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  1058. }
  1059. static String expandHomeFolderToken (const String& path)
  1060. {
  1061. auto homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  1062. return path.replace ("${user.home}", homeFolder)
  1063. .replace ("~", homeFolder);
  1064. }
  1065. //==============================================================================
  1066. void addCompileUnits (const Project::Item& projectItem, MemoryOutputStream& mo,
  1067. Array<build_tools::RelativePath>& excludeFromBuild, Array<std::pair<build_tools::RelativePath, String>>& extraCompilerFlags) const
  1068. {
  1069. if (projectItem.isGroup())
  1070. {
  1071. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  1072. addCompileUnits (projectItem.getChild (i), mo, excludeFromBuild, extraCompilerFlags);
  1073. }
  1074. else if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (*this))
  1075. {
  1076. auto f = projectItem.getFile();
  1077. build_tools::RelativePath file (f, getTargetFolder().getChildFile ("app"), build_tools::RelativePath::buildTargetFolder);
  1078. auto targetType = getProject().getTargetTypeFromFilePath (f, true);
  1079. mo << " \"" << file.toUnixStyle() << "\"" << newLine;
  1080. if ((! projectItem.shouldBeCompiled()) || (! shouldFileBeCompiledByDefault (f))
  1081. || (getProject().isAudioPluginProject()
  1082. && targetType != build_tools::ProjectType::Target::SharedCodeTarget
  1083. && targetType != build_tools::ProjectType::Target::StandalonePlugIn))
  1084. {
  1085. excludeFromBuild.add (file);
  1086. }
  1087. else
  1088. {
  1089. auto extraFlags = compilerFlagSchemesMap[projectItem.getCompilerFlagSchemeString()].get().toString();
  1090. if (extraFlags.isNotEmpty())
  1091. extraCompilerFlags.add ({ file, extraFlags });
  1092. }
  1093. }
  1094. }
  1095. void addCompileUnits (MemoryOutputStream& mo, Array<build_tools::RelativePath>& excludeFromBuild,
  1096. Array<std::pair<build_tools::RelativePath, String>>& extraCompilerFlags) const
  1097. {
  1098. for (int i = 0; i < getAllGroups().size(); ++i)
  1099. addCompileUnits (getAllGroups().getReference(i), mo, excludeFromBuild, extraCompilerFlags);
  1100. }
  1101. //==============================================================================
  1102. StringArray getCmakeDefinitions() const
  1103. {
  1104. auto toolchain = gradleToolchain.get().toString();
  1105. bool isClang = (toolchain == "clang");
  1106. StringArray cmakeArgs;
  1107. cmakeArgs.add ("\"-DANDROID_TOOLCHAIN=" + toolchain + "\"");
  1108. cmakeArgs.add ("\"-DANDROID_PLATFORM=" + getAppPlatform() + "\"");
  1109. cmakeArgs.add (String ("\"-DANDROID_STL=") + (isClang ? "c++_static" : "gnustl_static") + "\"");
  1110. cmakeArgs.add ("\"-DANDROID_CPP_FEATURES=exceptions rtti\"");
  1111. cmakeArgs.add ("\"-DANDROID_ARM_MODE=arm\"");
  1112. cmakeArgs.add ("\"-DANDROID_ARM_NEON=TRUE\"");
  1113. auto cppStandard = [this]
  1114. {
  1115. auto projectStandard = project.getCppStandardString();
  1116. if (projectStandard == "latest")
  1117. return project.getLatestNumberedCppStandardString();
  1118. return projectStandard;
  1119. }();
  1120. cmakeArgs.add ("\"-DCMAKE_CXX_STANDARD=" + cppStandard + "\"");
  1121. cmakeArgs.add ("\"-DCMAKE_CXX_EXTENSIONS=" + String (shouldUseGNUExtensions() ? "ON" : "OFF") + "\"");
  1122. return cmakeArgs;
  1123. }
  1124. //==============================================================================
  1125. StringArray getAndroidCompilerFlags() const
  1126. {
  1127. StringArray cFlags;
  1128. cFlags.add ("\"-fsigned-char\"");
  1129. return cFlags;
  1130. }
  1131. StringArray getProjectCompilerFlags() const
  1132. {
  1133. auto cFlags = getAndroidCompilerFlags();
  1134. cFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  1135. return cFlags;
  1136. }
  1137. //==============================================================================
  1138. StringPairArray getAndroidPreprocessorDefs() const
  1139. {
  1140. StringPairArray defines;
  1141. defines.set ("JUCE_ANDROID", "1");
  1142. defines.set ("JUCE_ANDROID_API_VERSION", androidMinimumSDK.get());
  1143. if (arePushNotificationsEnabled())
  1144. {
  1145. defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");
  1146. defines.set ("JUCE_PUSH_NOTIFICATIONS_ACTIVITY", getJNIActivityClassName().quoted());
  1147. }
  1148. if (isInAppBillingEnabled())
  1149. defines.set ("JUCE_IN_APP_PURCHASES", "1");
  1150. if (isContentSharingEnabled())
  1151. defines.set ("JUCE_CONTENT_SHARING", "1");
  1152. if (supportsGLv3())
  1153. defines.set ("JUCE_ANDROID_GL_ES_VERSION_3_0", "1");
  1154. if (areRemoteNotificationsEnabled())
  1155. {
  1156. defines.set ("JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME", "com_rmsl_juce_JuceFirebaseInstanceIdService");
  1157. defines.set ("JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME", "com_rmsl_juce_JuceFirebaseMessagingService");
  1158. }
  1159. return defines;
  1160. }
  1161. StringPairArray getProjectPreprocessorDefs() const
  1162. {
  1163. auto defines = getAndroidPreprocessorDefs();
  1164. return mergePreprocessorDefs (defines, getAllPreprocessorDefs());
  1165. }
  1166. StringPairArray getConfigPreprocessorDefs (const BuildConfiguration& config) const
  1167. {
  1168. auto cfgDefines = getAllPreprocessorDefs (config, build_tools::ProjectType::Target::unspecified);
  1169. if (config.isDebug())
  1170. {
  1171. cfgDefines.set ("DEBUG", "1");
  1172. cfgDefines.set ("_DEBUG", "1");
  1173. }
  1174. else
  1175. {
  1176. cfgDefines.set ("NDEBUG", "1");
  1177. }
  1178. return cfgDefines;
  1179. }
  1180. //==============================================================================
  1181. StringArray getUserLibraries() const
  1182. {
  1183. auto userLibraries = StringArray::fromTokens (getExternalLibrariesString(), ";", "");
  1184. userLibraries = getCleanedStringArray (userLibraries);
  1185. const auto ppDefs = getAllPreprocessorDefs();
  1186. for (auto& lib : userLibraries)
  1187. lib = build_tools::replacePreprocessorDefs (ppDefs, lib);
  1188. userLibraries.addArray (androidLibs);
  1189. return userLibraries;
  1190. }
  1191. StringArray getAndroidLibraries() const
  1192. {
  1193. StringArray libraries;
  1194. libraries.add ("log");
  1195. libraries.add ("android");
  1196. libraries.add (supportsGLv3() ? "GLESv3" : "GLESv2");
  1197. libraries.add ("EGL");
  1198. return libraries;
  1199. }
  1200. //==============================================================================
  1201. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  1202. {
  1203. auto paths = extraSearchPaths;
  1204. paths.addArray (config.getHeaderSearchPaths());
  1205. paths = getCleanedStringArray (paths);
  1206. return paths;
  1207. }
  1208. //==============================================================================
  1209. String escapeDirectoryForCmake (const String& path) const
  1210. {
  1211. auto relative =
  1212. build_tools::RelativePath (path, build_tools::RelativePath::buildTargetFolder)
  1213. .rebased (getTargetFolder(), getTargetFolder().getChildFile ("app"), build_tools::RelativePath::buildTargetFolder);
  1214. return relative.toUnixStyle();
  1215. }
  1216. void writeCmakePathLines (MemoryOutputStream& mo, const String& prefix, const String& firstLine, const StringArray& paths,
  1217. const String& suffix = ")") const
  1218. {
  1219. if (paths.size() > 0)
  1220. {
  1221. mo << prefix << firstLine << newLine;
  1222. for (auto& path : paths)
  1223. mo << prefix << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  1224. mo << prefix << suffix << newLine << newLine;
  1225. }
  1226. }
  1227. static StringArray getEscapedPreprocessorDefs (const StringPairArray& defs)
  1228. {
  1229. StringArray escapedDefs;
  1230. for (int i = 0; i < defs.size(); ++i)
  1231. {
  1232. auto escaped = "[[-D" + defs.getAllKeys()[i];
  1233. auto value = defs.getAllValues()[i];
  1234. if (value.isNotEmpty())
  1235. escaped += ("=" + value);
  1236. escapedDefs.add (escaped + "]]");
  1237. }
  1238. return escapedDefs;
  1239. }
  1240. static StringArray getEscapedFlags (const StringArray& flags)
  1241. {
  1242. StringArray escaped;
  1243. for (auto& flag : flags)
  1244. escaped.add ("[[" + flag + "]]");
  1245. return escaped;
  1246. }
  1247. //==============================================================================
  1248. std::unique_ptr<XmlElement> createManifestXML() const
  1249. {
  1250. auto manifest = createManifestElement();
  1251. createSupportsScreensElement (*manifest);
  1252. createPermissionElements (*manifest);
  1253. createOpenGlFeatureElement (*manifest);
  1254. if (! isLibrary())
  1255. {
  1256. auto* app = createApplicationElement (*manifest);
  1257. auto* act = createActivityElement (*app);
  1258. createIntentElement (*act);
  1259. createServiceElements (*app);
  1260. createProviderElement (*app);
  1261. }
  1262. return manifest;
  1263. }
  1264. std::unique_ptr<XmlElement> createManifestElement() const
  1265. {
  1266. auto manifest = parseXML (androidManifestCustomXmlElements.get());
  1267. if (manifest == nullptr)
  1268. manifest = std::make_unique<XmlElement> ("manifest");
  1269. setAttributeIfNotPresent (*manifest, "xmlns:android", "http://schemas.android.com/apk/res/android");
  1270. setAttributeIfNotPresent (*manifest, "android:versionCode", androidVersionCode.get());
  1271. setAttributeIfNotPresent (*manifest, "android:versionName", project.getVersionString());
  1272. setAttributeIfNotPresent (*manifest, "package", project.getBundleIdentifierString().toLowerCase());
  1273. return manifest;
  1274. }
  1275. void createSupportsScreensElement (XmlElement& manifest) const
  1276. {
  1277. if (! isLibrary())
  1278. {
  1279. if (manifest.getChildByName ("supports-screens") == nullptr)
  1280. {
  1281. auto* screens = manifest.createNewChildElement ("supports-screens");
  1282. screens->setAttribute ("android:smallScreens", "true");
  1283. screens->setAttribute ("android:normalScreens", "true");
  1284. screens->setAttribute ("android:largeScreens", "true");
  1285. screens->setAttribute ("android:anyDensity", "true");
  1286. screens->setAttribute ("android:xlargeScreens", "true");
  1287. }
  1288. }
  1289. }
  1290. void createPermissionElements (XmlElement& manifest) const
  1291. {
  1292. auto permissions = getPermissionsRequired();
  1293. for (auto* child : manifest.getChildWithTagNameIterator ("uses-permission"))
  1294. {
  1295. permissions.removeString (child->getStringAttribute ("android:name"), false);
  1296. }
  1297. for (int i = permissions.size(); --i >= 0;)
  1298. manifest.createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  1299. }
  1300. void createOpenGlFeatureElement (XmlElement& manifest) const
  1301. {
  1302. if (project.getEnabledModules().isModuleEnabled ("juce_opengl"))
  1303. {
  1304. XmlElement* glVersion = nullptr;
  1305. for (auto* child : manifest.getChildWithTagNameIterator ("uses-feature"))
  1306. {
  1307. if (child->getStringAttribute ("android:glEsVersion").isNotEmpty())
  1308. {
  1309. glVersion = child;
  1310. break;
  1311. }
  1312. }
  1313. if (glVersion == nullptr)
  1314. glVersion = manifest.createNewChildElement ("uses-feature");
  1315. setAttributeIfNotPresent (*glVersion, "android:glEsVersion", (static_cast<int> (androidMinimumSDK.get()) >= 18 ? "0x00030000" : "0x00020000"));
  1316. setAttributeIfNotPresent (*glVersion, "android:required", "true");
  1317. }
  1318. }
  1319. XmlElement* createApplicationElement (XmlElement& manifest) const
  1320. {
  1321. auto* app = getOrCreateChildWithName (manifest, "application");
  1322. setAttributeIfNotPresent (*app, "android:label", "@string/app_name");
  1323. setAttributeIfNotPresent (*app, "android:name", getApplicationClassString());
  1324. if (androidTheme.get().toString().isNotEmpty())
  1325. setAttributeIfNotPresent (*app, "android:theme", androidTheme.get());
  1326. if (! app->hasAttribute ("android:icon"))
  1327. {
  1328. std::unique_ptr<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  1329. if (bigIcon != nullptr || smallIcon != nullptr)
  1330. app->setAttribute ("android:icon", "@drawable/icon");
  1331. }
  1332. if (! app->hasAttribute ("android:hardwareAccelerated"))
  1333. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  1334. return app;
  1335. }
  1336. XmlElement* createActivityElement (XmlElement& application) const
  1337. {
  1338. auto* act = getOrCreateChildWithName (application, "activity");
  1339. setAttributeIfNotPresent (*act, "android:name", getActivityClassString());
  1340. setAttributeIfNotPresent (*act, "android:label", "@string/app_name");
  1341. if (! act->hasAttribute ("android:configChanges"))
  1342. act->setAttribute ("android:configChanges", "keyboardHidden|orientation|screenSize");
  1343. if (androidScreenOrientation.get() == "landscape")
  1344. {
  1345. setAttributeIfNotPresent (*act, "android:screenOrientation",
  1346. static_cast<int> (androidMinimumSDK.get()) < 18 ? "sensorLandscape" : "userLandscape");
  1347. }
  1348. else
  1349. {
  1350. setAttributeIfNotPresent (*act, "android:screenOrientation", androidScreenOrientation.get());
  1351. }
  1352. setAttributeIfNotPresent (*act, "android:launchMode", "singleTask");
  1353. // Using the 2D acceleration slows down OpenGL. We *do* enable it here for the activity though, and we disable it
  1354. // in each ComponentPeerView instead. This way any embedded native views, which are not children of ComponentPeerView,
  1355. // can still use hardware acceleration if needed (e.g. web view).
  1356. if (! act->hasAttribute ("android:hardwareAccelerated"))
  1357. act->setAttribute ("android:hardwareAccelerated", "true"); // (using the 2D acceleration slows down openGL)
  1358. act->setAttribute ("android:exported", "true");
  1359. return act;
  1360. }
  1361. void createIntentElement (XmlElement& application) const
  1362. {
  1363. auto* intent = getOrCreateChildWithName (application, "intent-filter");
  1364. auto* action = getOrCreateChildWithName (*intent, "action");
  1365. setAttributeIfNotPresent (*action, "android:name", "android.intent.action.MAIN");
  1366. auto* category = getOrCreateChildWithName (*intent, "category");
  1367. setAttributeIfNotPresent (*category, "android:name", "android.intent.category.LAUNCHER");
  1368. }
  1369. void createServiceElements (XmlElement& application) const
  1370. {
  1371. if (areRemoteNotificationsEnabled())
  1372. {
  1373. auto* service = application.createNewChildElement ("service");
  1374. service->setAttribute ("android:name", "com.rmsl.juce.JuceFirebaseMessagingService");
  1375. auto* intentFilter = service->createNewChildElement ("intent-filter");
  1376. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.MESSAGING_EVENT");
  1377. service = application.createNewChildElement ("service");
  1378. service->setAttribute ("android:name", "com.rmsl.juce.JuceFirebaseInstanceIdService");
  1379. intentFilter = service->createNewChildElement ("intent-filter");
  1380. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.INSTANCE_ID_EVENT");
  1381. auto* metaData = application.createNewChildElement ("meta-data");
  1382. metaData->setAttribute ("android:name", "firebase_analytics_collection_deactivated");
  1383. metaData->setAttribute ("android:value", "true");
  1384. }
  1385. }
  1386. void createProviderElement (XmlElement& application) const
  1387. {
  1388. if (isContentSharingEnabled())
  1389. {
  1390. auto* provider = application.createNewChildElement ("provider");
  1391. provider->setAttribute ("android:name", "com.rmsl.juce.JuceSharingContentProvider");
  1392. provider->setAttribute ("android:authorities", project.getBundleIdentifierString().toLowerCase() + ".sharingcontentprovider");
  1393. provider->setAttribute ("android:grantUriPermissions", "true");
  1394. provider->setAttribute ("android:exported", "true");
  1395. }
  1396. }
  1397. static XmlElement* getOrCreateChildWithName (XmlElement& element, const String& childName)
  1398. {
  1399. auto* child = element.getChildByName (childName);
  1400. if (child == nullptr)
  1401. child = element.createNewChildElement (childName);
  1402. return child;
  1403. }
  1404. static void setAttributeIfNotPresent (XmlElement& element, const Identifier& attribute, const String& value)
  1405. {
  1406. if (! element.hasAttribute (attribute.toString()))
  1407. element.setAttribute (attribute, value);
  1408. }
  1409. StringArray getPermissionsRequired() const
  1410. {
  1411. StringArray s = StringArray::fromTokens (androidOtherPermissions.get().toString(), ", ", {});
  1412. if (androidInternetNeeded.get())
  1413. {
  1414. s.add ("android.permission.INTERNET");
  1415. s.add ("android.permission.CHANGE_WIFI_MULTICAST_STATE");
  1416. }
  1417. if (androidMicNeeded.get())
  1418. s.add ("android.permission.RECORD_AUDIO");
  1419. if (androidCameraNeeded.get())
  1420. s.add ("android.permission.CAMERA");
  1421. if (androidBluetoothNeeded.get())
  1422. {
  1423. s.add ("android.permission.BLUETOOTH");
  1424. s.add ("android.permission.BLUETOOTH_ADMIN");
  1425. s.add ("android.permission.ACCESS_FINE_LOCATION");
  1426. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  1427. }
  1428. if (androidExternalReadPermission.get())
  1429. s.add ("android.permission.READ_EXTERNAL_STORAGE");
  1430. if (androidExternalWritePermission.get())
  1431. s.add ("android.permission.WRITE_EXTERNAL_STORAGE");
  1432. if (isInAppBillingEnabled())
  1433. s.add ("com.android.vending.BILLING");
  1434. if (androidVibratePermission.get())
  1435. s.add ("android.permission.VIBRATE");
  1436. return getCleanedStringArray (s);
  1437. }
  1438. //==============================================================================
  1439. bool isLibrary() const
  1440. {
  1441. return getProject().getProjectType().isDynamicLibrary()
  1442. || getProject().getProjectType().isStaticLibrary();
  1443. }
  1444. static String toGradleList (const StringArray& array)
  1445. {
  1446. StringArray escapedArray;
  1447. for (auto element : array)
  1448. escapedArray.add ("\"" + element.replace ("\\", "\\\\").replace ("\"", "\\\"") + "\"");
  1449. return escapedArray.joinIntoString (", ");
  1450. }
  1451. bool supportsGLv3() const
  1452. {
  1453. return (static_cast<int> (androidMinimumSDK.get()) >= 18);
  1454. }
  1455. //==============================================================================
  1456. const File AndroidExecutable;
  1457. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  1458. };