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.

1332 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. String 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),
  621. Ids::androidSDKPath, TargetOS::getThisOS())));
  622. ndkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidNDKPath),
  623. Ids::androidNDKPath, TargetOS::getThisOS())));
  624. }
  625. //==============================================================================
  626. void copyActivityJavaFiles (const OwnedArray<LibraryModule>& modules, const File& targetFolder, const String& package) const
  627. {
  628. const String className (getActivityName());
  629. if (className.isEmpty())
  630. throw SaveError ("Invalid Android Activity class name: " + androidActivityClass.get());
  631. createDirectoryOrThrow (targetFolder);
  632. LibraryModule* const coreModule = getCoreModule (modules);
  633. if (coreModule != nullptr)
  634. {
  635. File javaDestFile (targetFolder.getChildFile (className + ".java"));
  636. File javaSourceFolder (coreModule->getFolder().getChildFile ("native")
  637. .getChildFile ("java"));
  638. String juceMidiCode, juceMidiImports, juceRuntimePermissionsCode;
  639. juceMidiImports << newLine;
  640. if (androidMinimumSDK.get().getIntValue() >= 23)
  641. {
  642. File javaAndroidMidi (javaSourceFolder.getChildFile ("AndroidMidi.java"));
  643. File javaRuntimePermissions (javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java"));
  644. juceMidiImports << "import android.media.midi.*;" << newLine
  645. << "import android.bluetooth.*;" << newLine
  646. << "import android.bluetooth.le.*;" << newLine;
  647. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  648. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  649. }
  650. else
  651. {
  652. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  653. .loadFileAsString()
  654. .replace ("JuceAppActivity", className);
  655. }
  656. File javaSourceFile (javaSourceFolder.getChildFile ("JuceAppActivity.java"));
  657. StringArray javaSourceLines (StringArray::fromLines (javaSourceFile.loadFileAsString()));
  658. {
  659. MemoryOutputStream newFile;
  660. for (int i = 0; i < javaSourceLines.size(); ++i)
  661. {
  662. const String& line = javaSourceLines[i];
  663. if (line.contains ("$$JuceAndroidMidiImports$$"))
  664. newFile << juceMidiImports;
  665. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  666. newFile << juceMidiCode;
  667. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  668. newFile << juceRuntimePermissionsCode;
  669. else
  670. newFile << line.replace ("JuceAppActivity", className)
  671. .replace ("package com.juce;", "package " + package + ";") << newLine;
  672. }
  673. javaSourceLines = StringArray::fromLines (newFile.toString());
  674. }
  675. while (javaSourceLines.size() > 2
  676. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  677. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  678. javaSourceLines.remove (javaSourceLines.size() - 1);
  679. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  680. }
  681. }
  682. String getActivityName() const
  683. {
  684. return androidActivityClass.get().fromLastOccurrenceOf (".", false, false);
  685. }
  686. String getActivitySubClassName() const
  687. {
  688. String activityPath = androidActivitySubClassName.get();
  689. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  690. }
  691. String getActivityClassPackage() const
  692. {
  693. return androidActivityClass.get().upToLastOccurrenceOf (".", false, false);
  694. }
  695. String getJNIActivityClassName() const
  696. {
  697. return androidActivityClass.get().replaceCharacter ('.', '/');
  698. }
  699. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  700. {
  701. for (int i = modules.size(); --i >= 0;)
  702. if (modules.getUnchecked(i)->getID() == "juce_core")
  703. return modules.getUnchecked(i);
  704. return nullptr;
  705. }
  706. //==============================================================================
  707. String getNativeModuleBinaryName (const AndroidBuildConfiguration& config) const
  708. {
  709. return (isLibrary() ? File::createLegalFileName (config.getTargetBinaryNameString().trim()) : "juce_jni");
  710. }
  711. String getAppPlatform() const
  712. {
  713. int ndkVersion = androidMinimumSDK.get().getIntValue();
  714. if (ndkVersion == 9)
  715. ndkVersion = 10; // (doesn't seem to be a version '9')
  716. return "android-" + String (ndkVersion);
  717. }
  718. //==============================================================================
  719. void writeStringsXML (const File& folder) const
  720. {
  721. XmlElement strings ("resources");
  722. XmlElement* resourceName = strings.createNewChildElement ("string");
  723. resourceName->setAttribute ("name", "app_name");
  724. resourceName->addTextElement (projectName);
  725. writeXmlOrThrow (strings, folder.getChildFile ("app/src/main/res/values/string.xml"), "utf-8", 100, true);
  726. }
  727. void writeAndroidManifest (const File& folder) const
  728. {
  729. ScopedPointer<XmlElement> manifest (createManifestXML());
  730. writeXmlOrThrow (*manifest, folder.getChildFile ("src/main/AndroidManifest.xml"), "utf-8", 100, true);
  731. }
  732. void writeIcon (const File& file, const Image& im) const
  733. {
  734. if (im.isValid())
  735. {
  736. createDirectoryOrThrow (file.getParentDirectory());
  737. PNGImageFormat png;
  738. MemoryOutputStream mo;
  739. if (! png.writeImageToStream (im, mo))
  740. throw SaveError ("Can't generate Android icon file");
  741. overwriteFileIfDifferentOrThrow (file, mo);
  742. }
  743. }
  744. void writeIcons (const File& folder) const
  745. {
  746. ScopedPointer<Drawable> bigIcon (getBigIcon());
  747. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  748. if (bigIcon != nullptr && smallIcon != nullptr)
  749. {
  750. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  751. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  752. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  753. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  754. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  755. }
  756. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  757. {
  758. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  759. }
  760. }
  761. void writeAppIcons (const File& folder) const
  762. {
  763. writeIcons (folder.getChildFile ("app/src/main/res/"));
  764. }
  765. static String sanitisePath (String path)
  766. {
  767. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  768. }
  769. static String expandHomeFolderToken (const String& path)
  770. {
  771. String homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  772. return path.replace ("${user.home}", homeFolder)
  773. .replace ("~", homeFolder);
  774. }
  775. //==============================================================================
  776. void addCompileUnits (const Project::Item& projectItem, MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  777. {
  778. if (projectItem.isGroup())
  779. {
  780. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  781. addCompileUnits (projectItem.getChild(i), mo, excludeFromBuild);
  782. }
  783. else if (projectItem.shouldBeAddedToTargetProject())
  784. {
  785. const RelativePath file (projectItem.getFile(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  786. const ProjectType::Target::Type targetType = getProject().getTargetTypeFromFilePath (projectItem.getFile(), true);
  787. mo << " \"" << file.toUnixStyle() << "\"" << newLine;
  788. if ((! projectItem.shouldBeCompiled()) || (! shouldFileBeCompiledByDefault (file))
  789. || (getProject().getProjectType().isAudioPlugin()
  790. && targetType != ProjectType::Target::SharedCodeTarget
  791. && targetType != ProjectType::Target::StandalonePlugIn))
  792. excludeFromBuild.add (file);
  793. }
  794. }
  795. void addCompileUnits (MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  796. {
  797. for (int i = 0; i < getAllGroups().size(); ++i)
  798. addCompileUnits (getAllGroups().getReference(i), mo, excludeFromBuild);
  799. }
  800. //==============================================================================
  801. StringArray getCmakeDefinitions() const
  802. {
  803. const String toolchain = gradleToolchain.get();
  804. const bool isClang = (toolchain == "clang");
  805. StringArray cmakeArgs;
  806. cmakeArgs.add ("\"-DANDROID_TOOLCHAIN=" + toolchain + "\"");
  807. cmakeArgs.add ("\"-DANDROID_PLATFORM=" + getAppPlatform() + "\"");
  808. cmakeArgs.add (String ("\"-DANDROID_STL=") + (isClang ? "c++_static" : "gnustl_static") + "\"");
  809. cmakeArgs.add ("\"-DANDROID_CPP_FEATURES=exceptions rtti\"");
  810. cmakeArgs.add ("\"-DANDROID_ARM_MODE=arm\"");
  811. cmakeArgs.add ("\"-DANDROID_ARM_NEON=TRUE\"");
  812. return cmakeArgs;
  813. }
  814. //==============================================================================
  815. StringArray getAndroidCompilerFlags() const
  816. {
  817. StringArray cFlags;
  818. cFlags.add ("\"-fsigned-char\"");
  819. return cFlags;
  820. }
  821. StringArray getAndroidCxxCompilerFlags() const
  822. {
  823. StringArray cxxFlags (getAndroidCompilerFlags());
  824. String cppStandardToUse (getCppStandardString());
  825. if (cppStandardToUse.isEmpty())
  826. cppStandardToUse = "-std=c++11";
  827. cxxFlags.add ("\"" + cppStandardToUse + "\"");
  828. return cxxFlags;
  829. }
  830. StringArray getProjectCompilerFlags() const
  831. {
  832. StringArray cFlags (getAndroidCompilerFlags());
  833. cFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  834. return cFlags;
  835. }
  836. StringArray getProjectCxxCompilerFlags() const
  837. {
  838. StringArray cxxFlags (getAndroidCxxCompilerFlags());
  839. cxxFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  840. return cxxFlags;
  841. }
  842. //==============================================================================
  843. StringPairArray getAndroidPreprocessorDefs() const
  844. {
  845. StringPairArray defines;
  846. defines.set ("JUCE_ANDROID", "1");
  847. defines.set ("JUCE_ANDROID_API_VERSION", androidMinimumSDK.get());
  848. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  849. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\"" + getJNIActivityClassName() + "\"");
  850. if (supportsGLv3())
  851. defines.set ("JUCE_ANDROID_GL_ES_VERSION_3_0", "1");
  852. return defines;
  853. }
  854. StringPairArray getProjectPreprocessorDefs() const
  855. {
  856. StringPairArray defines (getAndroidPreprocessorDefs());
  857. return mergePreprocessorDefs (defines, getProject().getPreprocessorDefs());
  858. }
  859. StringPairArray getConfigPreprocessorDefs (const BuildConfiguration& config) const
  860. {
  861. StringPairArray cfgDefines (config.getUniquePreprocessorDefs());
  862. if (config.isDebug())
  863. {
  864. cfgDefines.set ("DEBUG", "1");
  865. cfgDefines.set ("_DEBUG", "1");
  866. }
  867. else
  868. {
  869. cfgDefines.set ("NDEBUG", "1");
  870. }
  871. return cfgDefines;
  872. }
  873. //==============================================================================
  874. StringArray getAndroidLibraries() const
  875. {
  876. StringArray libraries;
  877. libraries.add ("log");
  878. libraries.add ("android");
  879. libraries.add (supportsGLv3() ? "GLESv3" : "GLESv2");
  880. libraries.add ("EGL");
  881. return libraries;
  882. }
  883. //==============================================================================
  884. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  885. {
  886. StringArray paths (extraSearchPaths);
  887. paths.addArray (config.getHeaderSearchPaths());
  888. paths = getCleanedStringArray (paths);
  889. return paths;
  890. }
  891. //==============================================================================
  892. String escapeDirectoryForCmake (const String& path) const
  893. {
  894. RelativePath relative =
  895. RelativePath (path, RelativePath::buildTargetFolder)
  896. .rebased (getTargetFolder(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  897. return relative.toUnixStyle();
  898. }
  899. void writeCmakePathLines (MemoryOutputStream& mo, const String& prefix, const String& firstLine, const StringArray& paths,
  900. const String& suffix = ")") const
  901. {
  902. if (paths.size() > 0)
  903. {
  904. mo << prefix << firstLine << newLine;
  905. for (auto& path : paths)
  906. mo << prefix << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  907. mo << prefix << suffix << newLine << newLine;
  908. }
  909. }
  910. static StringArray getEscapedPreprocessorDefs (const StringPairArray& defs)
  911. {
  912. StringArray escapedDefs;
  913. for (int i = 0; i < defs.size(); ++i)
  914. {
  915. String escaped ("\"-D" + defs.getAllKeys()[i]);
  916. String value = defs.getAllValues()[i];
  917. if (value.isNotEmpty())
  918. {
  919. value = value.replace ("\"", "\\\"");
  920. if (value.containsChar (L' '))
  921. value = "\\\"" + value + "\\\"";
  922. escaped += ("=" + value + "\"");
  923. }
  924. escapedDefs.add (escaped);
  925. }
  926. return escapedDefs;
  927. }
  928. static StringArray getEscapedFlags (const StringArray& flags)
  929. {
  930. StringArray escaped;
  931. for (auto& flag : flags)
  932. escaped.add ("\"" + flag + "\"");
  933. return escaped;
  934. }
  935. //==============================================================================
  936. XmlElement* createManifestXML() const
  937. {
  938. XmlElement* manifest = new XmlElement ("manifest");
  939. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  940. manifest->setAttribute ("android:versionCode", androidVersionCode.get());
  941. manifest->setAttribute ("android:versionName", project.getVersionString());
  942. manifest->setAttribute ("package", getActivityClassPackage());
  943. if (! isLibrary())
  944. {
  945. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  946. screens->setAttribute ("android:smallScreens", "true");
  947. screens->setAttribute ("android:normalScreens", "true");
  948. screens->setAttribute ("android:largeScreens", "true");
  949. screens->setAttribute ("android:anyDensity", "true");
  950. }
  951. XmlElement* sdk = manifest->createNewChildElement ("uses-sdk");
  952. sdk->setAttribute ("android:minSdkVersion", androidMinimumSDK.get());
  953. sdk->setAttribute ("android:targetSdkVersion", androidMinimumSDK.get());
  954. {
  955. const StringArray permissions (getPermissionsRequired());
  956. for (int i = permissions.size(); --i >= 0;)
  957. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  958. }
  959. if (project.getModules().isModuleEnabled ("juce_opengl"))
  960. {
  961. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  962. feature->setAttribute ("android:glEsVersion", (androidMinimumSDK.get().getIntValue() >= 18 ? "0x00030000" : "0x00020000"));
  963. feature->setAttribute ("android:required", "true");
  964. }
  965. if (! isLibrary())
  966. {
  967. XmlElement* app = manifest->createNewChildElement ("application");
  968. app->setAttribute ("android:label", "@string/app_name");
  969. if (androidTheme.get().isNotEmpty())
  970. app->setAttribute ("android:theme", androidTheme.get());
  971. {
  972. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  973. if (bigIcon != nullptr || smallIcon != nullptr)
  974. app->setAttribute ("android:icon", "@drawable/icon");
  975. }
  976. if (androidMinimumSDK.get().getIntValue() >= 11)
  977. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  978. XmlElement* act = app->createNewChildElement ("activity");
  979. act->setAttribute ("android:name", getActivitySubClassName());
  980. act->setAttribute ("android:label", "@string/app_name");
  981. String configChanges ("keyboardHidden|orientation");
  982. if (androidMinimumSDK.get().getIntValue() >= 13)
  983. configChanges += "|screenSize";
  984. act->setAttribute ("android:configChanges", configChanges);
  985. act->setAttribute ("android:screenOrientation", androidScreenOrientation.get());
  986. XmlElement* intent = act->createNewChildElement ("intent-filter");
  987. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  988. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  989. }
  990. return manifest;
  991. }
  992. StringArray getPermissionsRequired() const
  993. {
  994. StringArray s;
  995. s.addTokens (androidOtherPermissions.get(), ", ", "");
  996. if (androidInternetNeeded.get())
  997. s.add ("android.permission.INTERNET");
  998. if (androidMicNeeded.get())
  999. s.add ("android.permission.RECORD_AUDIO");
  1000. if (androidBluetoothNeeded.get())
  1001. {
  1002. s.add ("android.permission.BLUETOOTH");
  1003. s.add ("android.permission.BLUETOOTH_ADMIN");
  1004. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  1005. }
  1006. return getCleanedStringArray (s);
  1007. }
  1008. //==============================================================================
  1009. bool isLibrary() const
  1010. {
  1011. return getProject().getProjectType().isDynamicLibrary()
  1012. || getProject().getProjectType().isStaticLibrary();
  1013. }
  1014. static String toGradleList (const StringArray& array)
  1015. {
  1016. StringArray escapedArray;
  1017. for (auto element : array)
  1018. escapedArray.add ("\"" + element.replace ("\\", "\\\\").replace ("\"", "\\\"") + "\"");
  1019. return escapedArray.joinIntoString (", ");
  1020. }
  1021. bool supportsGLv3() const
  1022. {
  1023. return (androidMinimumSDK.get().getIntValue() >= 18);
  1024. }
  1025. //==============================================================================
  1026. Value sdkPath, ndkPath;
  1027. const File AndroidExecutable;
  1028. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  1029. };
  1030. ProjectExporter* createAndroidExporter (Project& p, const ValueTree& t)
  1031. {
  1032. return new AndroidProjectExporter (p, t);
  1033. }
  1034. ProjectExporter* createAndroidExporterForSetting (Project& p, const ValueTree& t)
  1035. {
  1036. return AndroidProjectExporter::createForSettings (p, t);
  1037. }