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.

665 lines
26KB

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