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.

1832 lines
85KB

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