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.

1945 lines
90KB

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