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.

1467 lines
65KB

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