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.

1698 lines
76KB

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