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.

1884 lines
89KB

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