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.

1330 lines
58KB

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