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.

1325 lines
58KB

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