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.

867 lines
39KB

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