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.

1891 lines
86KB

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