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.

858 lines
39KB

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