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.

623 lines
23KB

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