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.

1497 lines
66KB

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