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.

2019 lines
93KB

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