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.

1511 lines
67KB

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