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.

1866 lines
84KB

  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, nullptr, ""),
  93. androidDependencies (settings, Ids::androidDependencies, nullptr, ""),
  94. androidScreenOrientation (settings, Ids::androidScreenOrientation, nullptr, "unspecified"),
  95. androidActivityClass (settings, Ids::androidActivityClass, nullptr, createDefaultClassName()),
  96. androidActivitySubClassName (settings, Ids::androidActivitySubClassName, nullptr),
  97. androidManifestCustomXmlElements (settings, Ids::androidManifestCustomXmlElements, nullptr, ""),
  98. androidVersionCode (settings, Ids::androidVersionCode, nullptr, "1"),
  99. androidMinimumSDK (settings, Ids::androidMinimumSDK, nullptr, "10"),
  100. androidTheme (settings, Ids::androidTheme, nullptr),
  101. androidSharedLibraries (settings, Ids::androidSharedLibraries, nullptr, ""),
  102. androidStaticLibraries (settings, Ids::androidStaticLibraries, nullptr, ""),
  103. androidExtraAssetsFolder (settings, Ids::androidExtraAssetsFolder, nullptr, ""),
  104. androidInternetNeeded (settings, Ids::androidInternetNeeded, nullptr, true),
  105. androidMicNeeded (settings, Ids::microphonePermissionNeeded, nullptr, false),
  106. androidBluetoothNeeded (settings, Ids::androidBluetoothNeeded, nullptr, true),
  107. androidExternalReadPermission (settings, Ids::androidExternalReadNeeded, nullptr, true),
  108. androidExternalWritePermission (settings, Ids::androidExternalWriteNeeded, nullptr, true),
  109. androidInAppBillingPermission (settings, Ids::androidInAppBilling, nullptr, false),
  110. androidVibratePermission (settings, Ids::androidVibratePermissionNeeded, nullptr, false),
  111. androidOtherPermissions (settings, Ids::androidOtherPermissions, nullptr),
  112. androidEnableRemoteNotifications (settings, Ids::androidEnableRemoteNotifications, nullptr, false),
  113. androidRemoteNotificationsConfigFile (settings, Ids::androidRemoteNotificationsConfigFile, nullptr, ""),
  114. androidEnableContentSharing (settings, Ids::androidEnableContentSharing, nullptr, false),
  115. androidKeyStore (settings, Ids::androidKeyStore, nullptr, "${user.home}/.android/debug.keystore"),
  116. androidKeyStorePass (settings, Ids::androidKeyStorePass, nullptr, "android"),
  117. androidKeyAlias (settings, Ids::androidKeyAlias, nullptr, "androiddebugkey"),
  118. androidKeyAliasPass (settings, Ids::androidKeyAliasPass, nullptr, "android"),
  119. gradleVersion (settings, Ids::gradleVersion, nullptr, "4.1"),
  120. gradleToolchain (settings, Ids::gradleToolchain, nullptr, "clang"),
  121. androidPluginVersion (settings, Ids::androidPluginVersion, nullptr, "3.0.0"),
  122. buildToolsVersion (settings, Ids::buildToolsVersion, nullptr, "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. const File 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. const File targetFolder (getTargetFolder());
  170. const File 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. const String androidExtraAssetsFolderValue = androidExtraAssetsFolder.get();
  193. if (androidExtraAssetsFolderValue.isNotEmpty())
  194. {
  195. File extraAssets (getProject().getFile().getParentDirectory().getChildFile(androidExtraAssetsFolderValue));
  196. if (extraAssets.exists() && extraAssets.isDirectory())
  197. {
  198. const File 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. const File defaultInstallation ("C:\\Program Files\\Android\\Android Studio\\bin");
  229. if (defaultInstallation.exists())
  230. {
  231. {
  232. const File studio64 = defaultInstallation.getChildFile ("studio64.exe");
  233. if (studio64.existsAsFile())
  234. return studio64;
  235. }
  236. {
  237. const File studio = defaultInstallation.getChildFile ("studio.exe");
  238. if (studio.existsAsFile())
  239. return studio;
  240. }
  241. }
  242. #elif JUCE_MAC
  243. const 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, nullptr, isDebug() ? "armeabi x86" : ""),
  257. androidAdditionalXmlValueResources (config, Ids::androidAdditionalXmlValueResources, nullptr, {}),
  258. androidAdditionalRawValueResources (config, Ids::androidAdditionalRawValueResources, nullptr, {}),
  259. androidCustomStringXmlElements (config, Ids::androidCustomStringXmlElements, nullptr, {})
  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. StringArray 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. const String& 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. StringArray 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. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  343. const StringArray& libSearchPaths = cfg.getLibrarySearchPaths();
  344. const StringPairArray& cfgDefines = getConfigPreprocessorDefs (cfg);
  345. const StringArray& cfgHeaderPaths = cfg.getHeaderSearchPaths();
  346. const StringArray& 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 (const 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. StringArray 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. const 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. String 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. const String bundleIdentifier = project.getBundleIdentifierString().toLowerCase();
  533. const StringArray& cmakeDefs = getCmakeDefinitions();
  534. const StringArray& cFlags = getProjectCompilerFlags();
  535. const StringArray& cxxFlags = getProjectCxxCompilerFlags();
  536. const int 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. const int 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. const 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. juce::StringArray repositories;
  597. repositories.addLines (androidRepositories.get().toString());
  598. mo << "repositories {" << newLine;
  599. for (const auto& r : repositories)
  600. mo << " " << r << newLine;
  601. mo << "}" << newLine;
  602. return mo.toString();
  603. }
  604. String getAndroidDependencies() const
  605. {
  606. MemoryOutputStream mo;
  607. juce::StringArray dependencies;
  608. dependencies.addLines (androidDependencies.get().toString());
  609. mo << "dependencies {" << newLine;
  610. if (androidEnableRemoteNotifications.get())
  611. {
  612. mo << " 'com.google.firebase:firebase-core:11.4.0'" << newLine;
  613. mo << " compile 'com.google.firebase:firebase-messaging:11.4.0'" << newLine;
  614. }
  615. for (const auto& d : dependencies)
  616. mo << " " << d << newLine;
  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 (androidRepositories, "Module repositories", 32768, true),
  646. "Module repositories (one per line). These will be added to module-level gradle file repositories section. ");
  647. props.add (new TextPropertyComponent (androidDependencies, "Module dependencies", 32768, true),
  648. "Module dependencies (one per line). These will be added to module-level gradle file dependencies section. ");
  649. props.add (new ChoicePropertyComponent (androidScreenOrientation, "Screen orientation",
  650. { "Portrait and Landscape", "Portrait", "Landscape" },
  651. { "unspecified", "portrait", "landscape" }),
  652. "The screen orientations that this app should support");
  653. props.add (new TextPropertyComponent (androidActivityClass, "Android Activity class name", 256, false),
  654. "The full java class name to use for the app's Activity class.");
  655. props.add (new TextPropertyComponent (androidActivitySubClassName, "Android Activity sub-class name", 256, false),
  656. "If not empty, specifies the Android Activity class name stored in the app's manifest. "
  657. "Use this if you would like to use your own Android Activity sub-class.");
  658. props.add (new TextPropertyComponent (androidVersionCode, "Android Version Code", 32, false),
  659. "An integer value that represents the version of the application code, relative to other versions.");
  660. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), sdkPath, "Android SDK Path"),
  661. "The path to the Android SDK folder on the target build machine");
  662. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), ndkPath, "Android NDK Path"),
  663. "The path to the Android NDK folder on the target build machine");
  664. props.add (new TextPropertyComponent (androidMinimumSDK, "Minimum SDK version", 32, false),
  665. "The number of the minimum version of the Android SDK that the app requires");
  666. props.add (new TextPropertyComponent (androidExtraAssetsFolder, "Extra Android Assets", 256, false),
  667. "A path to a folder (relative to the project folder) which contains extra android assets.");
  668. }
  669. //==============================================================================
  670. void createManifestExporterProperties (PropertyListBuilder& props)
  671. {
  672. props.add (new ChoicePropertyComponent (androidInternetNeeded, "Internet Access"),
  673. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  674. props.add (new ChoicePropertyComponent (androidMicNeeded, "Audio Input Required"),
  675. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  676. props.add (new ChoicePropertyComponent (androidBluetoothNeeded, "Bluetooth permissions Required"),
  677. "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.");
  678. props.add (new ChoicePropertyComponent (androidExternalReadPermission, "Read from external storage"),
  679. "If enabled, this will set the android.permission.READ_EXTERNAL_STORAGE flag in the manifest.");
  680. props.add (new ChoicePropertyComponent (androidExternalWritePermission, "Write to external storage"),
  681. "If enabled, this will set the android.permission.WRITE_EXTERNAL_STORAGE flag in the manifest.");
  682. props.add (new ChoicePropertyComponent (androidInAppBillingPermission, "In-App Billing"),
  683. "If enabled, this will set the com.android.vending.BILLING flag in the manifest.");
  684. props.add (new ChoicePropertyComponent (androidVibratePermission, "Vibrate"),
  685. "If enabled, this will set the android.permission.VIBRATE flag in the manifest.");
  686. props.add (new ChoicePropertyComponent (androidEnableContentSharing, "Content Sharing"),
  687. "If enabled, your app will be able to share content with other apps.");
  688. props.add (new TextPropertyComponent (androidOtherPermissions, "Custom permissions", 2048, false),
  689. "A space-separated list of other permission flags that should be added to the manifest.");
  690. props.add (new ChoicePropertyComponent (androidEnableRemoteNotifications, "Remote Notifications"),
  691. "Enable to be able to send remote notifications to devices running your app (min API level 14). Provide Remote Notifications Config File, "
  692. "configure your app in Firebase Console and ensure you have the latest Google Repository in Android Studio's SDK Manager.");
  693. props.add (new TextPropertyComponent (androidRemoteNotificationsConfigFile.getPropertyAsValue(), "Remote Notifications Config File", 2048, false),
  694. "Path to google-services.json file. This will be the file provided by Firebase when creating a new app in Firebase console.");
  695. props.add (new TextPropertyComponent (androidManifestCustomXmlElements, "Custom manifest XML content", 8192, true),
  696. "You can specify custom AndroidManifest.xml content overriding the default one generated by Projucer. "
  697. "Projucer will automatically create any missing and required XML elements and attributes "
  698. "and merge them into your custom content.");
  699. }
  700. //==============================================================================
  701. void createCodeSigningExporterProperties (PropertyListBuilder& props)
  702. {
  703. props.add (new TextPropertyComponent (androidKeyStore, "Key Signing: key.store", 2048, false),
  704. "The key.store value, used when signing the release package.");
  705. props.add (new TextPropertyComponent (androidKeyStorePass, "Key Signing: key.store.password", 2048, false),
  706. "The key.store password, used when signing the release package.");
  707. props.add (new TextPropertyComponent (androidKeyAlias, "Key Signing: key.alias", 2048, false),
  708. "The key.alias value, used when signing the release package.");
  709. props.add (new TextPropertyComponent (androidKeyAliasPass, "Key Signing: key.alias.password", 2048, false),
  710. "The key.alias password, used when signing the release package.");
  711. }
  712. //==============================================================================
  713. void createOtherExporterProperties (PropertyListBuilder& props)
  714. {
  715. props.add (new TextPropertyComponent (androidTheme, "Android Theme", 256, false),
  716. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  717. }
  718. //==============================================================================
  719. String createDefaultClassName() const
  720. {
  721. auto s = project.getBundleIdentifierString().toLowerCase();
  722. if (s.length() > 5
  723. && s.containsChar ('.')
  724. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  725. && ! s.startsWithChar ('.'))
  726. {
  727. if (! s.endsWithChar ('.'))
  728. s << ".";
  729. }
  730. else
  731. {
  732. s = "com.yourcompany.";
  733. }
  734. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRootString(), false, true, false);
  735. }
  736. //==============================================================================
  737. void copyJavaFiles (const OwnedArray<LibraryModule>& modules) const
  738. {
  739. if (auto* coreModule = getCoreModule (modules))
  740. {
  741. auto package = getActivityClassPackage();
  742. auto targetFolder = getTargetFolder();
  743. auto inAppBillingPath = String ("com.android.vending.billing").replaceCharacter ('.', File::getSeparatorChar());
  744. auto javaSourceFolder = coreModule->getFolder().getChildFile ("native").getChildFile ("java");
  745. auto javaInAppBillingTarget = targetFolder.getChildFile ("app/src/main/java").getChildFile (inAppBillingPath);
  746. auto javaTarget = targetFolder.getChildFile ("app/src/main/java")
  747. .getChildFile (package.replaceCharacter ('.', File::getSeparatorChar()));
  748. copyActivityJavaFiles (javaSourceFolder, javaTarget, package);
  749. copyServicesJavaFiles (javaSourceFolder, javaTarget, package);
  750. copyProviderJavaFile (javaSourceFolder, javaTarget, package);
  751. copyAdditionalJavaFiles (javaSourceFolder, javaInAppBillingTarget);
  752. }
  753. }
  754. void copyActivityJavaFiles (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  755. {
  756. if (androidActivityClass.get().toString().contains ("_"))
  757. throw SaveError ("Your Android activity class name or path may not contain any underscores! Try a project name without underscores.");
  758. auto className = getActivityName();
  759. if (className.isEmpty())
  760. throw SaveError ("Invalid Android Activity class name: " + androidActivityClass.get().toString());
  761. createDirectoryOrThrow (targetFolder);
  762. auto javaDestFile = targetFolder.getChildFile (className + ".java");
  763. String juceMidiCode, juceMidiImports, juceRuntimePermissionsCode;
  764. juceMidiImports << newLine;
  765. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  766. {
  767. auto javaAndroidMidi = javaSourceFolder.getChildFile ("AndroidMidi.java");
  768. auto javaRuntimePermissions = javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java");
  769. juceMidiImports << "import android.media.midi.*;" << newLine
  770. << "import android.bluetooth.*;" << newLine
  771. << "import android.bluetooth.le.*;" << newLine;
  772. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  773. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  774. }
  775. else
  776. {
  777. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  778. .loadFileAsString()
  779. .replace ("JuceAppActivity", className);
  780. }
  781. String juceWebViewImports, juceWebViewCodeNative, juceWebViewCode;
  782. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  783. juceWebViewImports << "import android.webkit.WebResourceError;" << newLine;
  784. if (static_cast<int> (androidMinimumSDK.get()) >= 21)
  785. juceWebViewImports << "import android.webkit.WebResourceRequest;" << newLine;
  786. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  787. juceWebViewImports << "import android.webkit.WebResourceResponse;" << newLine;
  788. auto javaWebViewFile = javaSourceFolder.getChildFile ("AndroidWebView.java");
  789. auto juceWebViewCodeAll = javaWebViewFile.loadFileAsString();
  790. if (static_cast<int> (androidMinimumSDK.get()) <= 10)
  791. {
  792. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi1_10", false, false)
  793. .upToFirstOccurrenceOf ("WebViewApi1_10$$", false, false);
  794. }
  795. else
  796. {
  797. if (static_cast<int> (androidMinimumSDK.get()) >= 23)
  798. {
  799. juceWebViewCodeNative << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewNativeApi23", false, false)
  800. .upToFirstOccurrenceOf ("WebViewNativeApi23$$", false, false);
  801. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi23", false, false)
  802. .upToFirstOccurrenceOf ("WebViewApi23$$", false, false);
  803. }
  804. if (static_cast<int> (androidMinimumSDK.get()) >= 21)
  805. {
  806. juceWebViewCodeNative << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewNativeApi21", false, false)
  807. .upToFirstOccurrenceOf ("WebViewNativeApi21$$", false, false);
  808. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi21", false, false)
  809. .upToFirstOccurrenceOf ("WebViewApi21$$", false, false);
  810. }
  811. else
  812. {
  813. juceWebViewCode << juceWebViewCodeAll.fromFirstOccurrenceOf ("$$WebViewApi11_20", false, false)
  814. .upToFirstOccurrenceOf ("WebViewApi11_20$$", false, false);
  815. }
  816. }
  817. auto javaSourceFile = javaSourceFolder.getChildFile ("JuceAppActivity.java");
  818. auto javaSourceLines = StringArray::fromLines (javaSourceFile.loadFileAsString());
  819. {
  820. MemoryOutputStream newFile;
  821. for (const auto& line : javaSourceLines)
  822. {
  823. if (line.contains ("$$JuceAndroidMidiImports$$"))
  824. newFile << juceMidiImports;
  825. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  826. newFile << juceMidiCode;
  827. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  828. newFile << juceRuntimePermissionsCode;
  829. else if (line.contains ("$$JuceAndroidWebViewImports$$"))
  830. newFile << juceWebViewImports;
  831. else if (line.contains ("$$JuceAndroidWebViewNativeCode$$"))
  832. newFile << juceWebViewCodeNative;
  833. else if (line.contains ("$$JuceAndroidWebViewCode$$"))
  834. newFile << juceWebViewCode;
  835. else
  836. newFile << line.replace ("JuceAppActivity", className)
  837. .replace ("package com.juce;", "package " + package + ";") << newLine;
  838. }
  839. javaSourceLines = StringArray::fromLines (newFile.toString());
  840. }
  841. while (javaSourceLines.size() > 2
  842. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  843. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  844. javaSourceLines.remove (javaSourceLines.size() - 1);
  845. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  846. }
  847. void copyAdditionalJavaFiles (const File& sourceFolder, const File& targetFolder) const
  848. {
  849. auto inAppBillingJavaFileName = String ("IInAppBillingService.java");
  850. auto inAppBillingJavaSrcFile = sourceFolder.getChildFile (inAppBillingJavaFileName);
  851. auto inAppBillingJavaDestFile = targetFolder.getChildFile (inAppBillingJavaFileName);
  852. createDirectoryOrThrow (targetFolder);
  853. jassert (inAppBillingJavaSrcFile.existsAsFile());
  854. if (inAppBillingJavaSrcFile.existsAsFile())
  855. inAppBillingJavaSrcFile.copyFileTo (inAppBillingJavaDestFile);
  856. }
  857. void copyServicesJavaFiles (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  858. {
  859. if (androidEnableRemoteNotifications.get())
  860. {
  861. String instanceIdFileName = "JuceFirebaseInstanceIdService.java";
  862. String messagingFileName = "JuceFirebaseMessagingService.java";
  863. File instanceIdFile (javaSourceFolder.getChildFile (instanceIdFileName));
  864. File messagingFile (javaSourceFolder.getChildFile (messagingFileName));
  865. jassert (instanceIdFile.existsAsFile());
  866. jassert (messagingFile .existsAsFile());
  867. Array<File> files;
  868. files.add (instanceIdFile);
  869. files.add (messagingFile);
  870. for (const auto& file : files)
  871. {
  872. auto newContent = file.loadFileAsString()
  873. .replace ("package com.juce;", "package " + package + ";");
  874. auto targetFile = targetFolder.getChildFile (file.getFileName());
  875. overwriteFileIfDifferentOrThrow (targetFile, newContent);
  876. }
  877. }
  878. }
  879. void copyProviderJavaFile (const File& javaSourceFolder, const File& targetFolder, const String& package) const
  880. {
  881. File providerFile (javaSourceFolder.getChildFile ("AndroidSharingContentProvider.java"));
  882. jassert (providerFile.existsAsFile());
  883. auto targetFile = targetFolder.getChildFile ("SharingContentProvider.java");
  884. auto fileContent = providerFile.loadFileAsString()
  885. .replace ("package com.juce;", "package " + package + ";");
  886. auto commonStart = fileContent.upToFirstOccurrenceOf ("$$ContentProviderApi11", false, false);
  887. auto commonEnd = fileContent.fromFirstOccurrenceOf ("ContentProviderApi11$$", false, false);
  888. auto middleContent = static_cast<int> (androidMinimumSDK.get()) >= 11
  889. ? fileContent.fromFirstOccurrenceOf ("$$ContentProviderApi11", false, false)
  890. .upToFirstOccurrenceOf ("ContentProviderApi11$$", false, false)
  891. : String();
  892. auto newContent = commonStart;
  893. newContent << middleContent << commonEnd;
  894. overwriteFileIfDifferentOrThrow (targetFile, newContent);
  895. }
  896. void copyExtraResourceFiles() const
  897. {
  898. for (ConstConfigIterator config (*this); config.next();)
  899. {
  900. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  901. const String xmlValuesPath = cfg.isDebug() ? "app/src/debug/res/values" : "app/src/release/res/values";
  902. const String rawPath = cfg.isDebug() ? "app/src/debug/res/raw" : "app/src/release/res/raw";
  903. copyExtraResourceFiles (cfg.getAdditionalXmlResources(), xmlValuesPath);
  904. copyExtraResourceFiles (cfg.getAdditionalRawResources(), rawPath);
  905. }
  906. if (androidEnableRemoteNotifications.get())
  907. {
  908. File file (getProject().getFile().getChildFile (androidRemoteNotificationsConfigFile.get().toString()));
  909. // Settings file must be present for remote notifications to work and it must be called google-services.json.
  910. jassert (file.existsAsFile() && file.getFileName() == "google-services.json");
  911. copyExtraResourceFiles (androidRemoteNotificationsConfigFile.get(), "app");
  912. }
  913. }
  914. void copyExtraResourceFiles (const String& resources, const String& dstRelativePath) const
  915. {
  916. StringArray resourcePaths;
  917. resourcePaths.addTokens (resources, true);
  918. const File parentFolder (getTargetFolder().getChildFile (dstRelativePath));
  919. parentFolder.createDirectory();
  920. for (const auto& path : resourcePaths)
  921. {
  922. File file (getProject().getFile().getChildFile (path));
  923. jassert (file.existsAsFile());
  924. if (file.existsAsFile())
  925. file.copyFileTo (parentFolder.getChildFile (file.getFileName()));
  926. }
  927. }
  928. String getActivityName() const
  929. {
  930. return androidActivityClass.get().toString().fromLastOccurrenceOf (".", false, false);
  931. }
  932. String getActivitySubClassName() const
  933. {
  934. String activityPath = androidActivitySubClassName.get();
  935. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  936. }
  937. String getActivityClassPackage() const
  938. {
  939. return androidActivityClass.get().toString().upToLastOccurrenceOf (".", false, false);
  940. }
  941. String getJNIActivityClassName() const
  942. {
  943. return androidActivityClass.get().toString().replaceCharacter ('.', '/');
  944. }
  945. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  946. {
  947. for (int i = modules.size(); --i >= 0;)
  948. if (modules.getUnchecked(i)->getID() == "juce_core")
  949. return modules.getUnchecked(i);
  950. return nullptr;
  951. }
  952. //==============================================================================
  953. String getNativeModuleBinaryName (const AndroidBuildConfiguration& config) const
  954. {
  955. return (isLibrary() ? File::createLegalFileName (config.getTargetBinaryNameString().trim()) : "juce_jni");
  956. }
  957. String getAppPlatform() const
  958. {
  959. int ndkVersion = static_cast<int> (androidMinimumSDK.get());
  960. if (ndkVersion == 9)
  961. ndkVersion = 10; // (doesn't seem to be a version '9')
  962. return "android-" + String (ndkVersion);
  963. }
  964. //==============================================================================
  965. void writeStringsXML (const File& folder) const
  966. {
  967. for (ConstConfigIterator config (*this); config.next();)
  968. {
  969. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  970. String customStringsXmlContent = "<resources>\n";
  971. customStringsXmlContent << "<string name=\"app_name\">" << projectName << "</string>\n";
  972. customStringsXmlContent << cfg.getCustomStringsXml();
  973. customStringsXmlContent << "\n</resources>";
  974. ScopedPointer<XmlElement> strings = XmlDocument::parse (customStringsXmlContent);
  975. const juce::String dir = cfg.isDebug() ? "debug" : "release";
  976. const juce::String subPath = "app/src/" + dir + "/res/values/string.xml";
  977. writeXmlOrThrow (*strings, folder.getChildFile (subPath), "utf-8", 100, true);
  978. }
  979. }
  980. void writeAndroidManifest (const File& folder) const
  981. {
  982. ScopedPointer<XmlElement> manifest (createManifestXML());
  983. writeXmlOrThrow (*manifest, folder.getChildFile ("src/main/AndroidManifest.xml"), "utf-8", 100, true);
  984. }
  985. void writeIcon (const File& file, const Image& im) const
  986. {
  987. if (im.isValid())
  988. {
  989. createDirectoryOrThrow (file.getParentDirectory());
  990. PNGImageFormat png;
  991. MemoryOutputStream mo;
  992. if (! png.writeImageToStream (im, mo))
  993. throw SaveError ("Can't generate Android icon file");
  994. overwriteFileIfDifferentOrThrow (file, mo);
  995. }
  996. }
  997. void writeIcons (const File& folder) const
  998. {
  999. ScopedPointer<Drawable> bigIcon (getBigIcon());
  1000. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  1001. if (bigIcon != nullptr && smallIcon != nullptr)
  1002. {
  1003. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  1004. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  1005. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  1006. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  1007. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  1008. }
  1009. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  1010. {
  1011. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  1012. }
  1013. }
  1014. void writeAppIcons (const File& folder) const
  1015. {
  1016. writeIcons (folder.getChildFile ("app/src/main/res/"));
  1017. }
  1018. static String sanitisePath (String path)
  1019. {
  1020. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  1021. }
  1022. static String expandHomeFolderToken (const String& path)
  1023. {
  1024. String homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  1025. return path.replace ("${user.home}", homeFolder)
  1026. .replace ("~", homeFolder);
  1027. }
  1028. //==============================================================================
  1029. void addCompileUnits (const Project::Item& projectItem, MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  1030. {
  1031. if (projectItem.isGroup())
  1032. {
  1033. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  1034. addCompileUnits (projectItem.getChild(i), mo, excludeFromBuild);
  1035. }
  1036. else if (projectItem.shouldBeAddedToTargetProject())
  1037. {
  1038. const RelativePath file (projectItem.getFile(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  1039. const ProjectType::Target::Type targetType = getProject().getTargetTypeFromFilePath (projectItem.getFile(), true);
  1040. mo << " \"" << file.toUnixStyle() << "\"" << newLine;
  1041. if ((! projectItem.shouldBeCompiled()) || (! shouldFileBeCompiledByDefault (file))
  1042. || (getProject().getProjectType().isAudioPlugin()
  1043. && targetType != ProjectType::Target::SharedCodeTarget
  1044. && targetType != ProjectType::Target::StandalonePlugIn))
  1045. excludeFromBuild.add (file);
  1046. }
  1047. }
  1048. void addCompileUnits (MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  1049. {
  1050. for (int i = 0; i < getAllGroups().size(); ++i)
  1051. addCompileUnits (getAllGroups().getReference(i), mo, excludeFromBuild);
  1052. }
  1053. //==============================================================================
  1054. StringArray getCmakeDefinitions() const
  1055. {
  1056. const String toolchain = gradleToolchain.get();
  1057. const bool isClang = (toolchain == "clang");
  1058. StringArray cmakeArgs;
  1059. cmakeArgs.add ("\"-DANDROID_TOOLCHAIN=" + toolchain + "\"");
  1060. cmakeArgs.add ("\"-DANDROID_PLATFORM=" + getAppPlatform() + "\"");
  1061. cmakeArgs.add (String ("\"-DANDROID_STL=") + (isClang ? "c++_static" : "gnustl_static") + "\"");
  1062. cmakeArgs.add ("\"-DANDROID_CPP_FEATURES=exceptions rtti\"");
  1063. cmakeArgs.add ("\"-DANDROID_ARM_MODE=arm\"");
  1064. cmakeArgs.add ("\"-DANDROID_ARM_NEON=TRUE\"");
  1065. return cmakeArgs;
  1066. }
  1067. //==============================================================================
  1068. StringArray getAndroidCompilerFlags() const
  1069. {
  1070. StringArray cFlags;
  1071. cFlags.add ("\"-fsigned-char\"");
  1072. return cFlags;
  1073. }
  1074. StringArray getAndroidCxxCompilerFlags() const
  1075. {
  1076. auto cxxFlags = getAndroidCompilerFlags();
  1077. auto cppStandard = project.getCppStandardString();
  1078. if (cppStandard == "latest")
  1079. cppStandard = "1z";
  1080. cppStandard = "-std=" + String (shouldUseGNUExtensions() ? "gnu++" : "c++") + cppStandard;
  1081. cxxFlags.add (cppStandard.quoted());
  1082. return cxxFlags;
  1083. }
  1084. StringArray getProjectCompilerFlags() const
  1085. {
  1086. StringArray cFlags (getAndroidCompilerFlags());
  1087. cFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  1088. return cFlags;
  1089. }
  1090. StringArray getProjectCxxCompilerFlags() const
  1091. {
  1092. StringArray cxxFlags (getAndroidCxxCompilerFlags());
  1093. cxxFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  1094. return cxxFlags;
  1095. }
  1096. //==============================================================================
  1097. StringPairArray getAndroidPreprocessorDefs() const
  1098. {
  1099. StringPairArray defines;
  1100. defines.set ("JUCE_ANDROID", "1");
  1101. defines.set ("JUCE_ANDROID_API_VERSION", androidMinimumSDK.get());
  1102. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  1103. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\"" + getJNIActivityClassName() + "\"");
  1104. defines.set ("JUCE_ANDROID_SHARING_CONTENT_PROVIDER_CLASSNAME", getSharingContentProviderClassName().replaceCharacter('.', '_'));
  1105. defines.set ("JUCE_ANDROID_SHARING_CONTENT_PROVIDER_CLASSPATH", "\"" + getSharingContentProviderClassName().replaceCharacter('.', '/') + "\"");
  1106. defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");
  1107. if (androidInAppBillingPermission.get())
  1108. defines.set ("JUCE_IN_APP_PURCHASES", "1");
  1109. if (androidEnableRemoteNotifications.get())
  1110. {
  1111. auto instanceIdClassName = getActivityClassPackage() + ".JuceFirebaseInstanceIdService";
  1112. auto messagingClassName = getActivityClassPackage() + ".JuceFirebaseMessagingService";
  1113. defines.set ("JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME", instanceIdClassName.replaceCharacter ('.', '_'));
  1114. defines.set ("JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME", messagingClassName.replaceCharacter ('.', '_'));
  1115. }
  1116. if (supportsGLv3())
  1117. defines.set ("JUCE_ANDROID_GL_ES_VERSION_3_0", "1");
  1118. return defines;
  1119. }
  1120. String getSharingContentProviderClassName() const
  1121. {
  1122. return getActivityClassPackage() + ".SharingContentProvider";
  1123. }
  1124. StringPairArray getProjectPreprocessorDefs() const
  1125. {
  1126. StringPairArray defines (getAndroidPreprocessorDefs());
  1127. return mergePreprocessorDefs (defines, getAllPreprocessorDefs());
  1128. }
  1129. StringPairArray getConfigPreprocessorDefs (const BuildConfiguration& config) const
  1130. {
  1131. StringPairArray cfgDefines (config.getUniquePreprocessorDefs());
  1132. if (config.isDebug())
  1133. {
  1134. cfgDefines.set ("DEBUG", "1");
  1135. cfgDefines.set ("_DEBUG", "1");
  1136. }
  1137. else
  1138. {
  1139. cfgDefines.set ("NDEBUG", "1");
  1140. }
  1141. return cfgDefines;
  1142. }
  1143. //==============================================================================
  1144. StringArray getAndroidLibraries() const
  1145. {
  1146. StringArray libraries;
  1147. libraries.add ("log");
  1148. libraries.add ("android");
  1149. libraries.add (supportsGLv3() ? "GLESv3" : "GLESv2");
  1150. libraries.add ("EGL");
  1151. return libraries;
  1152. }
  1153. //==============================================================================
  1154. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  1155. {
  1156. StringArray paths (extraSearchPaths);
  1157. paths.addArray (config.getHeaderSearchPaths());
  1158. paths = getCleanedStringArray (paths);
  1159. return paths;
  1160. }
  1161. //==============================================================================
  1162. String escapeDirectoryForCmake (const String& path) const
  1163. {
  1164. RelativePath relative =
  1165. RelativePath (path, RelativePath::buildTargetFolder)
  1166. .rebased (getTargetFolder(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  1167. return relative.toUnixStyle();
  1168. }
  1169. void writeCmakePathLines (MemoryOutputStream& mo, const String& prefix, const String& firstLine, const StringArray& paths,
  1170. const String& suffix = ")") const
  1171. {
  1172. if (paths.size() > 0)
  1173. {
  1174. mo << prefix << firstLine << newLine;
  1175. for (auto& path : paths)
  1176. mo << prefix << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  1177. mo << prefix << suffix << newLine << newLine;
  1178. }
  1179. }
  1180. static StringArray getEscapedPreprocessorDefs (const StringPairArray& defs)
  1181. {
  1182. StringArray escapedDefs;
  1183. for (int i = 0; i < defs.size(); ++i)
  1184. {
  1185. String escaped ("\"-D" + defs.getAllKeys()[i]);
  1186. String value = defs.getAllValues()[i];
  1187. if (value.isNotEmpty())
  1188. {
  1189. value = value.replace ("\"", "\\\"");
  1190. if (value.containsChar (L' '))
  1191. value = "\\\"" + value + "\\\"";
  1192. escaped += ("=" + value);
  1193. }
  1194. escapedDefs.add (escaped + "\"");
  1195. }
  1196. return escapedDefs;
  1197. }
  1198. static StringArray getEscapedFlags (const StringArray& flags)
  1199. {
  1200. StringArray escaped;
  1201. for (auto& flag : flags)
  1202. escaped.add ("\"" + flag + "\"");
  1203. return escaped;
  1204. }
  1205. //==============================================================================
  1206. XmlElement* createManifestXML() const
  1207. {
  1208. XmlElement* manifest = createManifestElement();
  1209. createSupportsScreensElement (*manifest);
  1210. createUsesSdkElement (*manifest);
  1211. createPermissionElements (*manifest);
  1212. createOpenGlFeatureElement (*manifest);
  1213. if (! isLibrary())
  1214. {
  1215. auto* app = createApplicationElement (*manifest);
  1216. auto* act = createActivityElement (*app);
  1217. createIntentElement (*act);
  1218. createServiceElements (*app);
  1219. createProviderElement (*app);
  1220. }
  1221. return manifest;
  1222. }
  1223. XmlElement* createManifestElement() const
  1224. {
  1225. XmlElement* manifest = XmlDocument::parse (androidManifestCustomXmlElements.get());
  1226. if (manifest == nullptr)
  1227. manifest = new XmlElement ("manifest");
  1228. setAttributeIfNotPresent (*manifest, "xmlns:android", "http://schemas.android.com/apk/res/android");
  1229. setAttributeIfNotPresent (*manifest, "android:versionCode", androidVersionCode.get());
  1230. setAttributeIfNotPresent (*manifest, "android:versionName", project.getVersionString());
  1231. setAttributeIfNotPresent (*manifest, "package", getActivityClassPackage());
  1232. return manifest;
  1233. }
  1234. void createSupportsScreensElement (XmlElement& manifest) const
  1235. {
  1236. if (! isLibrary())
  1237. {
  1238. if (manifest.getChildByName ("supports-screens") == nullptr)
  1239. {
  1240. XmlElement* screens = manifest.createNewChildElement ("supports-screens");
  1241. screens->setAttribute ("android:smallScreens", "true");
  1242. screens->setAttribute ("android:normalScreens", "true");
  1243. screens->setAttribute ("android:largeScreens", "true");
  1244. screens->setAttribute ("android:anyDensity", "true");
  1245. }
  1246. }
  1247. }
  1248. void createUsesSdkElement (XmlElement& manifest) const
  1249. {
  1250. auto* sdk = getOrCreateChildWithName (manifest, "uses-sdk");
  1251. setAttributeIfNotPresent (*sdk, "android:minSdkVersion", androidMinimumSDK.get());
  1252. setAttributeIfNotPresent (*sdk, "android:targetSdkVersion", androidMinimumSDK.get());
  1253. }
  1254. void createPermissionElements (XmlElement& manifest) const
  1255. {
  1256. StringArray permissions (getPermissionsRequired());
  1257. forEachXmlChildElementWithTagName (manifest, child, "uses-permission")
  1258. {
  1259. permissions.removeString (child->getStringAttribute ("android:name"), false);
  1260. }
  1261. for (int i = permissions.size(); --i >= 0;)
  1262. manifest.createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  1263. }
  1264. void createOpenGlFeatureElement (XmlElement& manifest) const
  1265. {
  1266. if (project.getModules().isModuleEnabled ("juce_opengl"))
  1267. {
  1268. XmlElement* glVersion = nullptr;
  1269. forEachXmlChildElementWithTagName (manifest, child, "uses-feature")
  1270. {
  1271. if (child->getStringAttribute ("android:glEsVersion").isNotEmpty())
  1272. {
  1273. glVersion = child;
  1274. break;
  1275. }
  1276. }
  1277. if (glVersion == nullptr)
  1278. glVersion = manifest.createNewChildElement ("uses-feature");
  1279. setAttributeIfNotPresent (*glVersion, "android:glEsVersion", (static_cast<int> (androidMinimumSDK.get()) >= 18 ? "0x00030000" : "0x00020000"));
  1280. setAttributeIfNotPresent (*glVersion, "android:required", "true");
  1281. }
  1282. }
  1283. XmlElement* createApplicationElement (XmlElement& manifest) const
  1284. {
  1285. auto* app = getOrCreateChildWithName (manifest, "application");
  1286. setAttributeIfNotPresent (*app, "android:label", "@string/app_name");
  1287. if (androidTheme.get().toString().isNotEmpty())
  1288. setAttributeIfNotPresent (*app, "android:theme", androidTheme.get());
  1289. if (! app->hasAttribute ("android:icon"))
  1290. {
  1291. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  1292. if (bigIcon != nullptr || smallIcon != nullptr)
  1293. app->setAttribute ("android:icon", "@drawable/icon");
  1294. }
  1295. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  1296. {
  1297. if (! app->hasAttribute ("android:hardwareAccelerated"))
  1298. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  1299. }
  1300. else
  1301. {
  1302. app->removeAttribute ("android:hardwareAccelerated");
  1303. }
  1304. return app;
  1305. }
  1306. XmlElement* createActivityElement (XmlElement& application) const
  1307. {
  1308. auto* act = getOrCreateChildWithName (application, "activity");
  1309. setAttributeIfNotPresent (*act, "android:name", getActivitySubClassName());
  1310. setAttributeIfNotPresent (*act, "android:label", "@string/app_name");
  1311. if (! act->hasAttribute ("android:configChanges"))
  1312. {
  1313. String configChanges ("keyboardHidden|orientation");
  1314. if (static_cast<int> (androidMinimumSDK.get()) >= 13)
  1315. configChanges += "|screenSize";
  1316. act->setAttribute ("android:configChanges", configChanges);
  1317. }
  1318. else
  1319. {
  1320. auto configChanges = act->getStringAttribute ("android:configChanges");
  1321. if (static_cast<int> (androidMinimumSDK.get()) < 13 && configChanges.contains ("screenSize"))
  1322. {
  1323. configChanges = configChanges.replace ("|screenSize", "")
  1324. .replace ("screenSize|", "")
  1325. .replace ("screenSize", "");
  1326. act->setAttribute ("android:configChanges", configChanges);
  1327. }
  1328. }
  1329. if (androidScreenOrientation.get() == "landscape")
  1330. {
  1331. String landscapeString = static_cast<int> (androidMinimumSDK.get()) < 9
  1332. ? "landscape"
  1333. : (static_cast<int> (androidMinimumSDK.get()) < 18 ? "sensorLandscape" : "userLandscape");
  1334. setAttributeIfNotPresent (*act, "android:screenOrientation", landscapeString);
  1335. }
  1336. else
  1337. {
  1338. setAttributeIfNotPresent (*act, "android:screenOrientation", androidScreenOrientation.get());
  1339. }
  1340. setAttributeIfNotPresent (*act, "android:launchMode", "singleTask");
  1341. // Using the 2D acceleration slows down OpenGL. We *do* enable it here for the activity though, and we disable it
  1342. // in each ComponentPeerView instead. This way any embedded native views, which are not children of ComponentPeerView,
  1343. // can still use hardware acceleration if needed (e.g. web view).
  1344. if (static_cast<int> (androidMinimumSDK.get()) >= 11)
  1345. {
  1346. if (! act->hasAttribute ("android:hardwareAccelerated"))
  1347. act->setAttribute ("android:hardwareAccelerated", "true"); // (using the 2D acceleration slows down openGL)
  1348. }
  1349. else
  1350. {
  1351. act->removeAttribute ("android:hardwareAccelerated");
  1352. }
  1353. return act;
  1354. }
  1355. void createIntentElement (XmlElement& application) const
  1356. {
  1357. auto* intent = getOrCreateChildWithName (application, "intent-filter");
  1358. auto* action = getOrCreateChildWithName (*intent, "action");
  1359. setAttributeIfNotPresent (*action, "android:name", "android.intent.action.MAIN");
  1360. auto* category = getOrCreateChildWithName (*intent, "category");
  1361. setAttributeIfNotPresent (*category, "android:name", "android.intent.category.LAUNCHER");
  1362. }
  1363. void createServiceElements (XmlElement& application) const
  1364. {
  1365. if (androidEnableRemoteNotifications.get())
  1366. {
  1367. auto* service = application.createNewChildElement ("service");
  1368. service->setAttribute ("android:name", ".JuceFirebaseMessagingService");
  1369. auto* intentFilter = service->createNewChildElement ("intent-filter");
  1370. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.MESSAGING_EVENT");
  1371. service = application.createNewChildElement ("service");
  1372. service->setAttribute ("android:name", ".JuceFirebaseInstanceIdService");
  1373. intentFilter = service->createNewChildElement ("intent-filter");
  1374. intentFilter->createNewChildElement ("action")->setAttribute ("android:name", "com.google.firebase.INSTANCE_ID_EVENT");
  1375. auto* metaData = application.createNewChildElement ("meta-data");
  1376. metaData->setAttribute ("android:name", "firebase_analytics_collection_deactivated");
  1377. metaData->setAttribute ("android:value", "true");
  1378. }
  1379. }
  1380. void createProviderElement (XmlElement& application) const
  1381. {
  1382. if (androidEnableContentSharing.get())
  1383. {
  1384. auto* provider = application.createNewChildElement ("provider");
  1385. provider->setAttribute ("android:name", getSharingContentProviderClassName());
  1386. provider->setAttribute ("android:authorities", getSharingContentProviderClassName().toLowerCase());
  1387. provider->setAttribute ("android:grantUriPermissions", "true");
  1388. provider->setAttribute ("android:exported", "false");
  1389. }
  1390. }
  1391. static XmlElement* getOrCreateChildWithName (XmlElement& element, const String& name)
  1392. {
  1393. auto* child = element.getChildByName (name);
  1394. if (child == nullptr)
  1395. child = element.createNewChildElement (name);
  1396. return child;
  1397. }
  1398. static void setAttributeIfNotPresent (XmlElement& element, const Identifier& attribute, const String& value)
  1399. {
  1400. if (! element.hasAttribute (attribute.toString()))
  1401. element.setAttribute (attribute, value);
  1402. }
  1403. StringArray getPermissionsRequired() const
  1404. {
  1405. StringArray s;
  1406. s.addTokens (androidOtherPermissions.get().toString(), ", ", "");
  1407. if (androidInternetNeeded.get())
  1408. s.add ("android.permission.INTERNET");
  1409. if (androidMicNeeded.get())
  1410. s.add ("android.permission.RECORD_AUDIO");
  1411. if (androidBluetoothNeeded.get())
  1412. {
  1413. s.add ("android.permission.BLUETOOTH");
  1414. s.add ("android.permission.BLUETOOTH_ADMIN");
  1415. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  1416. }
  1417. if (androidExternalReadPermission.get())
  1418. s.add ("android.permission.READ_EXTERNAL_STORAGE");
  1419. if (androidExternalWritePermission.get())
  1420. s.add ("android.permission.WRITE_EXTERNAL_STORAGE");
  1421. if (androidInAppBillingPermission.get())
  1422. s.add ("com.android.vending.BILLING");
  1423. if (androidVibratePermission.get())
  1424. s.add ("android.permission.VIBRATE");
  1425. return getCleanedStringArray (s);
  1426. }
  1427. //==============================================================================
  1428. bool isLibrary() const
  1429. {
  1430. return getProject().getProjectType().isDynamicLibrary()
  1431. || getProject().getProjectType().isStaticLibrary();
  1432. }
  1433. static String toGradleList (const StringArray& array)
  1434. {
  1435. StringArray escapedArray;
  1436. for (auto element : array)
  1437. escapedArray.add ("\"" + element.replace ("\\", "\\\\").replace ("\"", "\\\"") + "\"");
  1438. return escapedArray.joinIntoString (", ");
  1439. }
  1440. bool supportsGLv3() const
  1441. {
  1442. return (static_cast<int> (androidMinimumSDK.get()) >= 18);
  1443. }
  1444. //==============================================================================
  1445. Value sdkPath, ndkPath;
  1446. const File AndroidExecutable;
  1447. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  1448. };
  1449. ProjectExporter* createAndroidExporter (Project& p, const ValueTree& t)
  1450. {
  1451. return new AndroidProjectExporter (p, t);
  1452. }
  1453. ProjectExporter* createAndroidExporterForSetting (Project& p, const ValueTree& t)
  1454. {
  1455. return AndroidProjectExporter::createForSettings (p, t);
  1456. }