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.

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