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.

802 lines
36KB

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