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.

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