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.

635 lines
24KB

  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 AndroidStudioProjectExporter : public AndroidProjectExporterBase
  18. {
  19. public:
  20. //==============================================================================
  21. static const char* getName() { return "Android Studio"; }
  22. static const char* getValueTreeTypeName() { return "ANDROIDSTUDIO"; }
  23. static AndroidStudioProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  24. {
  25. if (settings.hasType (getValueTreeTypeName()))
  26. return new AndroidStudioProjectExporter (project, settings);
  27. return nullptr;
  28. }
  29. //==============================================================================
  30. AndroidStudioProjectExporter (Project& p, const ValueTree& t)
  31. : AndroidProjectExporterBase (p, t),
  32. androidStudioExecutable (findAndroidStudioExecutable())
  33. {
  34. name = getName();
  35. if (getTargetLocationString().isEmpty())
  36. getTargetLocationValue() = getDefaultBuildsRootFolder() + "AndroidStudio";
  37. }
  38. //==============================================================================
  39. bool canLaunchProject() override
  40. {
  41. return androidStudioExecutable.exists();
  42. }
  43. bool launchProject() override
  44. {
  45. if (! androidStudioExecutable.exists())
  46. {
  47. jassertfalse;
  48. return false;
  49. }
  50. const File targetFolder (getTargetFolder());
  51. return androidStudioExecutable.startAsProcess (targetFolder.getFullPathName());
  52. }
  53. void createExporterProperties (PropertyListBuilder& props) override
  54. {
  55. AndroidProjectExporterBase::createExporterProperties (props);
  56. props.add (new TextPropertyComponent (getNDKPlatformVersionValue(), "NDK Platform Version", 32, false),
  57. "The value to use for android$user.ndk.platformVersion in Gradle");
  58. }
  59. Value getNDKPlatformVersionValue() { return getSetting (Ids::androidNdkPlatformVersion); }
  60. String getNDKPlatformVersionString() const { return settings [Ids::androidNdkPlatformVersion]; }
  61. void create (const OwnedArray<LibraryModule>& modules) const override
  62. {
  63. const File targetFolder (getTargetFolder());
  64. targetFolder.deleteRecursively();
  65. {
  66. const String package (getActivityClassPackage());
  67. const String path (package.replaceCharacter ('.', File::separator));
  68. const File javaTarget (targetFolder.getChildFile ("app/src/main/java").getChildFile (path));
  69. copyActivityJavaFiles (modules, javaTarget, package);
  70. }
  71. writeSettingsDotGradle (targetFolder);
  72. writeLocalDotProperties (targetFolder);
  73. writeBuildDotGradleRoot (targetFolder);
  74. writeBuildDotGradleApp (targetFolder);
  75. writeGradleWrapperProperties (targetFolder);
  76. writeAndroidManifest (targetFolder);
  77. writeStringsXML (targetFolder);
  78. writeAppIcons (targetFolder);
  79. createSourceSymlinks (targetFolder);
  80. }
  81. static File findAndroidStudioExecutable()
  82. {
  83. #if JUCE_WINDOWS
  84. const File defaultInstallation ("C:\\Program Files\\Android\\Android Studio\\bin");
  85. if (defaultInstallation.exists())
  86. {
  87. {
  88. const File studio64 = defaultInstallation.getChildFile ("studio64.exe");
  89. if (studio64.existsAsFile())
  90. return studio64;
  91. }
  92. {
  93. const File studio = defaultInstallation.getChildFile ("studio.exe");
  94. if (studio.existsAsFile())
  95. return studio;
  96. }
  97. }
  98. #elif JUCE_MAC
  99. const File defaultInstallation ("/Applications/Android Studio.app");
  100. if (defaultInstallation.exists())
  101. return defaultInstallation;
  102. #endif
  103. return File::nonexistent;
  104. }
  105. protected:
  106. //==============================================================================
  107. class AndroidStudioBuildConfiguration : public BuildConfiguration
  108. {
  109. public:
  110. AndroidStudioBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
  111. : BuildConfiguration (p, settings, e)
  112. {
  113. if (getArchitectures().isEmpty())
  114. {
  115. if (isDebug())
  116. getArchitecturesValue() = "armeabi x86";
  117. else
  118. getArchitecturesValue() = "armeabi armeabi-v7a x86";
  119. }
  120. }
  121. Value getArchitecturesValue() { return getValue (Ids::androidArchitectures); }
  122. String getArchitectures() const { return config [Ids::androidArchitectures]; }
  123. var getDefaultOptimisationLevel() const override { return var ((int) (isDebug() ? gccO0 : gccO3)); }
  124. void createConfigProperties (PropertyListBuilder& props) override
  125. {
  126. addGCCOptimisationProperty (props);
  127. props.add (new TextPropertyComponent (getArchitecturesValue(), "Architectures", 256, false),
  128. "A list of the ARM architectures to build (for a fat binary).");
  129. }
  130. };
  131. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  132. {
  133. return new AndroidStudioBuildConfiguration (project, v, *this);
  134. }
  135. private:
  136. static void createSymboicLinkAndCreateParentFolders (const File& originalFile, const File& linkFile)
  137. {
  138. {
  139. const File linkFileParentDirectory (linkFile.getParentDirectory());
  140. // this will recursively creative the parent directories for the file
  141. // without this, the symlink would fail because it doesn't automatically create
  142. // the folders if they don't exist
  143. if (! linkFileParentDirectory.createDirectory())
  144. throw SaveError (String ("Could not create directory ") + linkFileParentDirectory.getFullPathName());
  145. }
  146. if (! originalFile.createSymbolicLink (linkFile, true))
  147. throw SaveError (String ("Failed to create symlink from ")
  148. + linkFile.getFullPathName() + " to "
  149. + originalFile.getFullPathName() + "!");
  150. }
  151. void makeSymlinksForGroup (const Project::Item& group, const File& targetFolder) const
  152. {
  153. if (! group.isGroup())
  154. {
  155. throw SaveError ("makeSymlinksForGroup was called with something other than a group!");
  156. }
  157. for (int i = 0; i < group.getNumChildren(); ++i)
  158. {
  159. const Project::Item& projectItem = group.getChild (i);
  160. if (projectItem.isGroup())
  161. {
  162. makeSymlinksForGroup (projectItem, targetFolder.getChildFile (projectItem.getName()));
  163. }
  164. else if (projectItem.shouldBeAddedToTargetProject()) // must be a file then
  165. {
  166. const File originalFile (projectItem.getFile());
  167. const File targetFile (targetFolder.getChildFile (originalFile.getFileName()));
  168. createSymboicLinkAndCreateParentFolders (originalFile, targetFile);
  169. }
  170. }
  171. }
  172. void createSourceSymlinks (const File& folder) const
  173. {
  174. const File targetFolder (folder.getChildFile ("app/src/main/jni"));
  175. // here we make symlinks to only to files included in the groups inside the project
  176. // this is because Android Studio does not have a concept of groups and just uses
  177. // the file system layout to determine what's to be compiled
  178. {
  179. const Array<Project::Item>& groups = getAllGroups();
  180. for (int i = 0; i < groups.size(); ++i)
  181. {
  182. const Project::Item projectItem (groups.getReference (i));
  183. const String projectItemName (projectItem.getName());
  184. if (projectItem.isGroup())
  185. makeSymlinksForGroup (projectItem, projectItemName == "Juce Modules" ? targetFolder.getChildFile ("JuceModules") : targetFolder);
  186. }
  187. }
  188. }
  189. void writeAppIcons (const File& folder) const
  190. {
  191. writeIcons (folder.getChildFile ("app/src/main/res/"));
  192. }
  193. void writeSettingsDotGradle (const File& folder) const
  194. {
  195. MemoryOutputStream memoryOutputStream;
  196. memoryOutputStream << "include ':app'";
  197. overwriteFileIfDifferentOrThrow (folder.getChildFile ("settings.gradle"), memoryOutputStream);
  198. }
  199. static String sanitisePath (String path)
  200. {
  201. return expandHomeFolderToken (path).replace ("\\", "\\\\");
  202. }
  203. static String expandHomeFolderToken (const String& path)
  204. {
  205. String homeFolder = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
  206. return path.replace ("${user.home}", homeFolder)
  207. .replace ("~", homeFolder);
  208. }
  209. void writeLocalDotProperties (const File& folder) const
  210. {
  211. MemoryOutputStream memoryOutputStream;
  212. memoryOutputStream << "ndk.dir=" << sanitisePath (getNDKPathString()) << newLine
  213. << "sdk.dir=" << sanitisePath (getSDKPathString());
  214. overwriteFileIfDifferentOrThrow (folder.getChildFile ("local.properties"), memoryOutputStream);
  215. }
  216. void writeGradleWrapperProperties (const File& folder) const
  217. {
  218. MemoryOutputStream memoryOutputStream;
  219. memoryOutputStream << "distributionUrl=https\\://services.gradle.org/distributions/gradle-2.6-all.zip";
  220. overwriteFileIfDifferentOrThrow (folder.getChildFile ("gradle/wrapper/gradle-wrapper.properties"), memoryOutputStream);
  221. }
  222. void writeBuildDotGradleRoot (const File& folder) const
  223. {
  224. MemoryOutputStream memoryOutputStream;
  225. const String indent = getIndentationString();
  226. // this is needed to make sure the correct version of
  227. // the gradle build tools is available
  228. // otherwise, the user will get an error about
  229. // com.android.tools.something not being available
  230. memoryOutputStream << "buildscript {" << newLine
  231. << indent << "repositories {" << newLine
  232. << indent << indent << "jcenter()" << newLine
  233. << indent << "}" << newLine
  234. << indent << "dependencies {" << newLine
  235. << indent << indent << "classpath 'com.android.tools.build:gradle-experimental:0.3.0-alpha7'" << newLine
  236. << indent << "}" << newLine
  237. << "}" << newLine
  238. << newLine
  239. << "allprojects {" << newLine
  240. << indent << "repositories {" << newLine
  241. << indent << indent << "jcenter()" << newLine
  242. << indent << "}" << newLine
  243. << "}";
  244. overwriteFileIfDifferentOrThrow (folder.getChildFile ("build.gradle"), memoryOutputStream);
  245. }
  246. void writeStringsXML (const File& folder) const
  247. {
  248. XmlElement strings ("resources");
  249. XmlElement* resourceName = strings.createNewChildElement ("string");
  250. resourceName->setAttribute ("name", "app_name");
  251. resourceName->addTextElement (projectName);
  252. writeXmlOrThrow (strings, folder.getChildFile ("app/src/main/res/values/string.xml"), "utf-8", 100, true);
  253. }
  254. void writeAndroidManifest (const File& folder) const
  255. {
  256. ScopedPointer<XmlElement> manifest (createManifestXML());
  257. writeXmlOrThrow (*manifest, folder.getChildFile ("app/src/main/AndroidManifest.xml"), "utf-8", 100, true);
  258. }
  259. String createModelDotAndroid (const String& indent, const String& minimumSDKVersion, const String& bundleIdentifier) const
  260. {
  261. String result;
  262. result << "android {" << newLine
  263. << indent << "compileSdkVersion = " << minimumSDKVersion << newLine
  264. << indent << "buildToolsVersion = \"" << "23.0.1" << "\"" << newLine
  265. << indent << "defaultConfig.with {" << newLine
  266. << indent << indent << "applicationId = \"" << bundleIdentifier.toLowerCase() << "\"" << newLine
  267. << indent << indent << "minSdkVersion.apiLevel = 11" << newLine
  268. << indent << indent << "targetSdkVersion.apiLevel = " << minimumSDKVersion << newLine
  269. << indent << "}" << newLine
  270. << "}" << newLine;
  271. return result;
  272. }
  273. String createModelDotCompileOptions (const String& indent) const
  274. {
  275. String result;
  276. result << "compileOptions.with {" << newLine
  277. << indent << "sourceCompatibility = JavaVersion.VERSION_1_7" << newLine
  278. << indent << indent << "targetCompatibility = JavaVersion.VERSION_1_7" << newLine
  279. << "}" << newLine;
  280. return result;
  281. }
  282. String createModelDotAndroidSources (const String& indent) const
  283. {
  284. String result;
  285. result << "android.sources {" << newLine
  286. << indent << "main {" << newLine
  287. << indent << indent << "jni {" << newLine
  288. << indent << indent << indent << "source {" << newLine
  289. << indent << indent << indent << indent << "exclude \"**/JuceModules/\"" << newLine
  290. << indent << indent << indent << "}" << newLine
  291. << indent << indent << "}" << newLine
  292. << indent << "}" << newLine
  293. << "}" << newLine;
  294. return result;
  295. }
  296. struct ShouldBeAddedToProjectPredicate
  297. {
  298. bool operator() (const Project::Item& projectItem) const { return projectItem.shouldBeAddedToTargetProject(); }
  299. };
  300. StringArray getCPPFlags() const
  301. {
  302. StringArray result;
  303. result.add ("\"-fsigned-char\"");
  304. result.add ("\"-fexceptions\"");
  305. result.add ("\"-frtti\"");
  306. if (isCPP11Enabled())
  307. result.add ("\"-std=gnu++11\"");
  308. // preprocessor definitions
  309. {
  310. StringPairArray preprocessorDefinitions = getAllPreprocessorDefs();
  311. preprocessorDefinitions.set ("JUCE_ANDROID", "1");
  312. preprocessorDefinitions.set ("JUCE_ANDROID_API_VERSION", getMinimumSDKVersionString());
  313. preprocessorDefinitions.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  314. preprocessorDefinitions.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\\\"" + getActivityClassPath().replaceCharacter('.', '/') + "\\\"");
  315. const StringArray& keys = preprocessorDefinitions.getAllKeys();
  316. for (int i = 0; i < keys.size(); ++i)
  317. result.add (String ("\"-D") + keys[i] + String ("=") + preprocessorDefinitions[keys[i]] + "\"");
  318. }
  319. // include paths
  320. result.add ("\"-I${project.rootDir}/app\".toString()");
  321. result.add ("\"-I${ext.juceRootDir}\".toString()");
  322. result.add ("\"-I${ext.juceModuleDir}\".toString()");
  323. {
  324. Array<RelativePath> cppFiles;
  325. const Array<Project::Item>& groups = getAllGroups();
  326. for (int i = 0; i < groups.size(); ++i)
  327. findAllProjectItemsWithPredicate (groups.getReference (i), cppFiles, ShouldBeAddedToProjectPredicate());
  328. for (int i = 0; i < cppFiles.size(); ++i)
  329. {
  330. const RelativePath absoluteSourceFile (cppFiles.getReference (i).rebased (getTargetFolder(),
  331. project.getProjectFolder(),
  332. RelativePath::projectFolder));
  333. const String absoluteIncludeFolder (sanitisePath (project.getProjectFolder().getFullPathName() + "/"
  334. + absoluteSourceFile.toUnixStyle().upToLastOccurrenceOf ("/", false, false)));
  335. result.addIfNotAlreadyThere ("\"-I" + absoluteIncludeFolder + "\".toString()");
  336. }
  337. }
  338. return result;
  339. }
  340. StringArray getLDLibs() const
  341. {
  342. StringArray result;
  343. result.add ("android");
  344. result.add ("EGL");
  345. result.add ("GLESv2");
  346. result.add ("log");
  347. result.addArray (StringArray::fromTokens(getExternalLibrariesString(), ";", ""));
  348. return result;
  349. }
  350. String createModelDotAndroidNDK (const String& indent) const
  351. {
  352. String result;
  353. const String platformVersion (getNDKPlatformVersionString());
  354. result << "android.ndk {" << newLine
  355. << indent << "moduleName = \"juce_jni\"" << newLine
  356. << indent << "stl = \"gnustl_static\"" << newLine
  357. << indent << "toolchainVersion = 4.9" << newLine;
  358. if (platformVersion.isNotEmpty())
  359. result << indent << "platformVersion = " << getNDKPlatformVersionString() << newLine;
  360. result << indent << "ext {" << newLine
  361. << indent << indent << "juceRootDir = \"" << "${project.rootDir}/../../../../" << "\".toString()" << newLine
  362. << indent << indent << "juceModuleDir = \"" << "${juceRootDir}/modules" << "\".toString()" << newLine
  363. << indent << "}" << newLine;
  364. // CPP flags
  365. {
  366. StringArray cppFlags (getCPPFlags());
  367. for (int i = 0; i < cppFlags.size(); ++i)
  368. result << indent << "cppFlags += " << cppFlags[i] << newLine;
  369. }
  370. // libraries
  371. {
  372. StringArray libraries (getLDLibs());
  373. result << indent << "ldLibs += [";
  374. for (int i = 0; i < libraries.size(); ++i)
  375. {
  376. result << "\"" << libraries[i] << "\"";
  377. if (i + 1 != libraries.size())
  378. result << ", ";
  379. }
  380. result << "]" << newLine;
  381. }
  382. result << "}" << newLine;
  383. return result;
  384. }
  385. String getGradleCPPFlags (const String& indent, const ConstConfigIterator& config) const
  386. {
  387. String result;
  388. StringArray rootFlags;
  389. StringArray ndkFlags;
  390. if (config->isDebug())
  391. {
  392. ndkFlags.add ("debuggable = true");
  393. ndkFlags.add ("cppFlags += \"-g\"");
  394. ndkFlags.add ("cppFlags += \"-DDEBUG=1\"");
  395. ndkFlags.add ("cppFlags += \"-D_DEBUG=1\"");
  396. }
  397. else
  398. {
  399. rootFlags.add ("minifyEnabled = true");
  400. rootFlags.add ("proguardFiles += 'proguard-android-optimize.txt'");
  401. ndkFlags.add ("cppFlags += \"-DNDEBUG=1\"");
  402. }
  403. {
  404. StringArray extraFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), " ", ""));
  405. for (int i = 0; extraFlags.size(); ++i)
  406. ndkFlags.add (String ("cppFlags += \"") + extraFlags[i] + "\"");
  407. }
  408. // there appears to be an issue with build types that have a name other than
  409. // "debug" or "release". Apparently this is hard coded in Android Studio ...
  410. {
  411. const String configName (config->getName());
  412. if (configName != "Debug" && configName != "Release")
  413. throw SaveError ("Build configurations other than Debug and Release are not yet support for Android Studio");
  414. result << configName.toLowerCase() << " {" << newLine;
  415. }
  416. for (int i = 0; i < rootFlags.size(); ++i)
  417. result << indent << rootFlags[i] << newLine;
  418. result << indent << "ndk.with {" << newLine;
  419. for (int i = 0; i < ndkFlags.size(); ++i)
  420. result << indent << indent << ndkFlags[i] << newLine;
  421. result << indent << "}" << newLine
  422. << "}" << newLine;
  423. return result;
  424. }
  425. String createModelDotAndroidDotBuildTypes (const String& indent) const
  426. {
  427. String result;
  428. result << "android.buildTypes {" << newLine;
  429. for (ConstConfigIterator config (*this); config.next();)
  430. result << CodeHelpers::indent (getGradleCPPFlags (indent, config), indent.length(), true);
  431. result << "}";
  432. return result;
  433. }
  434. String createModelDotAndroidDotProductFlavors (const String& indent) const
  435. {
  436. String result;
  437. result << "android.productFlavors {" << newLine;
  438. // TODO! - this needs to be changed so that it generates seperate flags for debug and release ...
  439. // at present, it just generates all ABIs for all build types
  440. StringArray architectures (StringArray::fromTokens (getABIs<AndroidStudioBuildConfiguration> (true), " ", ""));
  441. architectures.mergeArray (StringArray::fromTokens (getABIs<AndroidStudioBuildConfiguration> (false), " ", ""));
  442. if (architectures.size() == 0)
  443. throw SaveError ("Can't build for no architectures!");
  444. for (int i = 0; i < architectures.size(); ++i)
  445. {
  446. String architecture (architectures[i].trim());
  447. if (architecture.isEmpty())
  448. continue;
  449. result << indent << "create(\"" << architecture << "\") {" << newLine
  450. << indent << indent << "ndk.abiFilters += \"" << architecture << "\"" << newLine
  451. << indent << "}" << newLine;
  452. }
  453. result << "}" << newLine;
  454. return result;
  455. }
  456. void writeBuildDotGradleApp (const File& folder) const
  457. {
  458. MemoryOutputStream memoryOutputStream;
  459. const String indent = getIndentationString();
  460. const String minimumSDKVersion = getMinimumSDKVersionString();
  461. const String bundleIdentifier = project.getBundleIdentifier().toString();
  462. memoryOutputStream << "apply plugin: 'com.android.model.application'" << newLine
  463. << newLine
  464. << "model {" << newLine
  465. << CodeHelpers::indent (createModelDotAndroid (indent, minimumSDKVersion, bundleIdentifier), indent.length(), true)
  466. << newLine
  467. << CodeHelpers::indent (createModelDotCompileOptions (indent), indent.length(), true)
  468. << newLine
  469. << CodeHelpers::indent (createModelDotAndroidSources (indent), indent.length(), true)
  470. << newLine
  471. << CodeHelpers::indent (createModelDotAndroidNDK (indent), indent.length(), true)
  472. << newLine
  473. << CodeHelpers::indent (createModelDotAndroidDotBuildTypes (indent), indent.length(), true)
  474. << newLine
  475. << CodeHelpers::indent (createModelDotAndroidDotProductFlavors (indent), indent.length(), true)
  476. << "}";
  477. overwriteFileIfDifferentOrThrow (folder.getChildFile ("app/build.gradle"), memoryOutputStream);
  478. }
  479. static const char* getIndentationString() noexcept
  480. {
  481. return " ";
  482. }
  483. const File androidStudioExecutable;
  484. JUCE_DECLARE_NON_COPYABLE (AndroidStudioProjectExporter)
  485. };