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.

1340 lines
59KB

  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. mo << "add_library(\"cpufeatures\" STATIC \"${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c\")" << newLine << newLine;
  285. {
  286. StringArray projectDefines (getEscapedPreprocessorDefs (getProjectPreprocessorDefs()));
  287. if (projectDefines.size() > 0)
  288. mo << "add_definitions(" << projectDefines.joinIntoString (" ") << ")" << newLine << newLine;
  289. }
  290. {
  291. mo << "include_directories( AFTER" << newLine;
  292. for (auto& path : extraSearchPaths)
  293. mo << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  294. mo << " \"${ANDROID_NDK}/sources/android/cpufeatures\"" << newLine;
  295. mo << ")" << newLine << newLine;
  296. }
  297. const String& cfgExtraLinkerFlags = getExtraLinkerFlagsString();
  298. if (cfgExtraLinkerFlags.isNotEmpty())
  299. {
  300. mo << "SET( JUCE_LDFLAGS \"" << cfgExtraLinkerFlags.replace ("\"", "\\\"") << "\")" << newLine;
  301. mo << "SET( CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${JUCE_LDFLAGS}\")" << newLine << newLine;
  302. }
  303. const StringArray userLibraries = StringArray::fromTokens(getExternalLibrariesString(), ";", "");
  304. if (getNumConfigurations() > 0)
  305. {
  306. bool first = true;
  307. for (ConstConfigIterator config (*this); config.next();)
  308. {
  309. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  310. const StringArray& libSearchPaths = cfg.getLibrarySearchPaths();
  311. const StringPairArray& cfgDefines = getConfigPreprocessorDefs (cfg);
  312. const StringArray& cfgHeaderPaths = cfg.getHeaderSearchPaths();
  313. const StringArray& cfgLibraryPaths = cfg.getLibrarySearchPaths();
  314. if (! isLibrary() && libSearchPaths.size() == 0 && cfgDefines.size() == 0
  315. && cfgHeaderPaths.size() == 0 && cfgLibraryPaths.size() == 0)
  316. continue;
  317. mo << (first ? "IF" : "ELSEIF") << "(JUCE_BUILD_CONFIGFURATION MATCHES \"" << cfg.getProductFlavourCMakeIdentifier() <<"\")" << newLine;
  318. if (isLibrary())
  319. mo << " SET(BINARY_NAME \"" << getNativeModuleBinaryName (cfg) << "\")" << newLine;
  320. writeCmakePathLines (mo, " ", "link_directories(", libSearchPaths);
  321. if (cfgDefines.size() > 0)
  322. mo << " add_definitions(" << getEscapedPreprocessorDefs (cfgDefines).joinIntoString (" ") << ")" << newLine;
  323. writeCmakePathLines (mo, " ", "include_directories( AFTER", cfgHeaderPaths);
  324. if (userLibraries.size() > 0)
  325. {
  326. for (auto& lib : userLibraries)
  327. {
  328. String findLibraryCmd;
  329. findLibraryCmd << "find_library(" << lib.toLowerCase().replaceCharacter (L' ', L'_')
  330. << " \"" << lib << "\" PATHS";
  331. writeCmakePathLines (mo, " ", findLibraryCmd, cfgLibraryPaths, " NO_CMAKE_FIND_ROOT_PATH)");
  332. }
  333. mo << newLine;
  334. }
  335. first = false;
  336. }
  337. if (! first)
  338. {
  339. ProjectExporter::BuildConfiguration::Ptr config (getConfiguration(0));
  340. if (config)
  341. {
  342. if (const auto* cfg = dynamic_cast<const AndroidBuildConfiguration*> (config.get()))
  343. {
  344. mo << "ELSE(JUCE_BUILD_CONFIGFURATION MATCHES \"" << cfg->getProductFlavourCMakeIdentifier() <<"\")" << newLine;
  345. mo << " MESSAGE( FATAL_ERROR \"No matching build-configuration found.\" )" << newLine;
  346. mo << "ENDIF(JUCE_BUILD_CONFIGFURATION MATCHES \"" << cfg->getProductFlavourCMakeIdentifier() <<"\")" << newLine << newLine;
  347. }
  348. }
  349. }
  350. }
  351. Array<RelativePath> excludeFromBuild;
  352. mo << "add_library( ${BINARY_NAME}" << newLine;
  353. mo << newLine;
  354. mo << " " << (getProject().getProjectType().isStaticLibrary() ? "STATIC" : "SHARED") << newLine;
  355. mo << newLine;
  356. addCompileUnits (mo, excludeFromBuild);
  357. mo << ")" << newLine << newLine;
  358. if (excludeFromBuild.size() > 0)
  359. {
  360. for (auto& exclude : excludeFromBuild)
  361. mo << "set_source_files_properties(\"" << exclude.toUnixStyle() << "\" PROPERTIES HEADER_FILE_ONLY TRUE)" << newLine;
  362. mo << newLine;
  363. }
  364. StringArray libraries (getAndroidLibraries());
  365. if (libraries.size() > 0)
  366. {
  367. for (auto& lib : libraries)
  368. mo << "find_library(" << lib.toLowerCase().replaceCharacter (L' ', L'_') << " \"" << lib << "\")" << newLine;
  369. mo << newLine;
  370. }
  371. libraries.addArray (userLibraries);
  372. mo << "target_link_libraries( ${BINARY_NAME}";
  373. if (libraries.size() > 0)
  374. {
  375. mo << newLine << newLine;
  376. for (auto& lib : libraries)
  377. mo << " ${" << lib.toLowerCase().replaceCharacter (L' ', L'_') << "}" << newLine;
  378. mo << " \"cpufeatures\"" << newLine;
  379. }
  380. mo << ")" << newLine;
  381. overwriteFileIfDifferentOrThrow (file, mo);
  382. }
  383. //==============================================================================
  384. String getProjectBuildGradleFileContent() const
  385. {
  386. MemoryOutputStream mo;
  387. mo << "buildscript {" << newLine;
  388. mo << " repositories {" << newLine;
  389. mo << " jcenter()" << newLine;
  390. mo << " }" << newLine;
  391. mo << " dependencies {" << newLine;
  392. mo << " classpath 'com.android.tools.build:gradle:" << androidPluginVersion.get() << "'" << newLine;
  393. mo << " }" << newLine;
  394. mo << "}" << newLine;
  395. mo << "" << newLine;
  396. mo << "allprojects {" << newLine;
  397. mo << " repositories {" << newLine;
  398. mo << " jcenter()" << newLine;
  399. mo << " }" << newLine;
  400. mo << "}" << newLine;
  401. return mo.toString();
  402. }
  403. //==============================================================================
  404. String getAppBuildGradleFileContent() const
  405. {
  406. MemoryOutputStream mo;
  407. mo << "apply plugin: 'com.android." << (isLibrary() ? "library" : "application") << "'" << newLine << newLine;
  408. mo << "android {" << newLine;
  409. mo << " compileSdkVersion " << androidMinimumSDK.get().getIntValue() << newLine;
  410. mo << " buildToolsVersion \"" << buildToolsVersion.get() << "\"" << newLine;
  411. mo << " externalNativeBuild {" << newLine;
  412. mo << " cmake {" << newLine;
  413. mo << " path \"CMakeLists.txt\"" << newLine;
  414. mo << " }" << newLine;
  415. mo << " }" << newLine;
  416. mo << getAndroidSigningConfig() << newLine;
  417. mo << getAndroidDefaultConfig() << newLine;
  418. mo << getAndroidBuildTypes() << newLine;
  419. mo << getAndroidProductFlavours() << newLine;
  420. mo << getAndroidVariantFilter() << newLine;
  421. mo << "}" << newLine;
  422. return mo.toString();
  423. }
  424. String getAndroidProductFlavours() const
  425. {
  426. MemoryOutputStream mo;
  427. mo << " productFlavors {" << newLine;
  428. for (ConstConfigIterator config (*this); config.next();)
  429. {
  430. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  431. mo << " " << cfg.getProductFlavourNameIdentifier() << " {" << newLine;
  432. if (cfg.getArchitectures().isNotEmpty())
  433. {
  434. mo << " ndk {" << newLine;
  435. mo << " abiFilters " << toGradleList (StringArray::fromTokens (cfg.getArchitectures(), " ", "")) << newLine;
  436. mo << " }" << newLine;
  437. }
  438. mo << " externalNativeBuild {" << newLine;
  439. mo << " cmake {" << newLine;
  440. if (getProject().getProjectType().isStaticLibrary())
  441. mo << " targets \"" << getNativeModuleBinaryName (cfg) << "\"" << newLine;
  442. mo << " arguments \"-DJUCE_BUILD_CONFIGFURATION=" << cfg.getProductFlavourCMakeIdentifier() << "\"" << newLine;
  443. mo << " cFlags \"-O" << cfg.getGCCOptimisationFlag() << "\"" << newLine;
  444. mo << " cppFlags \"-O" << cfg.getGCCOptimisationFlag() << "\"" << newLine;
  445. mo << " }" << newLine;
  446. mo << " }" << newLine;
  447. mo << " }" << newLine;
  448. }
  449. mo << " }" << newLine;
  450. return mo.toString();
  451. }
  452. String getAndroidSigningConfig() const
  453. {
  454. MemoryOutputStream mo;
  455. String keyStoreFilePath = androidKeyStore.get().replace ("${user.home}", "${System.properties['user.home']}")
  456. .replace ("/", "${File.separator}");
  457. mo << " signingConfigs {" << newLine;
  458. mo << " release {" << newLine;
  459. mo << " storeFile file(\"" << keyStoreFilePath << "\")" << newLine;
  460. mo << " storePassword \"" << androidKeyStorePass.get() << "\"" << newLine;
  461. mo << " keyAlias \"" << androidKeyAlias.get() << "\"" << newLine;
  462. mo << " keyPassword \"" << androidKeyAliasPass.get() << "\"" << newLine;
  463. mo << " storeType \"jks\"" << newLine;
  464. mo << " }" << newLine;
  465. mo << " }" << newLine;
  466. return mo.toString();
  467. }
  468. String getAndroidDefaultConfig() const
  469. {
  470. const String bundleIdentifier = project.getBundleIdentifier().toString().toLowerCase();
  471. const StringArray& cmakeDefs = getCmakeDefinitions();
  472. const StringArray& cFlags = getProjectCompilerFlags();
  473. const StringArray& cxxFlags = getProjectCxxCompilerFlags();
  474. const int minSdkVersion = androidMinimumSDK.get().getIntValue();
  475. MemoryOutputStream mo;
  476. mo << " defaultConfig {" << newLine;
  477. if (! isLibrary())
  478. mo << " applicationId \"" << bundleIdentifier << "\"" << newLine;
  479. mo << " minSdkVersion " << minSdkVersion << newLine;
  480. mo << " targetSdkVersion " << minSdkVersion << newLine;
  481. mo << " externalNativeBuild {" << newLine;
  482. mo << " cmake {" << newLine;
  483. mo << " arguments " << cmakeDefs.joinIntoString (", ") << newLine;
  484. if (cFlags.size() > 0)
  485. mo << " cFlags " << cFlags.joinIntoString (", ") << newLine;
  486. if (cxxFlags.size() > 0)
  487. mo << " cppFlags " << cxxFlags.joinIntoString (", ") << newLine;
  488. mo << " }" << newLine;
  489. mo << " }" << newLine;
  490. mo << " }" << newLine;
  491. return mo.toString();
  492. }
  493. String getAndroidBuildTypes() const
  494. {
  495. MemoryOutputStream mo;
  496. mo << " buildTypes {" << newLine;
  497. int numDebugConfigs = 0;
  498. const int numConfigs = getNumConfigurations();
  499. for (int i = 0; i < numConfigs; ++i)
  500. {
  501. auto config = getConfiguration(i);
  502. if (config->isDebug()) numDebugConfigs++;
  503. if (numDebugConfigs > 1 || ((numConfigs - numDebugConfigs) > 1))
  504. continue;
  505. mo << " " << (config->isDebug() ? "debug" : "release") << " {" << newLine;
  506. mo << " initWith " << (config->isDebug() ? "debug" : "release") << newLine;
  507. mo << " debuggable " << (config->isDebug() ? "true" : "false") << newLine;
  508. mo << " jniDebuggable " << (config->isDebug() ? "true" : "false") << newLine;
  509. if (! config->isDebug())
  510. mo << " signingConfig signingConfigs.release" << newLine;
  511. mo << " }" << newLine;
  512. }
  513. mo << " }" << newLine;
  514. return mo.toString();
  515. }
  516. String getAndroidVariantFilter() const
  517. {
  518. MemoryOutputStream mo;
  519. mo << " variantFilter { variant ->" << newLine;
  520. mo << " def names = variant.flavors*.name" << newLine;
  521. for (ConstConfigIterator config (*this); config.next();)
  522. {
  523. const auto& cfg = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  524. mo << " if (names.contains (\"" << cfg.getProductFlavourNameIdentifier() << "\")" << newLine;
  525. mo << " && variant.buildType.name != \"" << (cfg.isDebug() ? "debug" : "release") << "\") {" << newLine;
  526. mo << " setIgnore(true)" << newLine;
  527. mo << " }" << newLine;
  528. }
  529. mo << " }" << newLine;
  530. return mo.toString();
  531. }
  532. //==============================================================================
  533. String getLocalPropertiesFileContent() const
  534. {
  535. String props;
  536. props << "ndk.dir=" << sanitisePath (ndkPath.toString()) << newLine
  537. << "sdk.dir=" << sanitisePath (sdkPath.toString()) << newLine;
  538. return props;
  539. }
  540. String getGradleWrapperPropertiesFileContent() const
  541. {
  542. String props;
  543. props << "distributionUrl=https\\://services.gradle.org/distributions/gradle-"
  544. << gradleVersion.get() << "-all.zip";
  545. return props;
  546. }
  547. //==============================================================================
  548. void createBaseExporterProperties (PropertyListBuilder& props)
  549. {
  550. static const char* orientations[] = { "Portrait and Landscape", "Portrait", "Landscape", nullptr };
  551. static const char* orientationValues[] = { "unspecified", "portrait", "landscape", nullptr };
  552. props.add (new ChoicePropertyComponent (androidScreenOrientation.getPropertyAsValue(), "Screen orientation", StringArray (orientations), Array<var> (orientationValues)),
  553. "The screen orientations that this app should support");
  554. props.add (new TextWithDefaultPropertyComponent<String> (androidActivityClass, "Android Activity class name", 256),
  555. "The full java class name to use for the app's Activity class.");
  556. props.add (new TextPropertyComponent (androidActivitySubClassName.getPropertyAsValue(), "Android Activity sub-class name", 256, false),
  557. "If not empty, specifies the Android Activity class name stored in the app's manifest. "
  558. "Use this if you would like to use your own Android Activity sub-class.");
  559. props.add (new TextWithDefaultPropertyComponent<String> (androidVersionCode, "Android Version Code", 32),
  560. "An integer value that represents the version of the application code, relative to other versions.");
  561. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), sdkPath, "Android SDK Path"),
  562. "The path to the Android SDK folder on the target build machine");
  563. props.add (new DependencyPathPropertyComponent (project.getFile().getParentDirectory(), ndkPath, "Android NDK Path"),
  564. "The path to the Android NDK folder on the target build machine");
  565. props.add (new TextWithDefaultPropertyComponent<String> (androidMinimumSDK, "Minimum SDK version", 32),
  566. "The number of the minimum version of the Android SDK that the app requires");
  567. props.add (new TextPropertyComponent (androidExtraAssetsFolder.getPropertyAsValue(), "Extra Android Assets", 256, false),
  568. "A path to a folder (relative to the project folder) which conatins extra android assets.");
  569. }
  570. //==============================================================================
  571. void createManifestExporterProperties (PropertyListBuilder& props)
  572. {
  573. props.add (new BooleanPropertyComponent (androidInternetNeeded.getPropertyAsValue(), "Internet Access", "Specify internet access permission in the manifest"),
  574. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  575. props.add (new BooleanPropertyComponent (androidMicNeeded.getPropertyAsValue(), "Audio Input Required", "Specify audio record permission in the manifest"),
  576. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  577. props.add (new BooleanPropertyComponent (androidBluetoothNeeded.getPropertyAsValue(), "Bluetooth permissions Required", "Specify bluetooth permission (required for Bluetooth MIDI)"),
  578. "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.");
  579. props.add (new TextPropertyComponent (androidOtherPermissions.getPropertyAsValue(), "Custom permissions", 2048, false),
  580. "A space-separated list of other permission flags that should be added to the manifest.");
  581. }
  582. //==============================================================================
  583. void createCodeSigningExporterProperties (PropertyListBuilder& props)
  584. {
  585. props.add (new TextWithDefaultPropertyComponent<String> (androidKeyStore, "Key Signing: key.store", 2048),
  586. "The key.store value, used when signing the release package.");
  587. props.add (new TextWithDefaultPropertyComponent<String> (androidKeyStorePass, "Key Signing: key.store.password", 2048),
  588. "The key.store password, used when signing the release package.");
  589. props.add (new TextWithDefaultPropertyComponent<String> (androidKeyAlias, "Key Signing: key.alias", 2048),
  590. "The key.alias value, used when signing the release package.");
  591. props.add (new TextWithDefaultPropertyComponent<String> (androidKeyAliasPass, "Key Signing: key.alias.password", 2048),
  592. "The key.alias password, used when signing the release package.");
  593. }
  594. //==============================================================================
  595. void createOtherExporterProperties (PropertyListBuilder& props)
  596. {
  597. props.add (new TextPropertyComponent (androidTheme.getPropertyAsValue(), "Android Theme", 256, false),
  598. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  599. static const char* cppStandardNames[] = { "C++03", "C++11", "C++14", nullptr };
  600. static const char* cppStandardValues[] = { "-std=c++03", "-std=c++11", "-std=c++14", nullptr };
  601. props.add (new ChoicePropertyComponent (getCppStandardValue(), "C++ standard to use",
  602. StringArray (cppStandardNames), Array<var> (cppStandardValues)),
  603. "The C++ standard to specify in the makefile");
  604. }
  605. //==============================================================================
  606. Value getCppStandardValue() { return getSetting (Ids::cppLanguageStandard); }
  607. String getCppStandardString() const { return settings[Ids::cppLanguageStandard]; }
  608. //==============================================================================
  609. String createDefaultClassName() const
  610. {
  611. auto s = project.getBundleIdentifier().toString().toLowerCase();
  612. if (s.length() > 5
  613. && s.containsChar ('.')
  614. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  615. && ! s.startsWithChar ('.'))
  616. {
  617. if (! s.endsWithChar ('.'))
  618. s << ".";
  619. }
  620. else
  621. {
  622. s = "com.yourcompany.";
  623. }
  624. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRoot(), false, true, false);
  625. }
  626. void initialiseDependencyPathValues()
  627. {
  628. sdkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidSDKPath), Ids::androidSDKPath, TargetOS::getThisOS())));
  629. ndkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidNDKPath), Ids::androidNDKPath, TargetOS::getThisOS())));
  630. }
  631. //==============================================================================
  632. void copyActivityJavaFiles (const OwnedArray<LibraryModule>& modules, const File& targetFolder, const String& package) const
  633. {
  634. if (androidActivityClass.get().contains ("_"))
  635. throw SaveError ("Your Android activity class name or path may not contain any underscores! Try a project name without underscores.");
  636. const String className (getActivityName());
  637. if (className.isEmpty())
  638. throw SaveError ("Invalid Android Activity class name: " + androidActivityClass.get());
  639. createDirectoryOrThrow (targetFolder);
  640. if (auto* coreModule = getCoreModule (modules))
  641. {
  642. File javaDestFile (targetFolder.getChildFile (className + ".java"));
  643. File javaSourceFolder (coreModule->getFolder().getChildFile ("native")
  644. .getChildFile ("java"));
  645. String juceMidiCode, juceMidiImports, juceRuntimePermissionsCode;
  646. juceMidiImports << newLine;
  647. if (androidMinimumSDK.get().getIntValue() >= 23)
  648. {
  649. File javaAndroidMidi (javaSourceFolder.getChildFile ("AndroidMidi.java"));
  650. File javaRuntimePermissions (javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java"));
  651. juceMidiImports << "import android.media.midi.*;" << newLine
  652. << "import android.bluetooth.*;" << newLine
  653. << "import android.bluetooth.le.*;" << newLine;
  654. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  655. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  656. }
  657. else
  658. {
  659. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  660. .loadFileAsString()
  661. .replace ("JuceAppActivity", className);
  662. }
  663. auto javaSourceFile = javaSourceFolder.getChildFile ("JuceAppActivity.java");
  664. auto javaSourceLines = StringArray::fromLines (javaSourceFile.loadFileAsString());
  665. {
  666. MemoryOutputStream newFile;
  667. for (const auto& line : javaSourceLines)
  668. {
  669. if (line.contains ("$$JuceAndroidMidiImports$$"))
  670. newFile << juceMidiImports;
  671. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  672. newFile << juceMidiCode;
  673. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  674. newFile << juceRuntimePermissionsCode;
  675. else
  676. newFile << line.replace ("JuceAppActivity", className)
  677. .replace ("package com.juce;", "package " + package + ";") << newLine;
  678. }
  679. javaSourceLines = StringArray::fromLines (newFile.toString());
  680. }
  681. while (javaSourceLines.size() > 2
  682. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  683. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  684. javaSourceLines.remove (javaSourceLines.size() - 1);
  685. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  686. }
  687. }
  688. String getActivityName() const
  689. {
  690. return androidActivityClass.get().fromLastOccurrenceOf (".", false, false);
  691. }
  692. String getActivitySubClassName() const
  693. {
  694. String activityPath = androidActivitySubClassName.get();
  695. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  696. }
  697. String getActivityClassPackage() const
  698. {
  699. return androidActivityClass.get().upToLastOccurrenceOf (".", false, false);
  700. }
  701. String getJNIActivityClassName() const
  702. {
  703. return androidActivityClass.get().replaceCharacter ('.', '/');
  704. }
  705. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  706. {
  707. for (int i = modules.size(); --i >= 0;)
  708. if (modules.getUnchecked(i)->getID() == "juce_core")
  709. return modules.getUnchecked(i);
  710. return nullptr;
  711. }
  712. //==============================================================================
  713. String getNativeModuleBinaryName (const AndroidBuildConfiguration& config) const
  714. {
  715. return (isLibrary() ? File::createLegalFileName (config.getTargetBinaryNameString().trim()) : "juce_jni");
  716. }
  717. String getAppPlatform() const
  718. {
  719. int ndkVersion = androidMinimumSDK.get().getIntValue();
  720. if (ndkVersion == 9)
  721. ndkVersion = 10; // (doesn't seem to be a version '9')
  722. return "android-" + String (ndkVersion);
  723. }
  724. //==============================================================================
  725. void writeStringsXML (const File& folder) const
  726. {
  727. XmlElement strings ("resources");
  728. XmlElement* resourceName = strings.createNewChildElement ("string");
  729. resourceName->setAttribute ("name", "app_name");
  730. resourceName->addTextElement (projectName);
  731. writeXmlOrThrow (strings, folder.getChildFile ("app/src/main/res/values/string.xml"), "utf-8", 100, true);
  732. }
  733. void writeAndroidManifest (const File& folder) const
  734. {
  735. ScopedPointer<XmlElement> manifest (createManifestXML());
  736. writeXmlOrThrow (*manifest, folder.getChildFile ("src/main/AndroidManifest.xml"), "utf-8", 100, true);
  737. }
  738. void writeIcon (const File& file, const Image& im) const
  739. {
  740. if (im.isValid())
  741. {
  742. createDirectoryOrThrow (file.getParentDirectory());
  743. PNGImageFormat png;
  744. MemoryOutputStream mo;
  745. if (! png.writeImageToStream (im, mo))
  746. throw SaveError ("Can't generate Android icon file");
  747. overwriteFileIfDifferentOrThrow (file, mo);
  748. }
  749. }
  750. void writeIcons (const File& folder) const
  751. {
  752. ScopedPointer<Drawable> bigIcon (getBigIcon());
  753. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  754. if (bigIcon != nullptr && smallIcon != nullptr)
  755. {
  756. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  757. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  758. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  759. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  760. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  761. }
  762. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  763. {
  764. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  765. }
  766. }
  767. void writeAppIcons (const File& folder) const
  768. {
  769. writeIcons (folder.getChildFile ("app/src/main/res/"));
  770. }
  771. static String sanitisePath (String path)
  772. {
  773. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  774. }
  775. static String expandHomeFolderToken (const String& path)
  776. {
  777. String homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  778. return path.replace ("${user.home}", homeFolder)
  779. .replace ("~", homeFolder);
  780. }
  781. //==============================================================================
  782. void addCompileUnits (const Project::Item& projectItem, MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  783. {
  784. if (projectItem.isGroup())
  785. {
  786. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  787. addCompileUnits (projectItem.getChild(i), mo, excludeFromBuild);
  788. }
  789. else if (projectItem.shouldBeAddedToTargetProject())
  790. {
  791. const RelativePath file (projectItem.getFile(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  792. const ProjectType::Target::Type targetType = getProject().getTargetTypeFromFilePath (projectItem.getFile(), true);
  793. mo << " \"" << file.toUnixStyle() << "\"" << newLine;
  794. if ((! projectItem.shouldBeCompiled()) || (! shouldFileBeCompiledByDefault (file))
  795. || (getProject().getProjectType().isAudioPlugin()
  796. && targetType != ProjectType::Target::SharedCodeTarget
  797. && targetType != ProjectType::Target::StandalonePlugIn))
  798. excludeFromBuild.add (file);
  799. }
  800. }
  801. void addCompileUnits (MemoryOutputStream& mo, Array<RelativePath>& excludeFromBuild) const
  802. {
  803. for (int i = 0; i < getAllGroups().size(); ++i)
  804. addCompileUnits (getAllGroups().getReference(i), mo, excludeFromBuild);
  805. }
  806. //==============================================================================
  807. StringArray getCmakeDefinitions() const
  808. {
  809. const String toolchain = gradleToolchain.get();
  810. const bool isClang = (toolchain == "clang");
  811. StringArray cmakeArgs;
  812. cmakeArgs.add ("\"-DANDROID_TOOLCHAIN=" + toolchain + "\"");
  813. cmakeArgs.add ("\"-DANDROID_PLATFORM=" + getAppPlatform() + "\"");
  814. cmakeArgs.add (String ("\"-DANDROID_STL=") + (isClang ? "c++_static" : "gnustl_static") + "\"");
  815. cmakeArgs.add ("\"-DANDROID_CPP_FEATURES=exceptions rtti\"");
  816. cmakeArgs.add ("\"-DANDROID_ARM_MODE=arm\"");
  817. cmakeArgs.add ("\"-DANDROID_ARM_NEON=TRUE\"");
  818. return cmakeArgs;
  819. }
  820. //==============================================================================
  821. StringArray getAndroidCompilerFlags() const
  822. {
  823. StringArray cFlags;
  824. cFlags.add ("\"-fsigned-char\"");
  825. return cFlags;
  826. }
  827. StringArray getAndroidCxxCompilerFlags() const
  828. {
  829. StringArray cxxFlags (getAndroidCompilerFlags());
  830. String cppStandardToUse (getCppStandardString());
  831. if (cppStandardToUse.isEmpty())
  832. cppStandardToUse = "-std=c++11";
  833. cxxFlags.add ("\"" + cppStandardToUse + "\"");
  834. return cxxFlags;
  835. }
  836. StringArray getProjectCompilerFlags() const
  837. {
  838. StringArray cFlags (getAndroidCompilerFlags());
  839. cFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  840. return cFlags;
  841. }
  842. StringArray getProjectCxxCompilerFlags() const
  843. {
  844. StringArray cxxFlags (getAndroidCxxCompilerFlags());
  845. cxxFlags.addArray (getEscapedFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), true)));
  846. return cxxFlags;
  847. }
  848. //==============================================================================
  849. StringPairArray getAndroidPreprocessorDefs() const
  850. {
  851. StringPairArray defines;
  852. defines.set ("JUCE_ANDROID", "1");
  853. defines.set ("JUCE_ANDROID_API_VERSION", androidMinimumSDK.get());
  854. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  855. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\"" + getJNIActivityClassName() + "\"");
  856. if (supportsGLv3())
  857. defines.set ("JUCE_ANDROID_GL_ES_VERSION_3_0", "1");
  858. return defines;
  859. }
  860. StringPairArray getProjectPreprocessorDefs() const
  861. {
  862. StringPairArray defines (getAndroidPreprocessorDefs());
  863. return mergePreprocessorDefs (defines, getProject().getPreprocessorDefs());
  864. }
  865. StringPairArray getConfigPreprocessorDefs (const BuildConfiguration& config) const
  866. {
  867. StringPairArray cfgDefines (config.getUniquePreprocessorDefs());
  868. if (config.isDebug())
  869. {
  870. cfgDefines.set ("DEBUG", "1");
  871. cfgDefines.set ("_DEBUG", "1");
  872. }
  873. else
  874. {
  875. cfgDefines.set ("NDEBUG", "1");
  876. }
  877. return cfgDefines;
  878. }
  879. //==============================================================================
  880. StringArray getAndroidLibraries() const
  881. {
  882. StringArray libraries;
  883. libraries.add ("log");
  884. libraries.add ("android");
  885. libraries.add (supportsGLv3() ? "GLESv3" : "GLESv2");
  886. libraries.add ("EGL");
  887. return libraries;
  888. }
  889. //==============================================================================
  890. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  891. {
  892. StringArray paths (extraSearchPaths);
  893. paths.addArray (config.getHeaderSearchPaths());
  894. paths = getCleanedStringArray (paths);
  895. return paths;
  896. }
  897. //==============================================================================
  898. String escapeDirectoryForCmake (const String& path) const
  899. {
  900. RelativePath relative =
  901. RelativePath (path, RelativePath::buildTargetFolder)
  902. .rebased (getTargetFolder(), getTargetFolder().getChildFile ("app"), RelativePath::buildTargetFolder);
  903. return relative.toUnixStyle();
  904. }
  905. void writeCmakePathLines (MemoryOutputStream& mo, const String& prefix, const String& firstLine, const StringArray& paths,
  906. const String& suffix = ")") const
  907. {
  908. if (paths.size() > 0)
  909. {
  910. mo << prefix << firstLine << newLine;
  911. for (auto& path : paths)
  912. mo << prefix << " \"" << escapeDirectoryForCmake (path) << "\"" << newLine;
  913. mo << prefix << suffix << newLine << newLine;
  914. }
  915. }
  916. static StringArray getEscapedPreprocessorDefs (const StringPairArray& defs)
  917. {
  918. StringArray escapedDefs;
  919. for (int i = 0; i < defs.size(); ++i)
  920. {
  921. String escaped ("\"-D" + defs.getAllKeys()[i]);
  922. String value = defs.getAllValues()[i];
  923. if (value.isNotEmpty())
  924. {
  925. value = value.replace ("\"", "\\\"");
  926. if (value.containsChar (L' '))
  927. value = "\\\"" + value + "\\\"";
  928. escaped += ("=" + value + "\"");
  929. }
  930. escapedDefs.add (escaped);
  931. }
  932. return escapedDefs;
  933. }
  934. static StringArray getEscapedFlags (const StringArray& flags)
  935. {
  936. StringArray escaped;
  937. for (auto& flag : flags)
  938. escaped.add ("\"" + flag + "\"");
  939. return escaped;
  940. }
  941. //==============================================================================
  942. XmlElement* createManifestXML() const
  943. {
  944. XmlElement* manifest = new XmlElement ("manifest");
  945. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  946. manifest->setAttribute ("android:versionCode", androidVersionCode.get());
  947. manifest->setAttribute ("android:versionName", project.getVersionString());
  948. manifest->setAttribute ("package", getActivityClassPackage());
  949. if (! isLibrary())
  950. {
  951. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  952. screens->setAttribute ("android:smallScreens", "true");
  953. screens->setAttribute ("android:normalScreens", "true");
  954. screens->setAttribute ("android:largeScreens", "true");
  955. screens->setAttribute ("android:anyDensity", "true");
  956. }
  957. XmlElement* sdk = manifest->createNewChildElement ("uses-sdk");
  958. sdk->setAttribute ("android:minSdkVersion", androidMinimumSDK.get());
  959. sdk->setAttribute ("android:targetSdkVersion", androidMinimumSDK.get());
  960. {
  961. const StringArray permissions (getPermissionsRequired());
  962. for (int i = permissions.size(); --i >= 0;)
  963. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  964. }
  965. if (project.getModules().isModuleEnabled ("juce_opengl"))
  966. {
  967. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  968. feature->setAttribute ("android:glEsVersion", (androidMinimumSDK.get().getIntValue() >= 18 ? "0x00030000" : "0x00020000"));
  969. feature->setAttribute ("android:required", "true");
  970. }
  971. if (! isLibrary())
  972. {
  973. XmlElement* app = manifest->createNewChildElement ("application");
  974. app->setAttribute ("android:label", "@string/app_name");
  975. if (androidTheme.get().isNotEmpty())
  976. app->setAttribute ("android:theme", androidTheme.get());
  977. {
  978. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  979. if (bigIcon != nullptr || smallIcon != nullptr)
  980. app->setAttribute ("android:icon", "@drawable/icon");
  981. }
  982. if (androidMinimumSDK.get().getIntValue() >= 11)
  983. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  984. XmlElement* act = app->createNewChildElement ("activity");
  985. act->setAttribute ("android:name", getActivitySubClassName());
  986. act->setAttribute ("android:label", "@string/app_name");
  987. String configChanges ("keyboardHidden|orientation");
  988. if (androidMinimumSDK.get().getIntValue() >= 13)
  989. configChanges += "|screenSize";
  990. act->setAttribute ("android:configChanges", configChanges);
  991. act->setAttribute ("android:screenOrientation", androidScreenOrientation.get());
  992. XmlElement* intent = act->createNewChildElement ("intent-filter");
  993. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  994. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  995. }
  996. return manifest;
  997. }
  998. StringArray getPermissionsRequired() const
  999. {
  1000. StringArray s;
  1001. s.addTokens (androidOtherPermissions.get(), ", ", "");
  1002. if (androidInternetNeeded.get())
  1003. s.add ("android.permission.INTERNET");
  1004. if (androidMicNeeded.get())
  1005. s.add ("android.permission.RECORD_AUDIO");
  1006. if (androidBluetoothNeeded.get())
  1007. {
  1008. s.add ("android.permission.BLUETOOTH");
  1009. s.add ("android.permission.BLUETOOTH_ADMIN");
  1010. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  1011. }
  1012. return getCleanedStringArray (s);
  1013. }
  1014. //==============================================================================
  1015. bool isLibrary() const
  1016. {
  1017. return getProject().getProjectType().isDynamicLibrary()
  1018. || getProject().getProjectType().isStaticLibrary();
  1019. }
  1020. static String toGradleList (const StringArray& array)
  1021. {
  1022. StringArray escapedArray;
  1023. for (auto element : array)
  1024. escapedArray.add ("\"" + element.replace ("\\", "\\\\").replace ("\"", "\\\"") + "\"");
  1025. return escapedArray.joinIntoString (", ");
  1026. }
  1027. bool supportsGLv3() const
  1028. {
  1029. return (androidMinimumSDK.get().getIntValue() >= 18);
  1030. }
  1031. //==============================================================================
  1032. Value sdkPath, ndkPath;
  1033. const File AndroidExecutable;
  1034. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  1035. };
  1036. ProjectExporter* createAndroidExporter (Project& p, const ValueTree& t)
  1037. {
  1038. return new AndroidProjectExporter (p, t);
  1039. }
  1040. ProjectExporter* createAndroidExporterForSetting (Project& p, const ValueTree& t)
  1041. {
  1042. return AndroidProjectExporter::createForSettings (p, t);
  1043. }