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.

1355 lines
60KB

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