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.

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