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.

770 lines
35KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class AndroidProjectExporter : public ProjectExporter
  18. {
  19. public:
  20. //==============================================================================
  21. static const char* getNameAndroid() { return "Android Project"; }
  22. static const char* getValueTreeTypeName() { return "ANDROID"; }
  23. static AndroidProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  24. {
  25. if (settings.hasType (getValueTreeTypeName()))
  26. return new AndroidProjectExporter (project, settings);
  27. return nullptr;
  28. }
  29. //==============================================================================
  30. AndroidProjectExporter (Project& p, const ValueTree& t)
  31. : ProjectExporter (p, t)
  32. {
  33. name = getNameAndroid();
  34. if (getTargetLocationString().isEmpty())
  35. getTargetLocationValue() = getDefaultBuildsRootFolder() + "Android";
  36. if (getVersionCodeString().isEmpty())
  37. getVersionCodeValue() = 1;
  38. if (getActivityClassPath().isEmpty())
  39. getActivityClassPathValue() = createDefaultClassName();
  40. if (getMinimumSDKVersionString().isEmpty())
  41. getMinimumSDKVersionValue() = 10;
  42. if (getInternetNeededValue().toString().isEmpty())
  43. getInternetNeededValue() = true;
  44. if (getKeyStoreValue().getValue().isVoid()) getKeyStoreValue() = "${user.home}/.android/debug.keystore";
  45. if (getKeyStorePassValue().getValue().isVoid()) getKeyStorePassValue() = "android";
  46. if (getKeyAliasValue().getValue().isVoid()) getKeyAliasValue() = "androiddebugkey";
  47. if (getKeyAliasPassValue().getValue().isVoid()) getKeyAliasPassValue() = "android";
  48. if (getCPP11EnabledValue().getValue().isVoid()) getCPP11EnabledValue() = true;
  49. initialiseDependencyPathValues();
  50. }
  51. //==============================================================================
  52. bool canLaunchProject() override { return false; }
  53. bool launchProject() override { return false; }
  54. bool isAndroid() const override { return true; }
  55. bool usesMMFiles() const override { return false; }
  56. bool canCopeWithDuplicateFiles() override { return false; }
  57. void createExporterProperties (PropertyListBuilder& props) override
  58. {
  59. props.add (new TextPropertyComponent (getActivityClassPathValue(), "Android Activity class name", 256, false),
  60. "The full java class name to use for the app's Activity class.");
  61. props.add (new TextPropertyComponent (getActivitySubClassPathValue(), "Android Activity sub-class name", 256, false),
  62. "If not empty, specifies the Android Activity class name stored in the app's manifest. "
  63. "Use this if you would like to use your own Android Activity sub-class.");
  64. props.add (new TextPropertyComponent (getVersionCodeValue(), "Android Version Code", 32, false),
  65. "An integer value that represents the version of the application code, relative to other versions.");
  66. props.add (new DependencyPathPropertyComponent (getSDKPathValue(), "Android SDK Path"),
  67. "The path to the Android SDK folder on the target build machine");
  68. props.add (new DependencyPathPropertyComponent (getNDKPathValue(), "Android NDK Path"),
  69. "The path to the Android NDK folder on the target build machine");
  70. props.add (new TextPropertyComponent (getMinimumSDKVersionValue(), "Minimum SDK version", 32, false),
  71. "The number of the minimum version of the Android SDK that the app requires");
  72. props.add (new TextPropertyComponent (getNDKToolchainVersionValue(), "NDK Toolchain version", 32, false),
  73. "The variable NDK_TOOLCHAIN_VERSION in Application.mk - leave blank for a default value");
  74. props.add (new BooleanPropertyComponent (getCPP11EnabledValue(), "Enable C++11 features", "Enable the -std=c++11 flag"),
  75. "If enabled, this will set the -std=c++11 flag for the build.");
  76. props.add (new BooleanPropertyComponent (getInternetNeededValue(), "Internet Access", "Specify internet access permission in the manifest"),
  77. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  78. props.add (new BooleanPropertyComponent (getAudioRecordNeededValue(), "Audio Input Required", "Specify audio record permission in the manifest"),
  79. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  80. props.add (new TextPropertyComponent (getOtherPermissionsValue(), "Custom permissions", 2048, false),
  81. "A space-separated list of other permission flags that should be added to the manifest.");
  82. props.add (new TextPropertyComponent (getStaticLibrariesValue(), "Import static library modules", 8192, true),
  83. "Comma or whitespace delimited list of static libraries (.a) defined in NDK_MODULE_PATH.");
  84. props.add (new TextPropertyComponent (getSharedLibrariesValue(), "Import shared library modules", 8192, true),
  85. "Comma or whitespace delimited list of shared libraries (.so) defined in NDK_MODULE_PATH.");
  86. props.add (new TextPropertyComponent (getThemeValue(), "Android Theme", 256, false),
  87. "E.g. @android:style/Theme.NoTitleBar or leave blank for default");
  88. props.add (new TextPropertyComponent (getKeyStoreValue(), "Key Signing: key.store", 2048, false),
  89. "The key.store value, used when signing the package.");
  90. props.add (new TextPropertyComponent (getKeyStorePassValue(), "Key Signing: key.store.password", 2048, false),
  91. "The key.store password, used when signing the package.");
  92. props.add (new TextPropertyComponent (getKeyAliasValue(), "Key Signing: key.alias", 2048, false),
  93. "The key.alias value, used when signing the package.");
  94. props.add (new TextPropertyComponent (getKeyAliasPassValue(), "Key Signing: key.alias.password", 2048, false),
  95. "The key.alias password, used when signing the package.");
  96. }
  97. Value getActivityClassPathValue() { return getSetting (Ids::androidActivityClass); }
  98. String getActivityClassPath() const { return settings [Ids::androidActivityClass]; }
  99. Value getActivitySubClassPathValue() { return getSetting (Ids::androidActivitySubClassName); }
  100. String getActivitySubClassPath() const { return settings [Ids::androidActivitySubClassName]; }
  101. Value getVersionCodeValue() { return getSetting (Ids::androidVersionCode); }
  102. String getVersionCodeString() const { return settings [Ids::androidVersionCode]; }
  103. Value getSDKPathValue() { return sdkPath; }
  104. String getSDKPathString() const { return sdkPath.toString(); }
  105. Value getNDKPathValue() { return ndkPath; }
  106. String getNDKPathString() const { return ndkPath.toString(); }
  107. Value getNDKToolchainVersionValue() { return getSetting (Ids::toolset); }
  108. String getNDKToolchainVersionString() const { return settings [Ids::toolset]; }
  109. Value getKeyStoreValue() { return getSetting (Ids::androidKeyStore); }
  110. String getKeyStoreString() const { return settings [Ids::androidKeyStore]; }
  111. Value getKeyStorePassValue() { return getSetting (Ids::androidKeyStorePass); }
  112. String getKeyStorePassString() const { return settings [Ids::androidKeyStorePass]; }
  113. Value getKeyAliasValue() { return getSetting (Ids::androidKeyAlias); }
  114. String getKeyAliasString() const { return settings [Ids::androidKeyAlias]; }
  115. Value getKeyAliasPassValue() { return getSetting (Ids::androidKeyAliasPass); }
  116. String getKeyAliasPassString() const { return settings [Ids::androidKeyAliasPass]; }
  117. Value getInternetNeededValue() { return getSetting (Ids::androidInternetNeeded); }
  118. bool getInternetNeeded() const { return settings [Ids::androidInternetNeeded]; }
  119. Value getAudioRecordNeededValue() { return getSetting (Ids::androidMicNeeded); }
  120. bool getAudioRecordNeeded() const { return settings [Ids::androidMicNeeded]; }
  121. Value getMinimumSDKVersionValue() { return getSetting (Ids::androidMinimumSDK); }
  122. String getMinimumSDKVersionString() const { return settings [Ids::androidMinimumSDK]; }
  123. Value getOtherPermissionsValue() { return getSetting (Ids::androidOtherPermissions); }
  124. String getOtherPermissions() const { return settings [Ids::androidOtherPermissions]; }
  125. Value getThemeValue() { return getSetting (Ids::androidTheme); }
  126. String getThemeString() const { return settings [Ids::androidTheme]; }
  127. Value getStaticLibrariesValue() { return getSetting (Ids::androidStaticLibraries); }
  128. String getStaticLibrariesString() const { return settings [Ids::androidStaticLibraries]; }
  129. Value getSharedLibrariesValue() { return getSetting (Ids::androidSharedLibraries); }
  130. String getSharedLibrariesString() const { return settings [Ids::androidSharedLibraries]; }
  131. Value getCPP11EnabledValue() { return getSetting (Ids::androidCpp11); }
  132. bool isCPP11Enabled() const { return settings [Ids::androidCpp11]; }
  133. String createDefaultClassName() const
  134. {
  135. String s (project.getBundleIdentifier().toString().toLowerCase());
  136. if (s.length() > 5
  137. && s.containsChar ('.')
  138. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  139. && ! s.startsWithChar ('.'))
  140. {
  141. if (! s.endsWithChar ('.'))
  142. s << ".";
  143. }
  144. else
  145. {
  146. s = "com.yourcompany.";
  147. }
  148. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRoot(), false, true, false);
  149. }
  150. //==============================================================================
  151. void create (const OwnedArray<LibraryModule>& modules) const override
  152. {
  153. const File target (getTargetFolder());
  154. const File jniFolder (target.getChildFile ("jni"));
  155. copyActivityJavaFiles (modules);
  156. createDirectoryOrThrow (jniFolder);
  157. createDirectoryOrThrow (target.getChildFile ("res").getChildFile ("values"));
  158. createDirectoryOrThrow (target.getChildFile ("libs"));
  159. createDirectoryOrThrow (target.getChildFile ("bin"));
  160. {
  161. ScopedPointer<XmlElement> manifest (createManifestXML());
  162. writeXmlOrThrow (*manifest, target.getChildFile ("AndroidManifest.xml"), "utf-8", 100, true);
  163. }
  164. writeApplicationMk (jniFolder.getChildFile ("Application.mk"));
  165. writeAndroidMk (jniFolder.getChildFile ("Android.mk"));
  166. {
  167. ScopedPointer<XmlElement> antBuildXml (createAntBuildXML());
  168. writeXmlOrThrow (*antBuildXml, target.getChildFile ("build.xml"), "UTF-8", 100);
  169. }
  170. writeProjectPropertiesFile (target.getChildFile ("project.properties"));
  171. writeLocalPropertiesFile (target.getChildFile ("local.properties"));
  172. writeStringsFile (target.getChildFile ("res/values/strings.xml"));
  173. ScopedPointer<Drawable> bigIcon (getBigIcon());
  174. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  175. if (bigIcon != nullptr && smallIcon != nullptr)
  176. {
  177. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  178. writeIcon (target.getChildFile ("res/drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  179. writeIcon (target.getChildFile ("res/drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  180. writeIcon (target.getChildFile ("res/drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  181. writeIcon (target.getChildFile ("res/drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  182. }
  183. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  184. {
  185. writeIcon (target.getChildFile ("res/drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  186. }
  187. }
  188. protected:
  189. //==============================================================================
  190. class AndroidBuildConfiguration : public BuildConfiguration
  191. {
  192. public:
  193. AndroidBuildConfiguration (Project& p, const ValueTree& settings)
  194. : BuildConfiguration (p, settings)
  195. {
  196. if (getArchitectures().isEmpty())
  197. getArchitecturesValue() = "armeabi armeabi-v7a";
  198. }
  199. Value getArchitecturesValue() { return getValue (Ids::androidArchitectures); }
  200. String getArchitectures() const { return config [Ids::androidArchitectures]; }
  201. var getDefaultOptimisationLevel() const override { return var ((int) (isDebug() ? gccO0 : gccO3)); }
  202. void createConfigProperties (PropertyListBuilder& props) override
  203. {
  204. addGCCOptimisationProperty (props);
  205. props.add (new TextPropertyComponent (getArchitecturesValue(), "Architectures", 256, false),
  206. "A list of the ARM architectures to build (for a fat binary).");
  207. }
  208. };
  209. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  210. {
  211. return new AndroidBuildConfiguration (project, v);
  212. }
  213. private:
  214. //==============================================================================
  215. XmlElement* createManifestXML() const
  216. {
  217. XmlElement* manifest = new XmlElement ("manifest");
  218. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  219. manifest->setAttribute ("android:versionCode", getVersionCodeString());
  220. manifest->setAttribute ("android:versionName", project.getVersionString());
  221. manifest->setAttribute ("package", getActivityClassPackage());
  222. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  223. screens->setAttribute ("android:smallScreens", "true");
  224. screens->setAttribute ("android:normalScreens", "true");
  225. screens->setAttribute ("android:largeScreens", "true");
  226. //screens->setAttribute ("android:xlargeScreens", "true");
  227. screens->setAttribute ("android:anyDensity", "true");
  228. XmlElement* sdk = manifest->createNewChildElement ("uses-sdk");
  229. sdk->setAttribute ("android:minSdkVersion", getMinimumSDKVersionString());
  230. sdk->setAttribute ("android:targetSdkVersion", "11");
  231. {
  232. const StringArray permissions (getPermissionsRequired());
  233. for (int i = permissions.size(); --i >= 0;)
  234. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  235. }
  236. if (project.getModules().isModuleEnabled ("juce_opengl"))
  237. {
  238. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  239. feature->setAttribute ("android:glEsVersion", "0x00020000");
  240. feature->setAttribute ("android:required", "true");
  241. }
  242. XmlElement* app = manifest->createNewChildElement ("application");
  243. app->setAttribute ("android:label", "@string/app_name");
  244. String androidThemeString (getThemeString());
  245. if (androidThemeString.isNotEmpty())
  246. app->setAttribute ("android:theme", androidThemeString);
  247. {
  248. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  249. if (bigIcon != nullptr || smallIcon != nullptr)
  250. app->setAttribute ("android:icon", "@drawable/icon");
  251. }
  252. if (getMinimumSDKVersionString().getIntValue() >= 11)
  253. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  254. XmlElement* act = app->createNewChildElement ("activity");
  255. act->setAttribute ("android:name", getActivitySubClassName());
  256. act->setAttribute ("android:label", "@string/app_name");
  257. act->setAttribute ("android:configChanges", "keyboardHidden|orientation");
  258. XmlElement* intent = act->createNewChildElement ("intent-filter");
  259. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  260. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  261. return manifest;
  262. }
  263. StringArray getPermissionsRequired() const
  264. {
  265. StringArray s;
  266. s.addTokens (getOtherPermissions(), ", ", "");
  267. if (getInternetNeeded()) s.add ("android.permission.INTERNET");
  268. if (getAudioRecordNeeded()) s.add ("android.permission.RECORD_AUDIO");
  269. return getCleanedStringArray (s);
  270. }
  271. //==============================================================================
  272. void findAllFilesToCompile (const Project::Item& projectItem, Array<RelativePath>& results) const
  273. {
  274. if (projectItem.isGroup())
  275. {
  276. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  277. findAllFilesToCompile (projectItem.getChild(i), results);
  278. }
  279. else
  280. {
  281. if (projectItem.shouldBeCompiled())
  282. results.add (RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder));
  283. }
  284. }
  285. //==============================================================================
  286. String getActivityName() const
  287. {
  288. return getActivityClassPath().fromLastOccurrenceOf (".", false, false);
  289. }
  290. String getActivitySubClassName() const
  291. {
  292. String activityPath = getActivitySubClassPath();
  293. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  294. }
  295. String getActivityClassPackage() const
  296. {
  297. return getActivityClassPath().upToLastOccurrenceOf (".", false, false);
  298. }
  299. String getJNIActivityClassName() const
  300. {
  301. return getActivityClassPath().replaceCharacter ('.', '/');
  302. }
  303. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  304. {
  305. for (int i = modules.size(); --i >= 0;)
  306. if (modules.getUnchecked(i)->getID() == "juce_core")
  307. return modules.getUnchecked(i);
  308. return nullptr;
  309. }
  310. void copyActivityJavaFiles (const OwnedArray<LibraryModule>& modules) const
  311. {
  312. const String className (getActivityName());
  313. const String package (getActivityClassPackage());
  314. String path (package.replaceCharacter ('.', File::separator));
  315. if (path.isEmpty() || className.isEmpty())
  316. throw SaveError ("Invalid Android Activity class name: " + getActivityClassPath());
  317. const File classFolder (getTargetFolder().getChildFile ("src")
  318. .getChildFile (path));
  319. createDirectoryOrThrow (classFolder);
  320. LibraryModule* const coreModule = getCoreModule (modules);
  321. if (coreModule != nullptr)
  322. {
  323. File javaDestFile (classFolder.getChildFile (className + ".java"));
  324. File javaSourceFile (coreModule->getFolder().getChildFile ("native")
  325. .getChildFile ("java")
  326. .getChildFile ("JuceAppActivity.java"));
  327. MemoryOutputStream newFile;
  328. newFile << javaSourceFile.loadFileAsString()
  329. .replace ("JuceAppActivity", className)
  330. .replace ("package com.juce;", "package " + package + ";");
  331. overwriteFileIfDifferentOrThrow (javaDestFile, newFile);
  332. }
  333. }
  334. String getABIs (bool forDebug) const
  335. {
  336. for (ConstConfigIterator config (*this); config.next();)
  337. {
  338. const AndroidBuildConfiguration& androidConfig = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  339. if (config->isDebug() == forDebug)
  340. return androidConfig.getArchitectures();
  341. }
  342. return String();
  343. }
  344. String getCppFlags() const
  345. {
  346. String flags ("-fsigned-char -fexceptions -frtti");
  347. if (! getNDKToolchainVersionString().startsWithIgnoreCase ("clang"))
  348. flags << " -Wno-psabi";
  349. return flags;
  350. }
  351. String getToolchainVersion() const
  352. {
  353. String v (getNDKToolchainVersionString());
  354. return v.isNotEmpty() ? v : "4.8";
  355. }
  356. void writeApplicationMk (const File& file) const
  357. {
  358. MemoryOutputStream mo;
  359. mo << "# Automatically generated makefile, created by the Introjucer" << newLine
  360. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  361. << newLine
  362. << "APP_STL := gnustl_static" << newLine
  363. << "APP_CPPFLAGS += " << getCppFlags() << newLine
  364. << "APP_PLATFORM := " << getAppPlatform() << newLine
  365. << "NDK_TOOLCHAIN_VERSION := " << getToolchainVersion() << newLine
  366. << newLine
  367. << "ifeq ($(NDK_DEBUG),1)" << newLine
  368. << " APP_ABI := " << getABIs (true) << newLine
  369. << "else" << newLine
  370. << " APP_ABI := " << getABIs (false) << newLine
  371. << "endif" << newLine;
  372. overwriteFileIfDifferentOrThrow (file, mo);
  373. }
  374. void writeAndroidMk (const File& file) const
  375. {
  376. Array<RelativePath> files;
  377. for (int i = 0; i < getAllGroups().size(); ++i)
  378. findAllFilesToCompile (getAllGroups().getReference(i), files);
  379. MemoryOutputStream mo;
  380. writeAndroidMk (mo, files);
  381. overwriteFileIfDifferentOrThrow (file, mo);
  382. }
  383. void writeAndroidMkVariableList (OutputStream& out, const String& variableName, const String& settingsValue) const
  384. {
  385. const StringArray separatedItems (getCommaOrWhitespaceSeparatedItems (settingsValue));
  386. if (separatedItems.size() > 0)
  387. out << newLine << variableName << " := " << separatedItems.joinIntoString (" ") << newLine;
  388. }
  389. void writeAndroidMk (OutputStream& out, const Array<RelativePath>& files) const
  390. {
  391. out << "# Automatically generated makefile, created by the Introjucer" << newLine
  392. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  393. << newLine
  394. << "LOCAL_PATH := $(call my-dir)" << newLine
  395. << newLine
  396. << "include $(CLEAR_VARS)" << newLine
  397. << newLine
  398. << "ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)" << newLine
  399. << " LOCAL_ARM_MODE := arm" << newLine
  400. << "endif" << newLine
  401. << newLine
  402. << "LOCAL_MODULE := juce_jni" << newLine
  403. << "LOCAL_SRC_FILES := \\" << newLine;
  404. for (int i = 0; i < files.size(); ++i)
  405. out << " " << (files.getReference(i).isAbsolute() ? "" : "../")
  406. << escapeSpaces (files.getReference(i).toUnixStyle()) << "\\" << newLine;
  407. writeAndroidMkVariableList (out, "LOCAL_STATIC_LIBRARIES", getStaticLibrariesString());
  408. writeAndroidMkVariableList (out, "LOCAL_SHARED_LIBRARIES", getSharedLibrariesString());
  409. out << newLine
  410. << "ifeq ($(NDK_DEBUG),1)" << newLine;
  411. writeConfigSettings (out, true);
  412. out << "else" << newLine;
  413. writeConfigSettings (out, false);
  414. out << "endif" << newLine
  415. << newLine
  416. << "include $(BUILD_SHARED_LIBRARY)" << newLine;
  417. StringArray importModules (getCommaOrWhitespaceSeparatedItems (getStaticLibrariesString()));
  418. importModules.addArray (getCommaOrWhitespaceSeparatedItems (getSharedLibrariesString()));
  419. for (int i = 0; i < importModules.size(); ++i)
  420. out << "$(call import-module," << importModules[i] << ")" << newLine;
  421. }
  422. void writeConfigSettings (OutputStream& out, bool forDebug) const
  423. {
  424. for (ConstConfigIterator config (*this); config.next();)
  425. {
  426. if (config->isDebug() == forDebug)
  427. {
  428. const AndroidBuildConfiguration& androidConfig = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  429. String cppFlags;
  430. cppFlags << createCPPFlags (androidConfig)
  431. << (" " + replacePreprocessorTokens (androidConfig, getExtraCompilerFlagsString()).trim()).trimEnd()
  432. << newLine
  433. << getLDLIBS (androidConfig).trimEnd()
  434. << newLine;
  435. out << " LOCAL_CPPFLAGS += " << cppFlags;
  436. out << " LOCAL_CFLAGS += " << cppFlags;
  437. break;
  438. }
  439. }
  440. }
  441. String getLDLIBS (const AndroidBuildConfiguration& config) const
  442. {
  443. return " LOCAL_LDLIBS :=" + config.getGCCLibraryPathFlags()
  444. + " -llog -lGLESv2 " + getExternalLibraryFlags (config)
  445. + " " + replacePreprocessorTokens (config, getExtraLinkerFlagsString());
  446. }
  447. String createIncludePathFlags (const BuildConfiguration& config) const
  448. {
  449. String flags;
  450. StringArray searchPaths (extraSearchPaths);
  451. searchPaths.addArray (config.getHeaderSearchPaths());
  452. searchPaths = getCleanedStringArray (searchPaths);
  453. for (int i = 0; i < searchPaths.size(); ++i)
  454. flags << " -I " << FileHelpers::unixStylePath (replacePreprocessorTokens (config, searchPaths[i])).quoted();
  455. return flags;
  456. }
  457. String createCPPFlags (const BuildConfiguration& config) const
  458. {
  459. StringPairArray defines;
  460. defines.set ("JUCE_ANDROID", "1");
  461. defines.set ("JUCE_ANDROID_API_VERSION", getMinimumSDKVersionString());
  462. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  463. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\\\"" + getJNIActivityClassName() + "\\\"");
  464. String flags ("-fsigned-char -fexceptions -frtti");
  465. if (config.isDebug())
  466. {
  467. flags << " -g";
  468. defines.set ("DEBUG", "1");
  469. defines.set ("_DEBUG", "1");
  470. }
  471. else
  472. {
  473. defines.set ("NDEBUG", "1");
  474. }
  475. flags << createIncludePathFlags (config)
  476. << " -O" << config.getGCCOptimisationFlag();
  477. if (isCPP11Enabled())
  478. flags << " -std=c++11 -std=gnu++11"; // these flags seem to enable slightly different things on gcc, and both seem to be needed
  479. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  480. return flags + createGCCPreprocessorFlags (defines);
  481. }
  482. //==============================================================================
  483. XmlElement* createAntBuildXML() const
  484. {
  485. XmlElement* proj = new XmlElement ("project");
  486. proj->setAttribute ("name", projectName);
  487. proj->setAttribute ("default", "debug");
  488. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "local.properties");
  489. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "project.properties");
  490. {
  491. XmlElement* target = proj->createNewChildElement ("target");
  492. target->setAttribute ("name", "clean");
  493. target->setAttribute ("depends", "android_rules.clean");
  494. target->createNewChildElement ("delete")->setAttribute ("dir", "libs");
  495. target->createNewChildElement ("delete")->setAttribute ("dir", "obj");
  496. XmlElement* executable = target->createNewChildElement ("exec");
  497. executable->setAttribute ("executable", "${ndk.dir}/ndk-build");
  498. executable->setAttribute ("dir", "${basedir}");
  499. executable->setAttribute ("failonerror", "true");
  500. executable->createNewChildElement ("arg")->setAttribute ("value", "clean");
  501. }
  502. {
  503. XmlElement* target = proj->createNewChildElement ("target");
  504. target->setAttribute ("name", "-pre-build");
  505. addDebugConditionClause (target, "makefileConfig", "Debug", "Release");
  506. addDebugConditionClause (target, "ndkDebugValue", "NDK_DEBUG=1", "NDK_DEBUG=0");
  507. String debugABIs, releaseABIs;
  508. for (ConstConfigIterator config (*this); config.next();)
  509. {
  510. const AndroidBuildConfiguration& androidConfig = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  511. if (config->isDebug())
  512. debugABIs = androidConfig.getArchitectures();
  513. else
  514. releaseABIs = androidConfig.getArchitectures();
  515. }
  516. addDebugConditionClause (target, "app_abis", debugABIs, releaseABIs);
  517. XmlElement* executable = target->createNewChildElement ("exec");
  518. executable->setAttribute ("executable", "${ndk.dir}/ndk-build");
  519. executable->setAttribute ("dir", "${basedir}");
  520. executable->setAttribute ("failonerror", "true");
  521. executable->createNewChildElement ("arg")->setAttribute ("value", "--jobs=4");
  522. executable->createNewChildElement ("arg")->setAttribute ("value", "CONFIG=${makefileConfig}");
  523. executable->createNewChildElement ("arg")->setAttribute ("value", "${ndkDebugValue}");
  524. executable->createNewChildElement ("arg")->setAttribute ("value", "APP_ABI=${app_abis}");
  525. target->createNewChildElement ("delete")->setAttribute ("file", "${out.final.file}");
  526. target->createNewChildElement ("delete")->setAttribute ("file", "${out.packaged.file}");
  527. }
  528. proj->createNewChildElement ("import")->setAttribute ("file", "${sdk.dir}/tools/ant/build.xml");
  529. return proj;
  530. }
  531. void addDebugConditionClause (XmlElement* target, const String& property,
  532. const String& debugValue, const String& releaseValue) const
  533. {
  534. XmlElement* condition = target->createNewChildElement ("condition");
  535. condition->setAttribute ("property", property);
  536. condition->setAttribute ("value", debugValue);
  537. condition->setAttribute ("else", releaseValue);
  538. XmlElement* equals = condition->createNewChildElement ("equals");
  539. equals->setAttribute ("arg1", "${ant.project.invoked-targets}");
  540. equals->setAttribute ("arg2", "debug");
  541. }
  542. String getAppPlatform() const
  543. {
  544. int ndkVersion = getMinimumSDKVersionString().getIntValue();
  545. if (ndkVersion == 9)
  546. ndkVersion = 10; // (doesn't seem to be a version '9')
  547. return "android-" + String (ndkVersion);
  548. }
  549. void writeProjectPropertiesFile (const File& file) const
  550. {
  551. MemoryOutputStream mo;
  552. mo << "# This file is used to override default values used by the Ant build system." << newLine
  553. << "# It is automatically generated - DO NOT EDIT IT or your changes will be lost!." << newLine
  554. << newLine
  555. << "target=" << getAppPlatform() << newLine
  556. << newLine;
  557. overwriteFileIfDifferentOrThrow (file, mo);
  558. }
  559. void writeLocalPropertiesFile (const File& file) const
  560. {
  561. MemoryOutputStream mo;
  562. mo << "# This file is used to override default values used by the Ant build system." << newLine
  563. << "# It is automatically generated by the Introjucer - DO NOT EDIT IT or your changes will be lost!." << newLine
  564. << newLine
  565. << "sdk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getSDKPathString())) << newLine
  566. << "ndk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getNDKPathString())) << newLine
  567. << "key.store=" << getKeyStoreString() << newLine
  568. << "key.alias=" << getKeyAliasString() << newLine
  569. << "key.store.password=" << getKeyStorePassString() << newLine
  570. << "key.alias.password=" << getKeyAliasPassString() << newLine
  571. << newLine;
  572. overwriteFileIfDifferentOrThrow (file, mo);
  573. }
  574. void writeIcon (const File& file, const Image& im) const
  575. {
  576. if (im.isValid())
  577. {
  578. createDirectoryOrThrow (file.getParentDirectory());
  579. PNGImageFormat png;
  580. MemoryOutputStream mo;
  581. if (! png.writeImageToStream (im, mo))
  582. throw SaveError ("Can't generate Android icon file");
  583. overwriteFileIfDifferentOrThrow (file, mo);
  584. }
  585. }
  586. void writeStringsFile (const File& file) const
  587. {
  588. XmlElement strings ("resources");
  589. XmlElement* resourceName = strings.createNewChildElement ("string");
  590. resourceName->setAttribute ("name", "app_name");
  591. resourceName->addTextElement (projectName);
  592. writeXmlOrThrow (strings, file, "utf-8", 100);
  593. }
  594. void initialiseDependencyPathValues()
  595. {
  596. sdkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidSDKPath),
  597. Ids::androidSDKPath,
  598. TargetOS::getThisOS())));
  599. ndkPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::androidNDKPath),
  600. Ids::androidNDKPath,
  601. TargetOS::getThisOS())));
  602. }
  603. //==============================================================================
  604. Value sdkPath, ndkPath;
  605. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter)
  606. };