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.

907 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, juceRuntimePermissionsCode;
  197. juceMidiImports << newLine;
  198. if (getMinimumSDKVersionString().getIntValue() >= 23)
  199. {
  200. File javaAndroidMidi (javaSourceFolder.getChildFile ("AndroidMidi.java"));
  201. File javaRuntimePermissions (javaSourceFolder.getChildFile ("AndroidRuntimePermissions.java"));
  202. juceMidiImports << "import android.media.midi.*;" << newLine
  203. << "import android.bluetooth.*;" << newLine
  204. << "import android.bluetooth.le.*;" << newLine;
  205. juceMidiCode = javaAndroidMidi.loadFileAsString().replace ("JuceAppActivity", className);
  206. juceRuntimePermissionsCode = javaRuntimePermissions.loadFileAsString().replace ("JuceAppActivity", className);
  207. }
  208. else
  209. {
  210. juceMidiCode = javaSourceFolder.getChildFile ("AndroidMidiFallback.java")
  211. .loadFileAsString()
  212. .replace ("JuceAppActivity", className);
  213. }
  214. File javaSourceFile (javaSourceFolder.getChildFile ("JuceAppActivity.java"));
  215. StringArray javaSourceLines (StringArray::fromLines (javaSourceFile.loadFileAsString()));
  216. {
  217. MemoryOutputStream newFile;
  218. for (int i = 0; i < javaSourceLines.size(); ++i)
  219. {
  220. const String& line = javaSourceLines[i];
  221. if (line.contains ("$$JuceAndroidMidiImports$$"))
  222. newFile << juceMidiImports;
  223. else if (line.contains ("$$JuceAndroidMidiCode$$"))
  224. newFile << juceMidiCode;
  225. else if (line.contains ("$$JuceAndroidRuntimePermissionsCode$$"))
  226. newFile << juceRuntimePermissionsCode;
  227. else
  228. newFile << line.replace ("JuceAppActivity", className)
  229. .replace ("package com.juce;", "package " + package + ";") << newLine;
  230. }
  231. javaSourceLines = StringArray::fromLines (newFile.toString());
  232. }
  233. while (javaSourceLines.size() > 2
  234. && javaSourceLines[javaSourceLines.size() - 1].trim().isEmpty()
  235. && javaSourceLines[javaSourceLines.size() - 2].trim().isEmpty())
  236. javaSourceLines.remove (javaSourceLines.size() - 1);
  237. overwriteFileIfDifferentOrThrow (javaDestFile, javaSourceLines.joinIntoString (newLine));
  238. }
  239. }
  240. String getAppPlatform() const
  241. {
  242. int ndkVersion = getMinimumSDKVersionString().getIntValue();
  243. if (ndkVersion == 9)
  244. ndkVersion = 10; // (doesn't seem to be a version '9')
  245. return "android-" + String (ndkVersion);
  246. }
  247. String getActivityName() const
  248. {
  249. return getActivityClassPath().fromLastOccurrenceOf (".", false, false);
  250. }
  251. String getActivitySubClassName() const
  252. {
  253. String activityPath = getActivitySubClassPath();
  254. return (activityPath.isEmpty()) ? getActivityName() : activityPath.fromLastOccurrenceOf (".", false, false);
  255. }
  256. String getActivityClassPackage() const
  257. {
  258. return getActivityClassPath().upToLastOccurrenceOf (".", false, false);
  259. }
  260. String getJNIActivityClassName() const
  261. {
  262. return getActivityClassPath().replaceCharacter ('.', '/');
  263. }
  264. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  265. {
  266. for (int i = modules.size(); --i >= 0;)
  267. if (modules.getUnchecked(i)->getID() == "juce_core")
  268. return modules.getUnchecked(i);
  269. return nullptr;
  270. }
  271. String getCppFlags() const
  272. {
  273. String flags ("-fsigned-char -fexceptions -frtti");
  274. if (! getNDKToolchainVersionString().startsWithIgnoreCase ("clang"))
  275. flags << " -Wno-psabi";
  276. return flags;
  277. }
  278. StringArray getPermissionsRequired() const
  279. {
  280. StringArray s;
  281. s.addTokens (getOtherPermissions(), ", ", "");
  282. if (getInternetNeeded())
  283. s.add ("android.permission.INTERNET");
  284. if (getAudioRecordNeeded())
  285. s.add ("android.permission.RECORD_AUDIO");
  286. if (getBluetoothPermissions())
  287. {
  288. s.add ("android.permission.BLUETOOTH");
  289. s.add ("android.permission.BLUETOOTH_ADMIN");
  290. s.add ("android.permission.ACCESS_COARSE_LOCATION");
  291. }
  292. return getCleanedStringArray (s);
  293. }
  294. template <typename PredicateT>
  295. void findAllProjectItemsWithPredicate (const Project::Item& projectItem, Array<RelativePath>& results, const PredicateT& predicate) const
  296. {
  297. if (projectItem.isGroup())
  298. {
  299. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  300. findAllProjectItemsWithPredicate (projectItem.getChild(i), results, predicate);
  301. }
  302. else
  303. {
  304. if (predicate (projectItem))
  305. results.add (RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder));
  306. }
  307. }
  308. void writeIcon (const File& file, const Image& im) const
  309. {
  310. if (im.isValid())
  311. {
  312. createDirectoryOrThrow (file.getParentDirectory());
  313. PNGImageFormat png;
  314. MemoryOutputStream mo;
  315. if (! png.writeImageToStream (im, mo))
  316. throw SaveError ("Can't generate Android icon file");
  317. overwriteFileIfDifferentOrThrow (file, mo);
  318. }
  319. }
  320. void writeIcons (const File& folder) const
  321. {
  322. ScopedPointer<Drawable> bigIcon (getBigIcon());
  323. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  324. if (bigIcon != nullptr && smallIcon != nullptr)
  325. {
  326. const int step = jmax (bigIcon->getWidth(), bigIcon->getHeight()) / 8;
  327. writeIcon (folder.getChildFile ("drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  328. writeIcon (folder.getChildFile ("drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  329. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  330. writeIcon (folder.getChildFile ("drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  331. }
  332. else if (Drawable* icon = bigIcon != nullptr ? bigIcon : smallIcon)
  333. {
  334. writeIcon (folder.getChildFile ("drawable-mdpi/icon.png"), rescaleImageForIcon (*icon, icon->getWidth()));
  335. }
  336. }
  337. template <typename BuildConfigType>
  338. String getABIs (bool forDebug) const
  339. {
  340. for (ConstConfigIterator config (*this); config.next();)
  341. {
  342. const BuildConfigType& androidConfig = dynamic_cast<const BuildConfigType&> (*config);
  343. if (config->isDebug() == forDebug)
  344. return androidConfig.getArchitectures();
  345. }
  346. return String();
  347. }
  348. //==============================================================================
  349. XmlElement* createManifestXML() const
  350. {
  351. XmlElement* manifest = new XmlElement ("manifest");
  352. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  353. manifest->setAttribute ("android:versionCode", getVersionCodeString());
  354. manifest->setAttribute ("android:versionName", project.getVersionString());
  355. manifest->setAttribute ("package", getActivityClassPackage());
  356. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  357. screens->setAttribute ("android:smallScreens", "true");
  358. screens->setAttribute ("android:normalScreens", "true");
  359. screens->setAttribute ("android:largeScreens", "true");
  360. //screens->setAttribute ("android:xlargeScreens", "true");
  361. screens->setAttribute ("android:anyDensity", "true");
  362. XmlElement* sdk = manifest->createNewChildElement ("uses-sdk");
  363. sdk->setAttribute ("android:minSdkVersion", getMinimumSDKVersionString());
  364. sdk->setAttribute ("android:targetSdkVersion", "11");
  365. {
  366. const StringArray permissions (getPermissionsRequired());
  367. for (int i = permissions.size(); --i >= 0;)
  368. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  369. }
  370. if (project.getModules().isModuleEnabled ("juce_opengl"))
  371. {
  372. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  373. feature->setAttribute ("android:glEsVersion", "0x00020000");
  374. feature->setAttribute ("android:required", "true");
  375. }
  376. XmlElement* app = manifest->createNewChildElement ("application");
  377. app->setAttribute ("android:label", "@string/app_name");
  378. String androidThemeString (getThemeString());
  379. if (androidThemeString.isNotEmpty())
  380. app->setAttribute ("android:theme", androidThemeString);
  381. {
  382. ScopedPointer<Drawable> bigIcon (getBigIcon()), smallIcon (getSmallIcon());
  383. if (bigIcon != nullptr || smallIcon != nullptr)
  384. app->setAttribute ("android:icon", "@drawable/icon");
  385. }
  386. if (getMinimumSDKVersionString().getIntValue() >= 11)
  387. app->setAttribute ("android:hardwareAccelerated", "false"); // (using the 2D acceleration slows down openGL)
  388. XmlElement* act = app->createNewChildElement ("activity");
  389. act->setAttribute ("android:name", getActivitySubClassName());
  390. act->setAttribute ("android:label", "@string/app_name");
  391. act->setAttribute ("android:configChanges", "keyboardHidden|orientation|screenSize");
  392. act->setAttribute ("android:screenOrientation", getScreenOrientationString());
  393. XmlElement* intent = act->createNewChildElement ("intent-filter");
  394. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  395. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  396. return manifest;
  397. }
  398. //==============================================================================
  399. Value sdkPath, ndkPath;
  400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidProjectExporterBase)
  401. };
  402. //==============================================================================
  403. //==============================================================================
  404. class AndroidAntProjectExporter : public AndroidProjectExporterBase
  405. {
  406. public:
  407. //==============================================================================
  408. static const char* getName() { return "Android Ant Project"; }
  409. static const char* getValueTreeTypeName() { return "ANDROID"; }
  410. static AndroidAntProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  411. {
  412. if (settings.hasType (getValueTreeTypeName()))
  413. return new AndroidAntProjectExporter (project, settings);
  414. return nullptr;
  415. }
  416. //==============================================================================
  417. AndroidAntProjectExporter (Project& p, const ValueTree& t)
  418. : AndroidProjectExporterBase (p, t)
  419. {
  420. name = getName();
  421. if (getTargetLocationString().isEmpty())
  422. getTargetLocationValue() = getDefaultBuildsRootFolder() + "Android";
  423. }
  424. //==============================================================================
  425. void createExporterProperties (PropertyListBuilder& props) override
  426. {
  427. AndroidProjectExporterBase::createExporterProperties (props);
  428. }
  429. void create (const OwnedArray<LibraryModule>& modules) const override
  430. {
  431. AndroidProjectExporterBase::create (modules);
  432. const File target (getTargetFolder());
  433. const File jniFolder (target.getChildFile ("jni"));
  434. createDirectoryOrThrow (jniFolder);
  435. createDirectoryOrThrow (target.getChildFile ("res").getChildFile ("values"));
  436. createDirectoryOrThrow (target.getChildFile ("libs"));
  437. createDirectoryOrThrow (target.getChildFile ("bin"));
  438. {
  439. ScopedPointer<XmlElement> manifest (createManifestXML());
  440. writeXmlOrThrow (*manifest, target.getChildFile ("AndroidManifest.xml"), "utf-8", 100, true);
  441. }
  442. writeApplicationMk (jniFolder.getChildFile ("Application.mk"));
  443. writeAndroidMk (jniFolder.getChildFile ("Android.mk"));
  444. {
  445. ScopedPointer<XmlElement> antBuildXml (createAntBuildXML());
  446. writeXmlOrThrow (*antBuildXml, target.getChildFile ("build.xml"), "UTF-8", 100);
  447. }
  448. writeProjectPropertiesFile (target.getChildFile ("project.properties"));
  449. writeLocalPropertiesFile (target.getChildFile ("local.properties"));
  450. writeStringsFile (target.getChildFile ("res/values/strings.xml"));
  451. writeIcons (target.getChildFile ("res"));
  452. }
  453. //==============================================================================
  454. class AndroidBuildConfiguration : public BuildConfiguration
  455. {
  456. public:
  457. AndroidBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
  458. : BuildConfiguration (p, settings, e)
  459. {
  460. if (getArchitectures().isEmpty())
  461. {
  462. if (isDebug())
  463. getArchitecturesValue() = "armeabi x86";
  464. else
  465. getArchitecturesValue() = "armeabi armeabi-v7a x86";
  466. }
  467. }
  468. Value getArchitecturesValue() { return getValue (Ids::androidArchitectures); }
  469. String getArchitectures() const { return config [Ids::androidArchitectures]; }
  470. var getDefaultOptimisationLevel() const override { return var ((int) (isDebug() ? gccO0 : gccO3)); }
  471. void createConfigProperties (PropertyListBuilder& props) override
  472. {
  473. addGCCOptimisationProperty (props);
  474. props.add (new TextPropertyComponent (getArchitecturesValue(), "Architectures", 256, false),
  475. "A list of the ARM architectures to build (for a fat binary).");
  476. }
  477. };
  478. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  479. {
  480. return new AndroidBuildConfiguration (project, v, *this);
  481. }
  482. private:
  483. //==============================================================================
  484. String getToolchainVersion() const
  485. {
  486. String v (getNDKToolchainVersionString());
  487. return v.isNotEmpty() ? v : "4.8";
  488. }
  489. void writeApplicationMk (const File& file) const
  490. {
  491. MemoryOutputStream mo;
  492. mo << "# Automatically generated makefile, created by the Introjucer" << newLine
  493. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  494. << newLine
  495. << "APP_STL := gnustl_static" << newLine
  496. << "APP_CPPFLAGS += " << getCppFlags() << newLine
  497. << "APP_PLATFORM := " << getAppPlatform() << newLine
  498. << "NDK_TOOLCHAIN_VERSION := " << getToolchainVersion() << newLine
  499. << newLine
  500. << "ifeq ($(NDK_DEBUG),1)" << newLine
  501. << " APP_ABI := " << getABIs<AndroidBuildConfiguration> (true) << newLine
  502. << "else" << newLine
  503. << " APP_ABI := " << getABIs<AndroidBuildConfiguration> (false) << newLine
  504. << "endif" << newLine;
  505. overwriteFileIfDifferentOrThrow (file, mo);
  506. }
  507. struct ShouldFileBeCompiledPredicate
  508. {
  509. bool operator() (const Project::Item& projectItem) const { return projectItem.shouldBeCompiled(); }
  510. };
  511. void writeAndroidMk (const File& file) const
  512. {
  513. Array<RelativePath> files;
  514. for (int i = 0; i < getAllGroups().size(); ++i)
  515. findAllProjectItemsWithPredicate (getAllGroups().getReference(i), files, ShouldFileBeCompiledPredicate());
  516. MemoryOutputStream mo;
  517. writeAndroidMk (mo, files);
  518. overwriteFileIfDifferentOrThrow (file, mo);
  519. }
  520. void writeAndroidMkVariableList (OutputStream& out, const String& variableName, const String& settingsValue) const
  521. {
  522. const StringArray separatedItems (getCommaOrWhitespaceSeparatedItems (settingsValue));
  523. if (separatedItems.size() > 0)
  524. out << newLine << variableName << " := " << separatedItems.joinIntoString (" ") << newLine;
  525. }
  526. void writeAndroidMk (OutputStream& out, const Array<RelativePath>& files) const
  527. {
  528. out << "# Automatically generated makefile, created by the Introjucer" << newLine
  529. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  530. << newLine
  531. << "LOCAL_PATH := $(call my-dir)" << newLine
  532. << newLine
  533. << "include $(CLEAR_VARS)" << newLine
  534. << newLine
  535. << "ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)" << newLine
  536. << " LOCAL_ARM_MODE := arm" << newLine
  537. << "endif" << newLine
  538. << newLine
  539. << "LOCAL_MODULE := juce_jni" << newLine
  540. << "LOCAL_SRC_FILES := \\" << newLine;
  541. for (int i = 0; i < files.size(); ++i)
  542. out << " " << (files.getReference(i).isAbsolute() ? "" : "../")
  543. << escapeSpaces (files.getReference(i).toUnixStyle()) << "\\" << newLine;
  544. writeAndroidMkVariableList (out, "LOCAL_STATIC_LIBRARIES", getStaticLibrariesString());
  545. writeAndroidMkVariableList (out, "LOCAL_SHARED_LIBRARIES", getSharedLibrariesString());
  546. out << newLine
  547. << "ifeq ($(NDK_DEBUG),1)" << newLine;
  548. writeConfigSettings (out, true);
  549. out << "else" << newLine;
  550. writeConfigSettings (out, false);
  551. out << "endif" << newLine
  552. << newLine
  553. << "include $(BUILD_SHARED_LIBRARY)" << newLine;
  554. StringArray importModules (getCommaOrWhitespaceSeparatedItems (getStaticLibrariesString()));
  555. importModules.addArray (getCommaOrWhitespaceSeparatedItems (getSharedLibrariesString()));
  556. for (int i = 0; i < importModules.size(); ++i)
  557. out << "$(call import-module," << importModules[i] << ")" << newLine;
  558. }
  559. void writeConfigSettings (OutputStream& out, bool forDebug) const
  560. {
  561. for (ConstConfigIterator config (*this); config.next();)
  562. {
  563. if (config->isDebug() == forDebug)
  564. {
  565. const AndroidBuildConfiguration& androidConfig = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  566. String cppFlags;
  567. cppFlags << createCPPFlags (androidConfig)
  568. << (" " + replacePreprocessorTokens (androidConfig, getExtraCompilerFlagsString()).trim()).trimEnd()
  569. << newLine
  570. << getLDLIBS (androidConfig).trimEnd()
  571. << newLine;
  572. out << " LOCAL_CPPFLAGS += " << cppFlags;
  573. out << " LOCAL_CFLAGS += " << cppFlags;
  574. break;
  575. }
  576. }
  577. }
  578. String getLDLIBS (const AndroidBuildConfiguration& config) const
  579. {
  580. return " LOCAL_LDLIBS :=" + config.getGCCLibraryPathFlags()
  581. + " -llog -lGLESv2 -landroid -lEGL" + getExternalLibraryFlags (config)
  582. + " " + replacePreprocessorTokens (config, getExtraLinkerFlagsString());
  583. }
  584. String createIncludePathFlags (const BuildConfiguration& config) const
  585. {
  586. String flags;
  587. StringArray searchPaths (extraSearchPaths);
  588. searchPaths.addArray (config.getHeaderSearchPaths());
  589. searchPaths = getCleanedStringArray (searchPaths);
  590. for (int i = 0; i < searchPaths.size(); ++i)
  591. flags << " -I " << FileHelpers::unixStylePath (replacePreprocessorTokens (config, searchPaths[i])).quoted();
  592. return flags;
  593. }
  594. String createCPPFlags (const BuildConfiguration& config) const
  595. {
  596. StringPairArray defines;
  597. defines.set ("JUCE_ANDROID", "1");
  598. defines.set ("JUCE_ANDROID_API_VERSION", getMinimumSDKVersionString());
  599. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  600. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\\\"" + getJNIActivityClassName() + "\\\"");
  601. String flags ("-fsigned-char -fexceptions -frtti");
  602. if (config.isDebug())
  603. {
  604. flags << " -g";
  605. defines.set ("DEBUG", "1");
  606. defines.set ("_DEBUG", "1");
  607. }
  608. else
  609. {
  610. defines.set ("NDEBUG", "1");
  611. }
  612. flags << createIncludePathFlags (config)
  613. << " -O" << config.getGCCOptimisationFlag();
  614. if (isCPP11Enabled())
  615. flags << " -std=c++11 -std=gnu++11"; // these flags seem to enable slightly different things on gcc, and both seem to be needed
  616. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  617. return flags + createGCCPreprocessorFlags (defines);
  618. }
  619. //==============================================================================
  620. XmlElement* createAntBuildXML() const
  621. {
  622. XmlElement* proj = new XmlElement ("project");
  623. proj->setAttribute ("name", projectName);
  624. proj->setAttribute ("default", "debug");
  625. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "local.properties");
  626. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "project.properties");
  627. {
  628. XmlElement* target = proj->createNewChildElement ("target");
  629. target->setAttribute ("name", "clean");
  630. target->setAttribute ("depends", "android_rules.clean");
  631. target->createNewChildElement ("delete")->setAttribute ("dir", "libs");
  632. target->createNewChildElement ("delete")->setAttribute ("dir", "obj");
  633. XmlElement* executable = target->createNewChildElement ("exec");
  634. executable->setAttribute ("executable", "${ndk.dir}/ndk-build");
  635. executable->setAttribute ("dir", "${basedir}");
  636. executable->setAttribute ("failonerror", "true");
  637. executable->createNewChildElement ("arg")->setAttribute ("value", "clean");
  638. }
  639. {
  640. XmlElement* target = proj->createNewChildElement ("target");
  641. target->setAttribute ("name", "-pre-build");
  642. addDebugConditionClause (target, "makefileConfig", "Debug", "Release");
  643. addDebugConditionClause (target, "ndkDebugValue", "NDK_DEBUG=1", "NDK_DEBUG=0");
  644. String debugABIs, releaseABIs;
  645. for (ConstConfigIterator config (*this); config.next();)
  646. {
  647. const AndroidBuildConfiguration& androidConfig = dynamic_cast<const AndroidBuildConfiguration&> (*config);
  648. if (config->isDebug())
  649. debugABIs = androidConfig.getArchitectures();
  650. else
  651. releaseABIs = androidConfig.getArchitectures();
  652. }
  653. addDebugConditionClause (target, "app_abis", debugABIs, releaseABIs);
  654. XmlElement* executable = target->createNewChildElement ("exec");
  655. executable->setAttribute ("executable", "${ndk.dir}/ndk-build");
  656. executable->setAttribute ("dir", "${basedir}");
  657. executable->setAttribute ("failonerror", "true");
  658. executable->createNewChildElement ("arg")->setAttribute ("value", "--jobs=4");
  659. executable->createNewChildElement ("arg")->setAttribute ("value", "CONFIG=${makefileConfig}");
  660. executable->createNewChildElement ("arg")->setAttribute ("value", "${ndkDebugValue}");
  661. executable->createNewChildElement ("arg")->setAttribute ("value", "APP_ABI=${app_abis}");
  662. target->createNewChildElement ("delete")->setAttribute ("file", "${out.final.file}");
  663. target->createNewChildElement ("delete")->setAttribute ("file", "${out.packaged.file}");
  664. }
  665. proj->createNewChildElement ("import")->setAttribute ("file", "${sdk.dir}/tools/ant/build.xml");
  666. return proj;
  667. }
  668. void addDebugConditionClause (XmlElement* target, const String& property,
  669. const String& debugValue, const String& releaseValue) const
  670. {
  671. XmlElement* condition = target->createNewChildElement ("condition");
  672. condition->setAttribute ("property", property);
  673. condition->setAttribute ("value", debugValue);
  674. condition->setAttribute ("else", releaseValue);
  675. XmlElement* equals = condition->createNewChildElement ("equals");
  676. equals->setAttribute ("arg1", "${ant.project.invoked-targets}");
  677. equals->setAttribute ("arg2", "debug");
  678. }
  679. void writeProjectPropertiesFile (const File& file) const
  680. {
  681. MemoryOutputStream mo;
  682. mo << "# This file is used to override default values used by the Ant build system." << newLine
  683. << "# It is automatically generated - DO NOT EDIT IT or your changes will be lost!." << newLine
  684. << newLine
  685. << "target=" << getAppPlatform() << newLine
  686. << newLine;
  687. overwriteFileIfDifferentOrThrow (file, mo);
  688. }
  689. void writeLocalPropertiesFile (const File& file) const
  690. {
  691. MemoryOutputStream mo;
  692. mo << "# This file is used to override default values used by the Ant build system." << newLine
  693. << "# It is automatically generated by the Introjucer - DO NOT EDIT IT or your changes will be lost!." << newLine
  694. << newLine
  695. << "sdk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getSDKPathString())) << newLine
  696. << "ndk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getNDKPathString())) << newLine
  697. << "key.store=" << getKeyStoreString() << newLine
  698. << "key.alias=" << getKeyAliasString() << newLine
  699. << "key.store.password=" << getKeyStorePassString() << newLine
  700. << "key.alias.password=" << getKeyAliasPassString() << newLine
  701. << newLine;
  702. overwriteFileIfDifferentOrThrow (file, mo);
  703. }
  704. void writeStringsFile (const File& file) const
  705. {
  706. XmlElement strings ("resources");
  707. XmlElement* resourceName = strings.createNewChildElement ("string");
  708. resourceName->setAttribute ("name", "app_name");
  709. resourceName->addTextElement (projectName);
  710. writeXmlOrThrow (strings, file, "utf-8", 100);
  711. }
  712. //==============================================================================
  713. JUCE_DECLARE_NON_COPYABLE (AndroidAntProjectExporter)
  714. };