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.

902 lines
41KB

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