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.

1865 lines
85KB

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