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.

1944 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.1"),
  123. gradleToolchain (settings, Ids::gradleToolchain, getUndoManager(), "clang"),
  124. androidPluginVersion (settings, Ids::androidPluginVersion, getUndoManager(), "3.0.1"),
  125. buildToolsVersion (settings, Ids::buildToolsVersion, getUndoManager(), "27.0.0"),
  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 (3.3 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 << " jcenter()" << newLine;
  463. mo << " google()" << 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 << " jcenter()" << newLine;
  475. if (androidEnableRemoteNotifications.get())
  476. {
  477. mo << " maven {" << newLine;
  478. mo << " url \"https://maven.google.com\"" << newLine;
  479. mo << " }" << newLine;
  480. }
  481. mo << " }" << newLine;
  482. mo << "}" << newLine;
  483. return mo.toString();
  484. }
  485. //==============================================================================
  486. String getAppBuildGradleFileContent() const
  487. {
  488. MemoryOutputStream mo;
  489. mo << "apply plugin: 'com.android." << (isLibrary() ? "library" : "application") << "'" << newLine << newLine;
  490. mo << "android {" << newLine;
  491. mo << " compileSdkVersion " << static_cast<int> (androidMinimumSDK.get()) << newLine;
  492. mo << " buildToolsVersion \"" << buildToolsVersion.get().toString() << "\"" << newLine;
  493. mo << " externalNativeBuild {" << newLine;
  494. mo << " cmake {" << newLine;
  495. mo << " path \"CMakeLists.txt\"" << newLine;
  496. mo << " }" << newLine;
  497. mo << " }" << newLine;
  498. mo << getAndroidSigningConfig() << newLine;
  499. mo << getAndroidDefaultConfig() << newLine;
  500. mo << getAndroidBuildTypes() << newLine;
  501. mo << getAndroidProductFlavours() << newLine;
  502. mo << getAndroidVariantFilter() << newLine;
  503. mo << getAndroidRepositories() << newLine;
  504. mo << getAndroidDependencies() << newLine;
  505. mo << getApplyPlugins() << newLine;
  506. mo << "}" << newLine << newLine;
  507. return mo.toString();
  508. }
  509. String getAndroidProductFlavours() const
  510. {
  511. MemoryOutputStream mo;
  512. mo << " flavorDimensions \"default\"" << newLine;
  513. mo << " productFlavors {" << newLine;
  514. for (ConstConfigIterator config (*this); config.next();)
  515. {
  516. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  517. mo << " " << cfg.getProductFlavourNameIdentifier() << " {" << newLine;
  518. if (cfg.getArchitectures().isNotEmpty())
  519. {
  520. mo << " ndk {" << newLine;
  521. mo << " abiFilters " << toGradleList (StringArray::fromTokens (cfg.getArchitectures(), " ", "")) << newLine;
  522. mo << " }" << newLine;
  523. }
  524. mo << " externalNativeBuild {" << newLine;
  525. mo << " cmake {" << newLine;
  526. if (getProject().getProjectType().isStaticLibrary())
  527. mo << " targets \"" << getNativeModuleBinaryName (cfg) << "\"" << newLine;
  528. mo << " arguments \"-DJUCE_BUILD_CONFIGURATION=" << cfg.getProductFlavourCMakeIdentifier() << "\""
  529. << ", \"-DCMAKE_CXX_FLAGS_" << (cfg.isDebug() ? "DEBUG" : "RELEASE")
  530. << "=-O" << cfg.getGCCOptimisationFlag() << "\""
  531. << ", \"-DCMAKE_C_FLAGS_" << (cfg.isDebug() ? "DEBUG" : "RELEASE")
  532. << "=-O" << cfg.getGCCOptimisationFlag() << "\"" << newLine;
  533. mo << " }" << newLine;
  534. mo << " }" << newLine << newLine;
  535. mo << " dimension \"default\"" << newLine;
  536. mo << " }" << newLine;
  537. }
  538. mo << " }" << newLine;
  539. return mo.toString();
  540. }
  541. String getAndroidSigningConfig() const
  542. {
  543. MemoryOutputStream mo;
  544. auto keyStoreFilePath = androidKeyStore.get().toString().replace ("${user.home}", "${System.properties['user.home']}")
  545. .replace ("/", "${File.separator}");
  546. mo << " signingConfigs {" << newLine;
  547. mo << " juceSigning {" << newLine;
  548. mo << " storeFile file(\"" << keyStoreFilePath << "\")" << newLine;
  549. mo << " storePassword \"" << androidKeyStorePass.get().toString() << "\"" << newLine;
  550. mo << " keyAlias \"" << androidKeyAlias.get().toString() << "\"" << newLine;
  551. mo << " keyPassword \"" << androidKeyAliasPass.get().toString() << "\"" << newLine;
  552. mo << " storeType \"jks\"" << newLine;
  553. mo << " }" << newLine;
  554. mo << " }" << newLine;
  555. return mo.toString();
  556. }
  557. String getAndroidDefaultConfig() const
  558. {
  559. auto bundleIdentifier = project.getBundleIdentifierString().toLowerCase();
  560. auto cmakeDefs = getCmakeDefinitions();
  561. auto cFlags = getProjectCompilerFlags();
  562. auto cxxFlags = getProjectCxxCompilerFlags();
  563. auto minSdkVersion = static_cast<int> (androidMinimumSDK.get());
  564. MemoryOutputStream mo;
  565. mo << " defaultConfig {" << newLine;
  566. if (! isLibrary())
  567. mo << " applicationId \"" << bundleIdentifier << "\"" << newLine;
  568. mo << " minSdkVersion " << minSdkVersion << newLine;
  569. mo << " targetSdkVersion " << minSdkVersion << newLine;
  570. mo << " externalNativeBuild {" << newLine;
  571. mo << " cmake {" << newLine;
  572. mo << " arguments " << cmakeDefs.joinIntoString (", ") << newLine;
  573. if (cFlags.size() > 0)
  574. mo << " cFlags " << cFlags.joinIntoString (", ") << newLine;
  575. if (cxxFlags.size() > 0)
  576. mo << " cppFlags " << cxxFlags.joinIntoString (", ") << newLine;
  577. mo << " }" << newLine;
  578. mo << " }" << newLine;
  579. mo << " }" << newLine;
  580. return mo.toString();
  581. }
  582. String getAndroidBuildTypes() const
  583. {
  584. MemoryOutputStream mo;
  585. mo << " buildTypes {" << newLine;
  586. int numDebugConfigs = 0;
  587. auto numConfigs = getNumConfigurations();
  588. for (int i = 0; i < numConfigs; ++i)
  589. {
  590. auto config = getConfiguration(i);
  591. if (config->isDebug()) numDebugConfigs++;
  592. if (numDebugConfigs > 1 || ((numConfigs - numDebugConfigs) > 1))
  593. continue;
  594. mo << " " << (config->isDebug() ? "debug" : "release") << " {" << newLine;
  595. mo << " initWith " << (config->isDebug() ? "debug" : "release") << newLine;
  596. mo << " debuggable " << (config->isDebug() ? "true" : "false") << newLine;
  597. mo << " jniDebuggable " << (config->isDebug() ? "true" : "false") << newLine;
  598. mo << " signingConfig signingConfigs.juceSigning" << newLine;
  599. mo << " }" << newLine;
  600. }
  601. mo << " }" << newLine;
  602. return mo.toString();
  603. }
  604. String getAndroidVariantFilter() const
  605. {
  606. MemoryOutputStream mo;
  607. mo << " variantFilter { variant ->" << newLine;
  608. mo << " def names = variant.flavors*.name" << newLine;
  609. for (ConstConfigIterator config (*this); config.next();)
  610. {
  611. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  612. mo << " if (names.contains (\"" << cfg.getProductFlavourNameIdentifier() << "\")" << newLine;
  613. mo << " && variant.buildType.name != \"" << (cfg.isDebug() ? "debug" : "release") << "\") {" << newLine;
  614. mo << " setIgnore(true)" << newLine;
  615. mo << " }" << newLine;
  616. }
  617. mo << " }" << newLine;
  618. return mo.toString();
  619. }
  620. String getAndroidRepositories() const
  621. {
  622. MemoryOutputStream mo;
  623. auto repositories = StringArray::fromLines (androidRepositories.get().toString());
  624. mo << "repositories {" << newLine;
  625. for (auto& r : repositories)
  626. mo << " " << r << newLine;
  627. mo << "}" << newLine;
  628. return mo.toString();
  629. }
  630. String getAndroidDependencies() const
  631. {
  632. MemoryOutputStream mo;
  633. mo << "dependencies {" << newLine;
  634. for (auto& d : StringArray::fromLines (androidDependencies.get().toString()))
  635. mo << " " << d << newLine;
  636. for (auto& d : StringArray::fromLines (androidJavaLibs.get().toString()))
  637. mo << " implementation files('libs/" << File (d).getFileName() << "')" << newLine;
  638. if (androidEnableRemoteNotifications.get())
  639. {
  640. mo << " 'com.google.firebase:firebase-core:11.4.0'" << newLine;
  641. mo << " compile 'com.google.firebase:firebase-messaging:11.4.0'" << newLine;
  642. }
  643. mo << "}" << newLine;
  644. return mo.toString();
  645. }
  646. String getApplyPlugins() const
  647. {
  648. MemoryOutputStream mo;
  649. if (androidEnableRemoteNotifications.get())
  650. mo << "apply plugin: 'com.google.gms.google-services'" << newLine;
  651. return mo.toString();
  652. }
  653. //==============================================================================
  654. String getLocalPropertiesFileContent() const
  655. {
  656. String props;
  657. props << "ndk.dir=" << sanitisePath (ndkPath.toString()) << newLine
  658. << "sdk.dir=" << sanitisePath (sdkPath.toString()) << newLine;
  659. return props;
  660. }
  661. String getGradleWrapperPropertiesFileContent() const
  662. {
  663. String props;
  664. props << "distributionUrl=https\\://services.gradle.org/distributions/gradle-"
  665. << gradleVersion.get().toString() << "-all.zip";
  666. return props;
  667. }
  668. //==============================================================================
  669. void createBaseExporterProperties (PropertyListBuilder& props)
  670. {
  671. props.add (new TextPropertyComponent (androidJavaLibs, "Java libraries to include", 32768, true),
  672. "Java libs (JAR files) (one per line). These will be copied to app/libs folder and \"implementation files\" "
  673. "dependency will be automatically added to module \"dependencies\" section for each library, so do "
  674. "not add the dependency yourself.");
  675. props.add (new TextPropertyComponent (androidRepositories, "Module repositories", 32768, true),
  676. "Module repositories (one per line). These will be added to module-level gradle file repositories section. ");
  677. props.add (new TextPropertyComponent (androidDependencies, "Module dependencies", 32768, true),
  678. "Module dependencies (one per line). These will be added to module-level gradle file \"dependencies\" section. "
  679. "If adding any java libs in \"Java libraries to include\" setting, do not add them here as "
  680. "they will be added automatically.");
  681. props.add (new ChoicePropertyComponent (androidScreenOrientation, "Screen orientation",
  682. { "Portrait and Landscape", "Portrait", "Landscape" },
  683. { "unspecified", "portrait", "landscape" }),
  684. "The screen orientations that this app should support");
  685. props.add (new TextPropertyComponent (androidActivityClass, "Android Activity class name", 256, false),
  686. "The full java class name to use for the app's Activity class.");
  687. props.add (new TextPropertyComponent (androidActivitySubClassName, "Android Activity sub-class name", 256, false),
  688. "If not empty, specifies the Android Activity class name stored in the app's manifest. "
  689. "Use this if you would like to use your own Android Activity sub-class.");
  690. props.add (new TextPropertyComponent (androidActivityBaseClassName, "Android Activity base class", 256, false),
  691. "If not empty, specifies the base class to use for your activity. If custom base class is "
  692. "specified, that base class should be a sub-class of android.app.Activity. When empty, Activity "
  693. "(android.app.Activity) will be used as the base class. "
  694. "Use this if you would like to use your own Android Activity base class.");
  695. props.add (new TextPropertyComponent (androidVersionCode, "Android Version Code", 32, false),
  696. "An integer value that represents the version of the application code, relative to other versions.");
  697. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), sdkPath, "Android SDK Path"),
  698. "The path to the Android SDK folder on the target build machine");
  699. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), ndkPath, "Android NDK Path"),
  700. "The path to the Android NDK folder on the target build machine");
  701. props.add (new TextPropertyComponent (androidMinimumSDK, "Minimum SDK version", 32, false),
  702. "The number of the minimum version of the Android SDK that the app requires");
  703. props.add (new TextPropertyComponent (androidExtraAssetsFolder, "Extra Android Assets", 256, false),
  704. "A path to a folder (relative to the project folder) which contains extra android assets.");
  705. }
  706. //==============================================================================
  707. void createManifestExporterProperties (PropertyListBuilder& props)
  708. {
  709. props.add (new TextPropertyComponent (androidOboeRepositoryPath, "Oboe repository path", 2048, false),
  710. "Path to the root of Oboe repository. Make sure to point Oboe repository to "
  711. "commit with SHA 44c6b6ea9c8fa9b5b74cbd60f355068b57b50b37 before building.");
  712. props.add (new ChoicePropertyComponent (androidInternetNeeded, "Internet Access"),
  713. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  714. props.add (new ChoicePropertyComponent (androidMicNeeded, "Audio Input Required"),
  715. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  716. props.add (new ChoicePropertyComponent (androidBluetoothNeeded, "Bluetooth permissions Required"),
  717. "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.");
  718. props.add (new ChoicePropertyComponent (androidExternalReadPermission, "Read from external storage"),
  719. "If enabled, this will set the android.permission.READ_EXTERNAL_STORAGE flag in the manifest.");
  720. props.add (new ChoicePropertyComponent (androidExternalWritePermission, "Write to external storage"),
  721. "If enabled, this will set the android.permission.WRITE_EXTERNAL_STORAGE flag in the manifest.");
  722. props.add (new ChoicePropertyComponent (androidInAppBillingPermission, "In-App Billing"),
  723. "If enabled, this will set the com.android.vending.BILLING flag in the manifest.");
  724. props.add (new ChoicePropertyComponent (androidVibratePermission, "Vibrate"),
  725. "If enabled, this will set the android.permission.VIBRATE flag in the manifest.");
  726. props.add (new ChoicePropertyComponent (androidEnableContentSharing, "Content Sharing"),
  727. "If enabled, your app will be able to share content with other apps.");
  728. props.add (new TextPropertyComponent (androidOtherPermissions, "Custom permissions", 2048, false),
  729. "A space-separated list of other permission flags that should be added to the manifest.");
  730. props.add (new ChoicePropertyComponent (androidEnableRemoteNotifications, "Remote Notifications"),
  731. "Enable to be able to send remote notifications to devices running your app (min API level 14). Provide Remote Notifications Config File, "
  732. "configure your app in Firebase Console and ensure you have the latest Google Repository in Android Studio's SDK Manager.");
  733. props.add (new TextPropertyComponent (androidRemoteNotificationsConfigFile.getPropertyAsValue(), "Remote Notifications Config File", 2048, false),
  734. "Path to google-services.json file. This will be the file provided by Firebase when creating a new app in Firebase console.");
  735. props.add (new TextPropertyComponent (androidManifestCustomXmlElements, "Custom manifest XML content", 8192, true),
  736. "You can specify custom AndroidManifest.xml content overriding the default one generated by Projucer. "
  737. "Projucer will automatically create any missing and required XML elements and attributes "
  738. "and merge them into your custom content.");
  739. }
  740. //==============================================================================
  741. void createCodeSigningExporterProperties (PropertyListBuilder& props)
  742. {
  743. props.add (new TextPropertyComponent (androidKeyStore, "Key Signing: key.store", 2048, false),
  744. "The key.store value, used when signing the release package.");
  745. props.add (new TextPropertyComponent (androidKeyStorePass, "Key Signing: key.store.password", 2048, false),
  746. "The key.store password, used when signing the release package.");
  747. props.add (new TextPropertyComponent (androidKeyAlias, "Key Signing: key.alias", 2048, false),
  748. "The key.alias value, used when signing the release package.");
  749. props.add (new TextPropertyComponent (androidKeyAliasPass, "Key Signing: key.alias.password", 2048, false),
  750. "The key.alias password, used when signing the release package.");
  751. }
  752. //==============================================================================
  753. void createOtherExporterProperties (PropertyListBuilder& props)
  754. {
  755. props.add (new TextPropertyComponent (androidTheme, "Android Theme", 256, false),
  756. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  757. }
  758. //==============================================================================
  759. String createDefaultClassName() const
  760. {
  761. auto s = project.getBundleIdentifierString().toLowerCase();
  762. if (s.length() > 5
  763. && s.containsChar ('.')
  764. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  765. && ! s.startsWithChar ('.'))
  766. {
  767. if (! s.endsWithChar ('.'))
  768. s << ".";
  769. }
  770. else
  771. {
  772. s = "com.yourcompany.";
  773. }
  774. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRootString(), false, true, false);
  775. }
  776. //==============================================================================
  777. void copyJavaFiles (const OwnedArray<LibraryModule>& modules) const
  778. {
  779. if (auto* coreModule = getCoreModule (modules))
  780. {
  781. auto package = getActivityClassPackage();
  782. auto targetFolder = getTargetFolder();
  783. auto inAppBillingPath = String ("com.android.vending.billing").replaceCharacter ('.', File::getSeparatorChar());
  784. auto javaSourceFolder = coreModule->getFolder().getChildFile ("native").getChildFile ("java");
  785. auto javaInAppBillingTarget = targetFolder.getChildFile ("app/src/main/java").getChildFile (inAppBillingPath);
  786. auto javaTarget = targetFolder.getChildFile ("app/src/main/java")
  787. .getChildFile (package.replaceCharacter ('.', File::getSeparatorChar()));
  788. auto libTarget = targetFolder.getChildFile ("app/libs");
  789. libTarget.createDirectory();
  790. copyActivityJavaFiles (javaSourceFolder, javaTarget, package);
  791. copyServicesJavaFiles (javaSourceFolder, javaTarget, package);
  792. copyProviderJavaFile (javaSourceFolder, javaTarget, package);
  793. copyAdditionalJavaFiles (javaSourceFolder, javaInAppBillingTarget);
  794. copyAdditionalJavaLibs (libTarget);
  795. }
  796. }
  797. void copyActivityJavaFiles (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  798. {
  799. if (androidActivityClass.get().toString().contains ("_"))
  800. throw SaveError ("Your Android activity class name or path may not contain any underscores! Try a project name without underscores.");
  801. auto className = getActivityName();
  802. if (className.isEmpty())
  803. throw SaveError ("Invalid Android Activity class name: " + androidActivityClass.get().toString());
  804. createDirectoryOrThrow (targetFolder);
  805. auto javaDestFile = targetFolder.getChildFile (className + ".java");
  806. String juceMidiCode, juceMidiImports, juceRuntimePermissionsCode;
  807. juceMidiImports << newLine;
  808. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  809. {
  810. auto javaAndroidMidi = javaSourceFolder.getChildFile ("AndroidMidi.java");
  811. auto javaRuntimePermissions = javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java");
  812. juceMidiImports << "import android.media.midi.*;" << newLine
  813. << "import android.bluetooth.*;" << newLine
  814. << "import android.bluetooth.le.*;" << newLine;
  815. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  816. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  817. }
  818. else
  819. {
  820. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  821. .loadFileAsString()
  822. .replace ("JuceAppActivity", className);
  823. }
  824. String juceWebViewImports, juceWebViewCodeNative, juceWebViewCode;
  825. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  826. juceWebViewImports << "import android.webkit.WebResourceError;" << newLine;
  827. if (static_cast<int> (androidMinimumSDK.get()) >= 21)
  828. juceWebViewImports << "import android.webkit.WebResourceRequest;" << newLine;
  829. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  830. juceWebViewImports << "import android.webkit.WebResourceResponse;" << newLine;
  831. auto javaWebViewFile = javaSourceFolder.getChildFile ("AndroidWebView.java");
  832. auto juceWebViewCodeAll = javaWebViewFile.loadFileAsString();
  833. if (static_cast<int> (androidMinimumSDK.get()) <= 10)
  834. {
  835. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi1_10", false, false)
  836. .upToFirstOccurrenceOf ("WebViewApi1_10$$", false, false);
  837. }
  838. else
  839. {
  840. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  841. {
  842. juceWebViewCodeNative << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewNativeApi23", false, false)
  843. .upToFirstOccurrenceOf ("WebViewNativeApi23$$", false, false);
  844. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi23", false, false)
  845. .upToFirstOccurrenceOf ("WebViewApi23$$", false, false);
  846. }
  847. if (static_cast<int> (androidMinimumSDK.get()) >= 21)
  848. {
  849. juceWebViewCodeNative << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewNativeApi21", false, false)
  850. .upToFirstOccurrenceOf ("WebViewNativeApi21$$", false, false);
  851. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi21", false, false)
  852. .upToFirstOccurrenceOf ("WebViewApi21$$", false, false);
  853. }
  854. else
  855. {
  856. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi11_20", false, false)
  857. .upToFirstOccurrenceOf ("WebViewApi11_20$$", false, false);
  858. }
  859. }
  860. auto javaSourceFile = javaSourceFolder.getChildFile ("JuceAppActivity.java");
  861. auto javaSourceLines = StringArray::fromLines (javaSourceFile.loadFileAsString());
  862. {
  863. MemoryOutputStream newFile;
  864. for (auto& line : javaSourceLines)
  865. {
  866. if (line.contains ("$$JuceAndroidMidiImports$$"))
  867. newFile << juceMidiImports;
  868. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  869. newFile << juceMidiCode;
  870. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  871. newFile << juceRuntimePermissionsCode;
  872. else if (line.contains ("$$JuceAndroidWebViewImports$$"))
  873. newFile << juceWebViewImports;
  874. else if (line.contains ("$$JuceAndroidWebViewNativeCode$$"))
  875. newFile << juceWebViewCodeNative;
  876. else if (line.contains ("$$JuceAndroidWebViewCode$$"))
  877. newFile << juceWebViewCode;
  878. else
  879. newFile << line.replace ("$$JuceAppActivityBaseClass$$", androidActivityBaseClassName.get().toString())
  880. .replace ("JuceAppActivity", className)
  881. .replace ("package com.juce;", "package " + package + ";") << newLine;
  882. }
  883. javaSourceLines = StringArray::fromLines (newFile.toString());
  884. }
  885. while (javaSourceLines.size() > 2
  886. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  887. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  888. javaSourceLines.remove (javaSourceLines.size() - 1);
  889. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  890. }
  891. void copyAdditionalJavaFiles (const File& sourceFolder, const File& targetFolder) const
  892. {
  893. auto inAppBillingJavaFileName = String ("IInAppBillingService.java");
  894. auto inAppBillingJavaSrcFile = sourceFolder.getChildFile (inAppBillingJavaFileName);
  895. auto inAppBillingJavaDestFile = targetFolder.getChildFile (inAppBillingJavaFileName);
  896. createDirectoryOrThrow (targetFolder);
  897. jassert (inAppBillingJavaSrcFile.existsAsFile());
  898. if (inAppBillingJavaSrcFile.existsAsFile())
  899. inAppBillingJavaSrcFile.copyFileTo (inAppBillingJavaDestFile);
  900. }
  901. void copyAdditionalJavaLibs (const File& targetFolder) const
  902. {
  903. auto libPaths = StringArray::fromLines (androidJavaLibs.get().toString());
  904. for (auto& p : libPaths)
  905. {
  906. File f = getTargetFolder().getChildFile (p);
  907. // Is the path to the java lib correct?
  908. jassert (f.existsAsFile());
  909. f.copyFileTo (targetFolder.getChildFile (f.getFileName()));
  910. }
  911. }
  912. void copyServicesJavaFiles (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  913. {
  914. if (androidEnableRemoteNotifications.get())
  915. {
  916. String instanceIdFileName ("JuceFirebaseInstanceIdService.java");
  917. String messagingFileName ("JuceFirebaseMessagingService.java");
  918. File instanceIdFile (javaSourceFolder.getChildFile (instanceIdFileName));
  919. File messagingFile (javaSourceFolder.getChildFile (messagingFileName));
  920. jassert (instanceIdFile.existsAsFile());
  921. jassert (messagingFile .existsAsFile());
  922. Array<File> files;
  923. files.add (instanceIdFile);
  924. files.add (messagingFile);
  925. for (auto& file : files)
  926. {
  927. auto newContent = file.loadFileAsString()
  928. .replace ("package com.juce;", "package " + package + ";");
  929. auto targetFile = targetFolder.getChildFile (file.getFileName());
  930. overwriteFileIfDifferentOrThrow (targetFile, newContent);
  931. }
  932. }
  933. }
  934. void copyProviderJavaFile (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  935. {
  936. auto providerFile = javaSourceFolder.getChildFile ("AndroidSharingContentProvider.java");
  937. jassert (providerFile.existsAsFile());
  938. auto targetFile = targetFolder.getChildFile ("SharingContentProvider.java");
  939. auto fileContent = providerFile.loadFileAsString()
  940. .replace ("package com.juce;", "package " + package + ";");
  941. auto commonStart = fileContent.upToFirstOccurrenceOf ("$$ContentProviderApi11", false, false);
  942. auto commonEnd = fileContent.fromFirstOccurrenceOf ("ContentProviderApi11$$", false, false);
  943. auto middleContent = static_cast<int> (androidMinimumSDK.get()) >= 11
  944. ? fileContent.fromFirstOccurrenceOf ("$$ContentProviderApi11", false, false)
  945. .upToFirstOccurrenceOf ("ContentProviderApi11$$", false, false)
  946. : String();
  947. auto newContent = commonStart;
  948. newContent << middleContent << commonEnd;
  949. overwriteFileIfDifferentOrThrow (targetFile, newContent);
  950. }
  951. void copyExtraResourceFiles() const
  952. {
  953. for (ConstConfigIterator config (*this); config.next();)
  954. {
  955. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  956. String cfgPath = cfg.isDebug() ? "app/src/debug" : "app/src/release";
  957. String xmlValuesPath = cfg.isDebug() ? "app/src/debug/res/values" : "app/src/release/res/values";
  958. String drawablesPath = cfg.isDebug() ? "app/src/debug/res" : "app/src/release/res";
  959. String rawPath = cfg.isDebug() ? "app/src/debug/res/raw" : "app/src/release/res/raw";
  960. copyExtraResourceFiles (cfg.getAdditionalXmlResources(), xmlValuesPath);
  961. copyExtraResourceFiles (cfg.getAdditionalDrawableResources(), drawablesPath);
  962. copyExtraResourceFiles (cfg.getAdditionalRawResources(), rawPath);
  963. if (androidEnableRemoteNotifications.get())
  964. {
  965. auto remoteNotifsConfigFilePath = cfg.getRemoteNotifsConfigFile();
  966. if (remoteNotifsConfigFilePath.isEmpty())
  967. remoteNotifsConfigFilePath = androidRemoteNotificationsConfigFile.get().toString();
  968. File file (getProject().getFile().getChildFile (remoteNotifsConfigFilePath));
  969. // Settings file must be present for remote notifications to work and it must be called google-services.json.
  970. jassert (file.existsAsFile() && file.getFileName() == "google-services.json");
  971. copyExtraResourceFiles (remoteNotifsConfigFilePath, cfgPath);
  972. }
  973. }
  974. }
  975. void copyExtraResourceFiles (const String& resources, const String& dstRelativePath) const
  976. {
  977. auto resourcePaths = StringArray::fromTokens (resources, true);
  978. auto parentFolder = getTargetFolder().getChildFile (dstRelativePath);
  979. parentFolder.createDirectory();
  980. for (auto& path : resourcePaths)
  981. {
  982. auto file = getProject().getFile().getChildFile (path);
  983. jassert (file.exists());
  984. if (file.exists())
  985. file.copyFileTo (parentFolder.getChildFile (file.getFileName()));
  986. }
  987. }
  988. String getActivityName() const
  989. {
  990. return androidActivityClass.get().toString().fromLastOccurrenceOf (".", false, false);
  991. }
  992. String getActivitySubClassName() const
  993. {
  994. auto activityPath = androidActivitySubClassName.get().toString();
  995. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  996. }
  997. String getActivityClassPackage() const
  998. {
  999. return androidActivityClass.get().toString().upToLastOccurrenceOf (".", false, false);
  1000. }
  1001. String getJNIActivityClassName() const
  1002. {
  1003. return androidActivityClass.get().toString().replaceCharacter ('.', '/');
  1004. }
  1005. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  1006. {
  1007. for (int i = modules.size(); --i >= 0;)
  1008. if (modules.getUnchecked (i)->getID() == "juce_core")
  1009. return modules.getUnchecked (i);
  1010. return nullptr;
  1011. }
  1012. //==============================================================================
  1013. String getNativeModuleBinaryName (const AndroidBuildConfiguration& config) const
  1014. {
  1015. return (isLibrary() ? File::createLegalFileName (config.getTargetBinaryNameString().trim()) : "juce_jni");
  1016. }
  1017. String getAppPlatform() const
  1018. {
  1019. auto ndkVersion = static_cast<int> (androidMinimumSDK.get());
  1020. if (ndkVersion == 9)
  1021. ndkVersion = 10; // (doesn't seem to be a version '9')
  1022. return "android-" + String (ndkVersion);
  1023. }
  1024. //==============================================================================
  1025. void writeStringsXML (const File& folder) const
  1026. {
  1027. for (ConstConfigIterator config (*this); config.next();)
  1028. {
  1029. auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  1030. String customStringsXmlContent ("<resources>\n");
  1031. customStringsXmlContent << "<string name=\"app_name\">" << projectName << "</string>\n";
  1032. customStringsXmlContent << cfg.getCustomStringsXml();
  1033. customStringsXmlContent << "\n</resources>";
  1034. ScopedPointer<XmlElement> strings = XmlDocument::parse (customStringsXmlContent);
  1035. String dir = cfg.isDebug() ? "debug" : "release";
  1036. String subPath = "app/src/" + dir + "/res/values/string.xml";
  1037. writeXmlOrThrow (*strings, folder.getChildFile (subPath), "utf-8", 100, true);
  1038. }
  1039. }
  1040. void writeAndroidManifest (const File& folder) const
  1041. {
  1042. ScopedPointer<XmlElement> manifest (createManifestXML());
  1043. writeXmlOrThrow (*manifest, folder.getChildFile ("src/main/AndroidManifest.xml"), "utf-8", 100, true);
  1044. }
  1045. void writeIcon (const File& file, const Image& im) const
  1046. {
  1047. if (im.isValid())
  1048. {
  1049. createDirectoryOrThrow (file.getParentDirectory());
  1050. PNGImageFormat png;
  1051. MemoryOutputStream mo;
  1052. if (! png.writeImageToStream (im, mo))
  1053. throw SaveError ("Can't generate Android icon file");
  1054. overwriteFileIfDifferentOrThrow (file, mo);
  1055. }
  1056. }
  1057. void writeIcons (const File& folder) const
  1058. {
  1059. ScopedPointer<Drawable> bigIcon (getBigIcon());
  1060. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  1061. if (bigIcon != nullptr && smallIcon != nullptr)
  1062. {
  1063. auto step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  1064. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  1065. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  1066. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  1067. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  1068. }
  1069. else if (auto* icon = (bigIcon != nullptr ? bigIcon.get() : smallIcon.get()))
  1070. {
  1071. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  1072. }
  1073. }
  1074. void writeAppIcons (const File& folder) const
  1075. {
  1076. writeIcons (folder.getChildFile ("app/src/main/res/"));
  1077. }
  1078. static String sanitisePath (String path)
  1079. {
  1080. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  1081. }
  1082. static String expandHomeFolderToken (const String& path)
  1083. {
  1084. auto homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  1085. return path.replace ("${user.home}", homeFolder)
  1086. .replace ("~", homeFolder);
  1087. }
  1088. //==============================================================================
  1089. void addCompileUnits (const Project::Item& projectItem, MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  1090. {
  1091. if (projectItem.isGroup())
  1092. {
  1093. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  1094. addCompileUnits (projectItem.getChild(i), mo, excludeFromBuild);
  1095. }
  1096. else if (projectItem.shouldBeAddedToTargetProject())
  1097. {
  1098. RelativePath file (projectItem.getFile(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  1099. auto targetType = getProject().getTargetTypeFromFilePath (projectItem.getFile(), true);
  1100. mo << " \"" << file.toUnixStyle() << "\"" << newLine;
  1101. if ((! projectItem.shouldBeCompiled()) || (! shouldFileBeCompiledByDefault (file))
  1102. || (getProject().getProjectType().isAudioPlugin()
  1103. && targetType != ProjectType::Target::SharedCodeTarget
  1104. && targetType != ProjectType::Target::StandalonePlugIn))
  1105. excludeFromBuild.add (file);
  1106. }
  1107. }
  1108. void addCompileUnits (MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  1109. {
  1110. for (int i = 0; i < getAllGroups().size(); ++i)
  1111. addCompileUnits (getAllGroups().getReference(i), mo, excludeFromBuild);
  1112. }
  1113. //==============================================================================
  1114. StringArray getCmakeDefinitions() const
  1115. {
  1116. auto toolchain = gradleToolchain.get().toString();
  1117. bool isClang = (toolchain == "clang");
  1118. StringArray cmakeArgs;
  1119. cmakeArgs.add ("\"-DANDROID_TOOLCHAIN=" + toolchain + "\"");
  1120. cmakeArgs.add ("\"-DANDROID_PLATFORM=" + getAppPlatform() + "\"");
  1121. cmakeArgs.add (String ("\"-DANDROID_STL=") + (isClang ? "c++_static" : "gnustl_static") + "\"");
  1122. cmakeArgs.add ("\"-DANDROID_CPP_FEATURES=exceptions rtti\"");
  1123. cmakeArgs.add ("\"-DANDROID_ARM_MODE=arm\"");
  1124. cmakeArgs.add ("\"-DANDROID_ARM_NEON=TRUE\"");
  1125. return cmakeArgs;
  1126. }
  1127. //==============================================================================
  1128. StringArray getAndroidCompilerFlags() const
  1129. {
  1130. StringArray cFlags;
  1131. cFlags.add ("\"-fsigned-char\"");
  1132. return cFlags;
  1133. }
  1134. StringArray getAndroidCxxCompilerFlags() const
  1135. {
  1136. auto cxxFlags = getAndroidCompilerFlags();
  1137. auto cppStandard = project.getCppStandardString();
  1138. if (cppStandard == "latest" || cppStandard == "17") // C++17 flag isn't supported yet so use 1z for now
  1139. cppStandard = "1z";
  1140. cppStandard = "-std=" + String (shouldUseGNUExtensions() ? "gnu++" : "c++") + cppStandard;
  1141. cxxFlags.add (cppStandard.quoted());
  1142. return cxxFlags;
  1143. }
  1144. StringArray getProjectCompilerFlags() const
  1145. {
  1146. auto cFlags = getAndroidCompilerFlags();
  1147. cFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  1148. return cFlags;
  1149. }
  1150. StringArray getProjectCxxCompilerFlags() const
  1151. {
  1152. auto cxxFlags = getAndroidCxxCompilerFlags();
  1153. cxxFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  1154. return cxxFlags;
  1155. }
  1156. //==============================================================================
  1157. StringPairArray getAndroidPreprocessorDefs() const
  1158. {
  1159. StringPairArray defines;
  1160. defines.set ("JUCE_ANDROID", "1");
  1161. defines.set ("JUCE_ANDROID_API_VERSION", androidMinimumSDK.get());
  1162. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  1163. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\"" + getJNIActivityClassName() + "\"");
  1164. defines.set ("JUCE_ANDROID_SHARING_CONTENT_PROVIDER_CLASSNAME", getSharingContentProviderClassName().replaceCharacter('.', '_'));
  1165. defines.set ("JUCE_ANDROID_SHARING_CONTENT_PROVIDER_CLASSPATH", "\"" + getSharingContentProviderClassName().replaceCharacter('.', '/') + "\"");
  1166. defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");
  1167. if (androidInAppBillingPermission.get())
  1168. defines.set ("JUCE_IN_APP_PURCHASES", "1");
  1169. if (androidEnableRemoteNotifications.get())
  1170. {
  1171. auto instanceIdClassName = getActivityClassPackage() + ".JuceFirebaseInstanceIdService";
  1172. auto messagingClassName = getActivityClassPackage() + ".JuceFirebaseMessagingService";
  1173. defines.set ("JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME", instanceIdClassName.replaceCharacter ('.', '_'));
  1174. defines.set ("JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME", messagingClassName.replaceCharacter ('.', '_'));
  1175. }
  1176. if (supportsGLv3())
  1177. defines.set ("JUCE_ANDROID_GL_ES_VERSION_3_0", "1");
  1178. return defines;
  1179. }
  1180. String getSharingContentProviderClassName() const
  1181. {
  1182. return getActivityClassPackage() + ".SharingContentProvider";
  1183. }
  1184. StringPairArray getProjectPreprocessorDefs() const
  1185. {
  1186. auto defines = getAndroidPreprocessorDefs();
  1187. return mergePreprocessorDefs (defines, getAllPreprocessorDefs());
  1188. }
  1189. StringPairArray getConfigPreprocessorDefs (const BuildConfiguration& config) const
  1190. {
  1191. auto cfgDefines = config.getUniquePreprocessorDefs();
  1192. if (config.isDebug())
  1193. {
  1194. cfgDefines.set ("DEBUG", "1");
  1195. cfgDefines.set ("_DEBUG", "1");
  1196. }
  1197. else
  1198. {
  1199. cfgDefines.set ("NDEBUG", "1");
  1200. }
  1201. return cfgDefines;
  1202. }
  1203. //==============================================================================
  1204. StringArray getAndroidLibraries() const
  1205. {
  1206. StringArray libraries;
  1207. libraries.add ("log");
  1208. libraries.add ("android");
  1209. libraries.add (supportsGLv3() ? "GLESv3" : "GLESv2");
  1210. libraries.add ("EGL");
  1211. return libraries;
  1212. }
  1213. //==============================================================================
  1214. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  1215. {
  1216. auto paths = extraSearchPaths;
  1217. paths.addArray (config.getHeaderSearchPaths());
  1218. paths = getCleanedStringArray (paths);
  1219. return paths;
  1220. }
  1221. //==============================================================================
  1222. String escapeDirectoryForCmake (const String& path) const
  1223. {
  1224. auto relative =
  1225. RelativePath (path, RelativePath::buildTargetFolder)
  1226. .rebased (getTargetFolder(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  1227. return relative.toUnixStyle();
  1228. }
  1229. void writeCmakePathLines (MemoryOutputStream& mo, const String& prefix, const String& firstLine, const StringArray& paths,
  1230. const String& suffix = ")") const
  1231. {
  1232. if (paths.size() > 0)
  1233. {
  1234. mo << prefix << firstLine << newLine;
  1235. for (auto& path : paths)
  1236. mo << prefix << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  1237. mo << prefix << suffix << newLine << newLine;
  1238. }
  1239. }
  1240. static StringArray getEscapedPreprocessorDefs (const StringPairArray& defs)
  1241. {
  1242. StringArray escapedDefs;
  1243. for (int i = 0; i < defs.size(); ++i)
  1244. {
  1245. auto escaped = "\"-D" + defs.getAllKeys()[i];
  1246. auto value = defs.getAllValues()[i];
  1247. if (value.isNotEmpty())
  1248. {
  1249. value = value.replace ("\"", "\\\"");
  1250. if (value.containsChar (L' '))
  1251. value = "\\\"" + value + "\\\"";
  1252. escaped += ("=" + value);
  1253. }
  1254. escapedDefs.add (escaped + "\"");
  1255. }
  1256. return escapedDefs;
  1257. }
  1258. static StringArray getEscapedFlags (const StringArray& flags)
  1259. {
  1260. StringArray escaped;
  1261. for (auto& flag : flags)
  1262. escaped.add ("\"" + flag + "\"");
  1263. return escaped;
  1264. }
  1265. //==============================================================================
  1266. XmlElement* createManifestXML() const
  1267. {
  1268. auto* manifest = createManifestElement();
  1269. createSupportsScreensElement (*manifest);
  1270. createUsesSdkElement (*manifest);
  1271. createPermissionElements (*manifest);
  1272. createOpenGlFeatureElement (*manifest);
  1273. if (! isLibrary())
  1274. {
  1275. auto* app = createApplicationElement (*manifest);
  1276. auto* act = createActivityElement (*app);
  1277. createIntentElement (*act);
  1278. createServiceElements (*app);
  1279. createProviderElement (*app);
  1280. }
  1281. return manifest;
  1282. }
  1283. XmlElement* createManifestElement() const
  1284. {
  1285. auto* manifest = XmlDocument::parse (androidManifestCustomXmlElements.get());
  1286. if (manifest == nullptr)
  1287. manifest = new XmlElement ("manifest");
  1288. setAttributeIfNotPresent (*manifest, "xmlns:android", "http://schemas.android.com/apk/res/android");
  1289. setAttributeIfNotPresent (*manifest, "android:versionCode", androidVersionCode.get());
  1290. setAttributeIfNotPresent (*manifest, "android:versionName", project.getVersionString());
  1291. setAttributeIfNotPresent (*manifest, "package", getActivityClassPackage());
  1292. return manifest;
  1293. }
  1294. void createSupportsScreensElement (XmlElement& manifest) const
  1295. {
  1296. if (! isLibrary())
  1297. {
  1298. if (manifest.getChildByName ("supports-screens") == nullptr)
  1299. {
  1300. auto* screens = manifest.createNewChildElement ("supports-screens");
  1301. screens->setAttribute ("android:smallScreens", "true");
  1302. screens->setAttribute ("android:normalScreens", "true");
  1303. screens->setAttribute ("android:largeScreens", "true");
  1304. screens->setAttribute ("android:anyDensity", "true");
  1305. }
  1306. }
  1307. }
  1308. void createUsesSdkElement (XmlElement& manifest) const
  1309. {
  1310. auto* sdk = getOrCreateChildWithName (manifest, "uses-sdk");
  1311. setAttributeIfNotPresent (*sdk, "android:minSdkVersion", androidMinimumSDK.get());
  1312. setAttributeIfNotPresent (*sdk, "android:targetSdkVersion", androidMinimumSDK.get());
  1313. }
  1314. void createPermissionElements (XmlElement& manifest) const
  1315. {
  1316. auto permissions = getPermissionsRequired();
  1317. forEachXmlChildElementWithTagName (manifest, child, "uses-permission")
  1318. {
  1319. permissions.removeString (child->getStringAttribute ("android:name"), false);
  1320. }
  1321. for (int i = permissions.size(); --i >= 0;)
  1322. manifest.createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  1323. }
  1324. void createOpenGlFeatureElement (XmlElement& manifest) const
  1325. {
  1326. if (project.getModules().isModuleEnabled ("juce_opengl"))
  1327. {
  1328. XmlElement* glVersion = nullptr;
  1329. forEachXmlChildElementWithTagName (manifest, child, "uses-feature")
  1330. {
  1331. if (child->getStringAttribute ("android:glEsVersion").isNotEmpty())
  1332. {
  1333. glVersion = child;
  1334. break;
  1335. }
  1336. }
  1337. if (glVersion == nullptr)
  1338. glVersion = manifest.createNewChildElement ("uses-feature");
  1339. setAttributeIfNotPresent (*glVersion, "android:glEsVersion", (static_cast<int> (androidMinimumSDK.get()) >= 18 ? "0x00030000" : "0x00020000"));
  1340. setAttributeIfNotPresent (*glVersion, "android:required", "true");
  1341. }
  1342. }
  1343. XmlElement* createApplicationElement (XmlElement& manifest) const
  1344. {
  1345. auto* app = getOrCreateChildWithName (manifest, "application");
  1346. setAttributeIfNotPresent (*app, "android:label", "@string/app_name");
  1347. if (androidTheme.get().toString().isNotEmpty())
  1348. setAttributeIfNotPresent (*app, "android:theme", androidTheme.get());
  1349. if (! app->hasAttribute ("android:icon"))
  1350. {
  1351. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  1352. if (bigIcon != nullptr || smallIcon != nullptr)
  1353. app->setAttribute ("android:icon", "@drawable/icon");
  1354. }
  1355. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  1356. {
  1357. if (! app->hasAttribute ("android:hardwareAccelerated"))
  1358. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  1359. }
  1360. else
  1361. {
  1362. app->removeAttribute ("android:hardwareAccelerated");
  1363. }
  1364. return app;
  1365. }
  1366. XmlElement* createActivityElement (XmlElement& application) const
  1367. {
  1368. auto* act = getOrCreateChildWithName (application, "activity");
  1369. setAttributeIfNotPresent (*act, "android:name", getActivitySubClassName());
  1370. setAttributeIfNotPresent (*act, "android:label", "@string/app_name");
  1371. if (! act->hasAttribute ("android:configChanges"))
  1372. {
  1373. String configChanges ("keyboardHidden|orientation");
  1374. if (static_cast<int> (androidMinimumSDK.get()) >= 13)
  1375. configChanges += "|screenSize";
  1376. act->setAttribute ("android:configChanges", configChanges);
  1377. }
  1378. else
  1379. {
  1380. auto configChanges = act->getStringAttribute ("android:configChanges");
  1381. if (static_cast<int> (androidMinimumSDK.get()) < 13 && configChanges.contains ("screenSize"))
  1382. {
  1383. configChanges = configChanges.replace ("|screenSize", "")
  1384. .replace ("screenSize|", "")
  1385. .replace ("screenSize", "");
  1386. act->setAttribute ("android:configChanges", configChanges);
  1387. }
  1388. }
  1389. if (androidScreenOrientation.get() == "landscape")
  1390. {
  1391. String landscapeString = static_cast<int> (androidMinimumSDK.get()) < 9
  1392. ? "landscape"
  1393. : (static_cast<int> (androidMinimumSDK.get()) < 18 ? "sensorLandscape" : "userLandscape");
  1394. setAttributeIfNotPresent (*act, "android:screenOrientation", landscapeString);
  1395. }
  1396. else
  1397. {
  1398. setAttributeIfNotPresent (*act, "android:screenOrientation", androidScreenOrientation.get());
  1399. }
  1400. setAttributeIfNotPresent (*act, "android:launchMode", "singleTask");
  1401. // Using the 2D acceleration slows down OpenGL. We *do* enable it here for the activity though, and we disable it
  1402. // in each ComponentPeerView instead. This way any embedded native views, which are not children of ComponentPeerView,
  1403. // can still use hardware acceleration if needed (e.g. web view).
  1404. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  1405. {
  1406. if (! act->hasAttribute ("android:hardwareAccelerated"))
  1407. act->setAttribute ("android:hardwareAccelerated", "true"); // (using the 2D acceleration slows down openGL)
  1408. }
  1409. else
  1410. {
  1411. act->removeAttribute ("android:hardwareAccelerated");
  1412. }
  1413. return act;
  1414. }
  1415. void createIntentElement (XmlElement& application) const
  1416. {
  1417. auto* intent = getOrCreateChildWithName (application, "intent-filter");
  1418. auto* action = getOrCreateChildWithName (*intent, "action");
  1419. setAttributeIfNotPresent (*action, "android:name", "android.intent.action.MAIN");
  1420. auto* category = getOrCreateChildWithName (*intent, "category");
  1421. setAttributeIfNotPresent (*category, "android:name", "android.intent.category.LAUNCHER");
  1422. }
  1423. void createServiceElements (XmlElement& application) const
  1424. {
  1425. if (androidEnableRemoteNotifications.get())
  1426. {
  1427. auto* service = application.createNewChildElement ("service");
  1428. service->setAttribute ("android:name", ".JuceFirebaseMessagingService");
  1429. auto* intentFilter = service->createNewChildElement ("intent-filter");
  1430. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.MESSAGING_EVENT");
  1431. service = application.createNewChildElement ("service");
  1432. service->setAttribute ("android:name", ".JuceFirebaseInstanceIdService");
  1433. intentFilter = service->createNewChildElement ("intent-filter");
  1434. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.INSTANCE_ID_EVENT");
  1435. auto* metaData = application.createNewChildElement ("meta-data");
  1436. metaData->setAttribute ("android:name", "firebase_analytics_collection_deactivated");
  1437. metaData->setAttribute ("android:value", "true");
  1438. }
  1439. }
  1440. void createProviderElement (XmlElement& application) const
  1441. {
  1442. if (androidEnableContentSharing.get())
  1443. {
  1444. auto* provider = application.createNewChildElement ("provider");
  1445. provider->setAttribute ("android:name", getSharingContentProviderClassName());
  1446. provider->setAttribute ("android:authorities", getSharingContentProviderClassName().toLowerCase());
  1447. provider->setAttribute ("android:grantUriPermissions", "true");
  1448. provider->setAttribute ("android:exported", "false");
  1449. }
  1450. }
  1451. static XmlElement* getOrCreateChildWithName (XmlElement& element, const String& name)
  1452. {
  1453. auto* child = element.getChildByName (name);
  1454. if (child == nullptr)
  1455. child = element.createNewChildElement (name);
  1456. return child;
  1457. }
  1458. static void setAttributeIfNotPresent (XmlElement& element, const Identifier& attribute, const String& value)
  1459. {
  1460. if (! element.hasAttribute (attribute.toString()))
  1461. element.setAttribute (attribute, value);
  1462. }
  1463. StringArray getPermissionsRequired() const
  1464. {
  1465. StringArray s = StringArray::fromTokens (androidOtherPermissions.get().toString(), ", ", {});
  1466. if (androidInternetNeeded.get())
  1467. s.add ("android.permission.INTERNET");
  1468. if (androidMicNeeded.get())
  1469. s.add ("android.permission.RECORD_AUDIO");
  1470. if (androidBluetoothNeeded.get())
  1471. {
  1472. s.add ("android.permission.BLUETOOTH");
  1473. s.add ("android.permission.BLUETOOTH_ADMIN");
  1474. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  1475. }
  1476. if (androidExternalReadPermission.get())
  1477. s.add ("android.permission.READ_EXTERNAL_STORAGE");
  1478. if (androidExternalWritePermission.get())
  1479. s.add ("android.permission.WRITE_EXTERNAL_STORAGE");
  1480. if (androidInAppBillingPermission.get())
  1481. s.add ("com.android.vending.BILLING");
  1482. if (androidVibratePermission.get())
  1483. s.add ("android.permission.VIBRATE");
  1484. return getCleanedStringArray (s);
  1485. }
  1486. //==============================================================================
  1487. bool isLibrary() const
  1488. {
  1489. return getProject().getProjectType().isDynamicLibrary()
  1490. || getProject().getProjectType().isStaticLibrary();
  1491. }
  1492. static String toGradleList (const StringArray& array)
  1493. {
  1494. StringArray escapedArray;
  1495. for (auto element : array)
  1496. escapedArray.add ("\"" + element.replace ("\\", "\\\\").replace ("\"", "\\\"") + "\"");
  1497. return escapedArray.joinIntoString (", ");
  1498. }
  1499. bool supportsGLv3() const
  1500. {
  1501. return (static_cast<int> (androidMinimumSDK.get()) >= 18);
  1502. }
  1503. //==============================================================================
  1504. Value sdkPath, ndkPath;
  1505. const File AndroidExecutable;
  1506. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  1507. };
  1508. inline ProjectExporter* createAndroidExporter (Project& p, const ValueTree& t)
  1509. {
  1510. return new AndroidProjectExporter (p, t);
  1511. }
  1512. inline ProjectExporter* createAndroidExporterForSetting (Project& p, const ValueTree& t)
  1513. {
  1514. return AndroidProjectExporter::createForSettings (p, t);
  1515. }