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.

593 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCER_PROJECTEXPORT_ANDROID_JUCEHEADER__
  19. #define __JUCER_PROJECTEXPORT_ANDROID_JUCEHEADER__
  20. #include "jucer_ProjectExporter.h"
  21. //==============================================================================
  22. class AndroidProjectExporter : public ProjectExporter
  23. {
  24. public:
  25. //==============================================================================
  26. static const char* getNameAndroid() { return "Android Project"; }
  27. static const char* getValueTreeTypeName() { return "ANDROID"; }
  28. static AndroidProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  29. {
  30. if (settings.hasType (getValueTreeTypeName()))
  31. return new AndroidProjectExporter (project, settings);
  32. return nullptr;
  33. }
  34. //==============================================================================
  35. AndroidProjectExporter (Project& project_, const ValueTree& settings_)
  36. : ProjectExporter (project_, settings_)
  37. {
  38. name = getNameAndroid();
  39. if (getTargetLocationString().isEmpty())
  40. getTargetLocationValue() = getDefaultBuildsRootFolder() + "Android";
  41. if (getActivityClassPath().isEmpty())
  42. getActivityClassPathValue() = createDefaultClassName();
  43. if (getSDKPathString().isEmpty())
  44. getSDKPathValue() = "${user.home}/SDKs/android-sdk-macosx";
  45. if (getNDKPathString().isEmpty())
  46. getNDKPathValue() = "${user.home}/SDKs/android-ndk-r7b";
  47. if (getMinimumSDKVersionString().isEmpty())
  48. getMinimumSDKVersionValue() = 8;
  49. if (getInternetNeededValue().toString().isEmpty())
  50. getInternetNeededValue() = true;
  51. }
  52. //==============================================================================
  53. int getLaunchPreferenceOrderForCurrentOS()
  54. {
  55. #if JUCE_ANDROID
  56. return 1;
  57. #else
  58. return 0;
  59. #endif
  60. }
  61. bool isPossibleForCurrentProject() { return projectType.isGUIApplication(); }
  62. bool usesMMFiles() const { return false; }
  63. bool canCopeWithDuplicateFiles() { return false; }
  64. void launchProject()
  65. {
  66. }
  67. void createPropertyEditors (PropertyListBuilder& props)
  68. {
  69. ProjectExporter::createPropertyEditors (props);
  70. props.add (new TextPropertyComponent (getActivityClassPathValue(), "Android Activity class name", 256, false),
  71. "The full java class name to use for the app's Activity class.");
  72. props.add (new TextPropertyComponent (getSDKPathValue(), "Android SDK Path", 1024, false),
  73. "The path to the Android SDK folder on the target build machine");
  74. props.add (new TextPropertyComponent (getNDKPathValue(), "Android NDK Path", 1024, false),
  75. "The path to the Android NDK folder on the target build machine");
  76. props.add (new TextPropertyComponent (getMinimumSDKVersionValue(), "Minimum SDK version", 32, false),
  77. "The number of the minimum version of the Android SDK that the app requires");
  78. props.add (new BooleanPropertyComponent (getInternetNeededValue(), "Internet Access", "Specify internet access permission in the manifest"),
  79. "If enabled, this will set the android.permission.INTERNET flag in the manifest.");
  80. props.add (new BooleanPropertyComponent (getAudioRecordNeededValue(), "Audio Input Required", "Specify audio record permission in the manifest"),
  81. "If enabled, this will set the android.permission.RECORD_AUDIO flag in the manifest.");
  82. props.add (new TextPropertyComponent (getOtherPermissionsValue(), "Custom permissions", 2048, false),
  83. "A space-separated list of other permission flags that should be added to the manifest.");
  84. }
  85. Value getActivityClassPathValue() { return getSetting (Ids::androidActivityClass); }
  86. String getActivityClassPath() const { return settings [Ids::androidActivityClass]; }
  87. Value getSDKPathValue() { return getSetting (Ids::androidSDKPath); }
  88. String getSDKPathString() const { return settings [Ids::androidSDKPath]; }
  89. Value getNDKPathValue() { return getSetting (Ids::androidNDKPath); }
  90. String getNDKPathString() const { return settings [Ids::androidNDKPath]; }
  91. Value getInternetNeededValue() { return getSetting (Ids::androidInternetNeeded); }
  92. bool getInternetNeeded() const { return settings [Ids::androidInternetNeeded]; }
  93. Value getAudioRecordNeededValue() { return getSetting (Ids::androidMicNeeded); }
  94. bool getAudioRecordNeeded() const { return settings [Ids::androidMicNeeded]; }
  95. Value getMinimumSDKVersionValue() { return getSetting (Ids::androidMinimumSDK); }
  96. String getMinimumSDKVersionString() const { return settings [Ids::androidMinimumSDK]; }
  97. Value getOtherPermissionsValue() { return getSetting (Ids::androidOtherPermissions); }
  98. String getOtherPermissions() const { return settings [Ids::androidOtherPermissions]; }
  99. String createDefaultClassName() const
  100. {
  101. String s (project.getBundleIdentifier().toString().toLowerCase());
  102. if (s.length() > 5
  103. && s.containsChar ('.')
  104. && s.containsOnly ("abcdefghijklmnopqrstuvwxyz_.")
  105. && ! s.startsWithChar ('.'))
  106. {
  107. if (! s.endsWithChar ('.'))
  108. s << ".";
  109. }
  110. else
  111. {
  112. s = "com.yourcompany.";
  113. }
  114. return s + CodeHelpers::makeValidIdentifier (project.getProjectFilenameRoot(), false, true, false);
  115. }
  116. //==============================================================================
  117. void create (const OwnedArray<LibraryModule>& modules) const
  118. {
  119. const File target (getTargetFolder());
  120. const File jniFolder (target.getChildFile ("jni"));
  121. copyActivityJavaFiles (modules);
  122. createDirectoryOrThrow (jniFolder);
  123. createDirectoryOrThrow (target.getChildFile ("res").getChildFile ("values"));
  124. createDirectoryOrThrow (target.getChildFile ("libs"));
  125. createDirectoryOrThrow (target.getChildFile ("bin"));
  126. {
  127. ScopedPointer<XmlElement> manifest (createManifestXML());
  128. writeXmlOrThrow (*manifest, target.getChildFile ("AndroidManifest.xml"), "utf-8", 100, true);
  129. }
  130. writeApplicationMk (jniFolder.getChildFile ("Application.mk"));
  131. writeAndroidMk (jniFolder.getChildFile ("Android.mk"));
  132. {
  133. ScopedPointer<XmlElement> antBuildXml (createAntBuildXML());
  134. writeXmlOrThrow (*antBuildXml, target.getChildFile ("build.xml"), "UTF-8", 100);
  135. }
  136. writeProjectPropertiesFile (target.getChildFile ("project.properties"));
  137. writeLocalPropertiesFile (target.getChildFile ("local.properties"));
  138. writeStringsFile (target.getChildFile ("res/values/strings.xml"));
  139. const Image bigIcon (getBigIcon());
  140. const Image smallIcon (getSmallIcon());
  141. if (bigIcon.isValid() && smallIcon.isValid())
  142. {
  143. const int step = jmax (bigIcon.getWidth(), bigIcon.getHeight()) / 8;
  144. writeIcon (target.getChildFile ("res/drawable-xhdpi/icon.png"), getBestIconForSize (step * 8, false));
  145. writeIcon (target.getChildFile ("res/drawable-hdpi/icon.png"), getBestIconForSize (step * 6, false));
  146. writeIcon (target.getChildFile ("res/drawable-mdpi/icon.png"), getBestIconForSize (step * 4, false));
  147. writeIcon (target.getChildFile ("res/drawable-ldpi/icon.png"), getBestIconForSize (step * 3, false));
  148. }
  149. else
  150. {
  151. writeIcon (target.getChildFile ("res/drawable-mdpi/icon.png"), bigIcon.isValid() ? bigIcon : smallIcon);
  152. }
  153. }
  154. protected:
  155. //==============================================================================
  156. class AndroidBuildConfiguration : public BuildConfiguration
  157. {
  158. public:
  159. AndroidBuildConfiguration (Project& project, const ValueTree& settings)
  160. : BuildConfiguration (project, settings)
  161. {
  162. if (getArchitectures().isEmpty())
  163. getArchitecturesValue() = "armeabi armeabi-v7a";
  164. }
  165. Value getArchitecturesValue() { return getValue (Ids::androidArchitectures); }
  166. String getArchitectures() const { return config [Ids::androidArchitectures]; }
  167. void createPropertyEditors (PropertyListBuilder& props)
  168. {
  169. createBasicPropertyEditors (props);
  170. props.add (new TextPropertyComponent (getArchitecturesValue(), "Architectures", 256, false),
  171. "A list of the ARM architectures to build (for a fat binary).");
  172. }
  173. };
  174. BuildConfiguration::Ptr createBuildConfig (const ValueTree& settings) const
  175. {
  176. return new AndroidBuildConfiguration (project, settings);
  177. }
  178. private:
  179. //==============================================================================
  180. XmlElement* createManifestXML() const
  181. {
  182. XmlElement* manifest = new XmlElement ("manifest");
  183. manifest->setAttribute ("xmlns:android", "http://schemas.android.com/apk/res/android");
  184. manifest->setAttribute ("android:versionCode", "1");
  185. manifest->setAttribute ("android:versionName", "1.0");
  186. manifest->setAttribute ("package", getActivityClassPackage());
  187. XmlElement* screens = manifest->createNewChildElement ("supports-screens");
  188. screens->setAttribute ("android:smallScreens", "true");
  189. screens->setAttribute ("android:normalScreens", "true");
  190. screens->setAttribute ("android:largeScreens", "true");
  191. //screens->setAttribute ("android:xlargeScreens", "true");
  192. screens->setAttribute ("android:anyDensity", "true");
  193. manifest->createNewChildElement ("uses-sdk")->setAttribute ("android:minSdkVersion", getMinimumSDKVersionString());
  194. {
  195. const StringArray permissions (getPermissionsRequired());
  196. for (int i = permissions.size(); --i >= 0;)
  197. manifest->createNewChildElement ("uses-permission")->setAttribute ("android:name", permissions[i]);
  198. }
  199. if (project.isModuleEnabled ("juce_opengl"))
  200. {
  201. XmlElement* feature = manifest->createNewChildElement ("uses-feature");
  202. feature->setAttribute ("android:glEsVersion", "0x00020000");
  203. feature->setAttribute ("android:required", "true");
  204. }
  205. XmlElement* app = manifest->createNewChildElement ("application");
  206. app->setAttribute ("android:label", "@string/app_name");
  207. app->setAttribute ("android:icon", "@drawable/icon");
  208. XmlElement* act = app->createNewChildElement ("activity");
  209. act->setAttribute ("android:name", getActivityName());
  210. act->setAttribute ("android:label", "@string/app_name");
  211. XmlElement* intent = act->createNewChildElement ("intent-filter");
  212. intent->createNewChildElement ("action")->setAttribute ("android:name", "android.intent.action.MAIN");
  213. intent->createNewChildElement ("category")->setAttribute ("android:name", "android.intent.category.LAUNCHER");
  214. return manifest;
  215. }
  216. StringArray getPermissionsRequired() const
  217. {
  218. StringArray s;
  219. s.addTokens (getOtherPermissions(), ", ", "");
  220. if (getInternetNeeded()) s.add ("android.permission.INTERNET");
  221. if (getAudioRecordNeeded()) s.add ("android.permission.RECORD_AUDIO");
  222. s.trim();
  223. s.removeDuplicates (false);
  224. return s;
  225. }
  226. //==============================================================================
  227. void findAllFilesToCompile (const Project::Item& projectItem, Array<RelativePath>& results) const
  228. {
  229. if (projectItem.isGroup())
  230. {
  231. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  232. findAllFilesToCompile (projectItem.getChild(i), results);
  233. }
  234. else
  235. {
  236. if (projectItem.shouldBeCompiled())
  237. results.add (RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder));
  238. }
  239. }
  240. //==============================================================================
  241. String getActivityName() const
  242. {
  243. return getActivityClassPath().fromLastOccurrenceOf (".", false, false);
  244. }
  245. String getActivityClassPackage() const
  246. {
  247. return getActivityClassPath().upToLastOccurrenceOf (".", false, false);
  248. }
  249. String getJNIActivityClassName() const
  250. {
  251. return getActivityClassPath().replaceCharacter ('.', '/');
  252. }
  253. static LibraryModule* getCoreModule (const OwnedArray<LibraryModule>& modules)
  254. {
  255. for (int i = modules.size(); --i >= 0;)
  256. if (modules.getUnchecked(i)->getID() == "juce_core")
  257. return modules.getUnchecked(i);
  258. return nullptr;
  259. }
  260. void copyActivityJavaFiles (const OwnedArray<LibraryModule>& modules) const
  261. {
  262. const String className (getActivityName());
  263. const String package (getActivityClassPackage());
  264. String path (package.replaceCharacter ('.', File::separator));
  265. if (path.isEmpty() || className.isEmpty())
  266. throw SaveError ("Invalid Android Activity class name: " + getActivityClassPath());
  267. const File classFolder (getTargetFolder().getChildFile ("src")
  268. .getChildFile (path));
  269. createDirectoryOrThrow (classFolder);
  270. LibraryModule* const coreModule = getCoreModule (modules);
  271. if (coreModule == nullptr)
  272. throw SaveError ("To build an Android app, the juce_core module must be included in your project!");
  273. File javaDestFile (classFolder.getChildFile (className + ".java"));
  274. File javaSourceFile (coreModule->getFolder().getChildFile ("native")
  275. .getChildFile ("java")
  276. .getChildFile ("JuceAppActivity.java"));
  277. MemoryOutputStream newFile;
  278. newFile << javaSourceFile.loadFileAsString()
  279. .replace ("JuceAppActivity", className)
  280. .replace ("package com.juce;", "package " + package + ";");
  281. overwriteFileIfDifferentOrThrow (javaDestFile, newFile);
  282. }
  283. void writeApplicationMk (const File& file) const
  284. {
  285. MemoryOutputStream mo;
  286. mo << "# Automatically generated makefile, created by the Introjucer" << newLine
  287. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  288. << newLine
  289. << "APP_STL := gnustl_static" << newLine
  290. << "APP_CPPFLAGS += -fsigned-char -fexceptions -frtti" << newLine
  291. << "APP_PLATFORM := android-8" << newLine;
  292. overwriteFileIfDifferentOrThrow (file, mo);
  293. }
  294. void writeAndroidMk (const File& file) const
  295. {
  296. Array<RelativePath> files;
  297. for (int i = 0; i < groups.size(); ++i)
  298. findAllFilesToCompile (groups.getReference(i), files);
  299. MemoryOutputStream mo;
  300. writeAndroidMk (mo, files);
  301. overwriteFileIfDifferentOrThrow (file, mo);
  302. }
  303. void writeAndroidMk (OutputStream& out, const Array<RelativePath>& files) const
  304. {
  305. out << "# Automatically generated makefile, created by the Introjucer" << newLine
  306. << "# Don't edit this file! Your changes will be overwritten when you re-save the Introjucer project!" << newLine
  307. << newLine
  308. << "LOCAL_PATH := $(call my-dir)" << newLine
  309. << newLine
  310. << "include $(CLEAR_VARS)" << newLine
  311. << newLine
  312. << "LOCAL_MODULE := juce_jni" << newLine
  313. << "LOCAL_SRC_FILES := \\" << newLine;
  314. for (int i = 0; i < files.size(); ++i)
  315. out << " ../" << escapeSpaces (files.getReference(i).toUnixStyle()) << "\\" << newLine;
  316. String debugSettings, releaseSettings;
  317. out << newLine
  318. << "ifeq ($(CONFIG),Debug)" << newLine;
  319. writeConfigSettings (out, true);
  320. out << "else" << newLine;
  321. writeConfigSettings (out, false);
  322. out << "endif" << newLine
  323. << newLine
  324. << "include $(BUILD_SHARED_LIBRARY)" << newLine;
  325. }
  326. void writeConfigSettings (OutputStream& out, bool forDebug) const
  327. {
  328. for (ConstConfigIterator config (*this); config.next();)
  329. {
  330. if (config->isDebug() == forDebug)
  331. {
  332. const AndroidBuildConfiguration& androidConfig = dynamic_cast <const AndroidBuildConfiguration&> (*config);
  333. out << " LOCAL_CPPFLAGS += " << createCPPFlags (*config) << newLine
  334. << " APP_ABI := " << androidConfig.getArchitectures() << newLine
  335. << getDynamicLibs (androidConfig);
  336. break;
  337. }
  338. }
  339. }
  340. String getDynamicLibs (const AndroidBuildConfiguration& config) const
  341. {
  342. String flags (" LOCAL_LDLIBS :=");
  343. flags << config.getGCCLibraryPathFlags();
  344. {
  345. StringArray libs;
  346. libs.add ("log");
  347. libs.add ("GLESv1_CM");
  348. libs.add ("GLESv2");
  349. for (int i = 0; i < libs.size(); ++i)
  350. flags << " -l" << libs[i];
  351. }
  352. return flags + newLine;
  353. }
  354. String createIncludePathFlags (const BuildConfiguration& config) const
  355. {
  356. String flags;
  357. StringArray searchPaths (extraSearchPaths);
  358. searchPaths.addArray (config.getHeaderSearchPaths());
  359. searchPaths.removeDuplicates (false);
  360. for (int i = 0; i < searchPaths.size(); ++i)
  361. flags << " -I " << FileHelpers::unixStylePath (replacePreprocessorTokens (config, searchPaths[i])).quoted();
  362. return flags;
  363. }
  364. String createCPPFlags (const BuildConfiguration& config) const
  365. {
  366. StringPairArray defines;
  367. defines.set ("JUCE_ANDROID", "1");
  368. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  369. defines.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\\\"" + getJNIActivityClassName() + "\\\"");
  370. String flags ("-fsigned-char -fexceptions -frtti");
  371. if (config.isDebug())
  372. {
  373. flags << " -g";
  374. defines.set ("DEBUG", "1");
  375. defines.set ("_DEBUG", "1");
  376. }
  377. else
  378. {
  379. defines.set ("NDEBUG", "1");
  380. }
  381. flags << createIncludePathFlags (config)
  382. << " -O" << config.getGCCOptimisationFlag();
  383. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  384. return flags + createGCCPreprocessorFlags (defines);
  385. }
  386. //==============================================================================
  387. XmlElement* createAntBuildXML() const
  388. {
  389. XmlElement* proj = new XmlElement ("project");
  390. proj->setAttribute ("name", projectName);
  391. proj->setAttribute ("default", "debug");
  392. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "local.properties");
  393. proj->createNewChildElement ("loadproperties")->setAttribute ("srcFile", "project.properties");
  394. XmlElement* path = proj->createNewChildElement ("path");
  395. path->setAttribute ("id", "android.antlibs");
  396. path->createNewChildElement ("pathelement")->setAttribute ("path", "${sdk.dir}/tools/lib/anttasks.jar");
  397. path->createNewChildElement ("pathelement")->setAttribute ("path", "${sdk.dir}/tools/lib/sdklib.jar");
  398. path->createNewChildElement ("pathelement")->setAttribute ("path", "${sdk.dir}/tools/lib/androidprefs.jar");
  399. XmlElement* taskdef = proj->createNewChildElement ("taskdef");
  400. taskdef->setAttribute ("name", "setup");
  401. taskdef->setAttribute ("classname", "com.android.ant.SetupTask");
  402. taskdef->setAttribute ("classpathref", "android.antlibs");
  403. addNDKBuildStep (proj, "clean", "clean");
  404. addNDKBuildStep (proj, "debug", "CONFIG=Debug");
  405. addNDKBuildStep (proj, "release", "CONFIG=Release");
  406. proj->createNewChildElement ("import")->setAttribute ("file", "${sdk.dir}/tools/ant/build.xml");
  407. return proj;
  408. }
  409. static void addNDKBuildStep (XmlElement* project, const String& type, const String& arg)
  410. {
  411. XmlElement* target = project->createNewChildElement ("target");
  412. target->setAttribute ("name", type);
  413. XmlElement* executable = target->createNewChildElement ("exec");
  414. executable->setAttribute ("executable", "${ndk.dir}/ndk-build");
  415. executable->setAttribute ("dir", "${basedir}");
  416. executable->setAttribute ("failonerror", "true");
  417. executable->createNewChildElement ("arg")->setAttribute ("value", "--jobs=2");
  418. executable->createNewChildElement ("arg")->setAttribute ("value", arg);
  419. }
  420. void writeProjectPropertiesFile (const File& file) const
  421. {
  422. MemoryOutputStream mo;
  423. mo << "# This file is used to override default values used by the Ant build system." << newLine
  424. << "# It is automatically generated - DO NOT EDIT IT or your changes will be lost!." << newLine
  425. << newLine
  426. << "target=Google Inc.:Google APIs:8" << newLine
  427. << newLine;
  428. overwriteFileIfDifferentOrThrow (file, mo);
  429. }
  430. void writeLocalPropertiesFile (const File& file) const
  431. {
  432. MemoryOutputStream mo;
  433. mo << "# This file is used to override default values used by the Ant build system." << newLine
  434. << "# It is automatically generated by the Introjucer - DO NOT EDIT IT or your changes will be lost!." << newLine
  435. << newLine
  436. << "sdk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getSDKPathString())) << newLine
  437. << "ndk.dir=" << escapeSpaces (replacePreprocessorDefs (getAllPreprocessorDefs(), getNDKPathString())) << newLine
  438. << newLine;
  439. overwriteFileIfDifferentOrThrow (file, mo);
  440. }
  441. void writeIcon (const File& file, const Image& im) const
  442. {
  443. if (im.isValid())
  444. {
  445. createDirectoryOrThrow (file.getParentDirectory());
  446. PNGImageFormat png;
  447. MemoryOutputStream mo;
  448. if (! png.writeImageToStream (im, mo))
  449. throw SaveError ("Can't generate Android icon file");
  450. overwriteFileIfDifferentOrThrow (file, mo);
  451. }
  452. }
  453. void writeStringsFile (const File& file) const
  454. {
  455. XmlElement strings ("resources");
  456. XmlElement* name = strings.createNewChildElement ("string");
  457. name->setAttribute ("name", "app_name");
  458. name->addTextElement (projectName);
  459. writeXmlOrThrow (strings, file, "utf-8", 100);
  460. }
  461. //==============================================================================
  462. JUCE_DECLARE_NON_COPYABLE (AndroidProjectExporter);
  463. };
  464. #endif // __JUCER_PROJECTEXPORT_ANDROID_JUCEHEADER__