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.

622 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. if (path.startsWith ("~"))
  198. {
  199. const String homeFolder (File::getSpecialLocation (File::SpecialLocationType::userHomeDirectory).getFullPathName());
  200. path = path.replaceSection (0, 1, homeFolder);
  201. }
  202. return path.replace ("\\", "\\\\");
  203. }
  204. void writeLocalDotProperties (const File& folder) const
  205. {
  206. MemoryOutputStream memoryOutputStream;
  207. memoryOutputStream << "ndk.dir=" << sanitisePath (getNDKPathString()) << newLine
  208. << "sdk.dir=" << sanitisePath (getSDKPathString());
  209. overwriteFileIfDifferentOrThrow (folder.getChildFile ("local.properties"), memoryOutputStream);
  210. }
  211. void writeGradleWrapperProperties (const File& folder) const
  212. {
  213. MemoryOutputStream memoryOutputStream;
  214. memoryOutputStream << "distributionUrl=https\\://services.gradle.org/distributions/gradle-2.6-all.zip";
  215. overwriteFileIfDifferentOrThrow (folder.getChildFile ("gradle/wrapper/gradle-wrapper.properties"), memoryOutputStream);
  216. }
  217. void writeBuildDotGradleRoot (const File& folder) const
  218. {
  219. MemoryOutputStream memoryOutputStream;
  220. const String indent = getIndentationString();
  221. // this is needed to make sure the correct version of
  222. // the gradle build tools is available
  223. // otherwise, the user will get an error about
  224. // com.android.tools.something not being available
  225. memoryOutputStream << "buildscript {" << newLine
  226. << indent << "repositories {" << newLine
  227. << indent << indent << "jcenter()" << newLine
  228. << indent << "}" << newLine
  229. << indent << "dependencies {" << newLine
  230. << indent << indent << "classpath 'com.android.tools.build:gradle-experimental:0.3.0-alpha7'" << newLine
  231. << indent << "}" << newLine
  232. << "}" << newLine
  233. << newLine
  234. << "allprojects {" << newLine
  235. << indent << "repositories {" << newLine
  236. << indent << indent << "jcenter()" << newLine
  237. << indent << "}" << newLine
  238. << "}";
  239. overwriteFileIfDifferentOrThrow (folder.getChildFile ("build.gradle"), memoryOutputStream);
  240. }
  241. void writeStringsXML (const File& folder) const
  242. {
  243. XmlElement strings ("resources");
  244. XmlElement* resourceName = strings.createNewChildElement ("string");
  245. resourceName->setAttribute ("name", "app_name");
  246. resourceName->addTextElement (projectName);
  247. writeXmlOrThrow (strings, folder.getChildFile ("app/src/main/res/values/string.xml"), "utf-8", 100, true);
  248. }
  249. void writeAndroidManifest (const File& folder) const
  250. {
  251. ScopedPointer<XmlElement> manifest (createManifestXML());
  252. writeXmlOrThrow (*manifest, folder.getChildFile ("app/src/main/AndroidManifest.xml"), "utf-8", 100, true);
  253. }
  254. String createModelDotAndroid (const String& indent, const String& minimumSDKVersion, const String& bundleIdentifier) const
  255. {
  256. String result;
  257. result << "android {" << newLine
  258. << indent << "compileSdkVersion = " << minimumSDKVersion << newLine
  259. << indent << "buildToolsVersion = \"" << "23.0.1" << "\"" << newLine
  260. << indent << "defaultConfig.with {" << newLine
  261. << indent << indent << "applicationId = \"" << bundleIdentifier.toLowerCase() << "\"" << newLine
  262. << indent << indent << "minSdkVersion.apiLevel = 11" << newLine
  263. << indent << indent << "targetSdkVersion.apiLevel = " << minimumSDKVersion << newLine
  264. << indent << "}" << newLine
  265. << "}" << newLine;
  266. return result;
  267. }
  268. String createModelDotCompileOptions (const String& indent) const
  269. {
  270. String result;
  271. result << "compileOptions.with {" << newLine
  272. << indent << "sourceCompatibility = JavaVersion.VERSION_1_7" << newLine
  273. << indent << indent << "targetCompatibility = JavaVersion.VERSION_1_7" << newLine
  274. << "}" << newLine;
  275. return result;
  276. }
  277. String createModelDotAndroidSources (const String& indent) const
  278. {
  279. String result;
  280. result << "android.sources {" << newLine
  281. << indent << "main {" << newLine
  282. << indent << indent << "jni {" << newLine
  283. << indent << indent << indent << "source {" << newLine
  284. << indent << indent << indent << indent << "exclude \"**/JuceModules/\"" << newLine
  285. << indent << indent << indent << "}" << newLine
  286. << indent << indent << "}" << newLine
  287. << indent << "}" << newLine
  288. << "}" << newLine;
  289. return result;
  290. }
  291. StringArray getCPPFlags() const
  292. {
  293. StringArray result;
  294. result.add ("\"-fsigned-char\"");
  295. result.add ("\"-fexceptions\"");
  296. result.add ("\"-frtti\"");
  297. if (isCPP11Enabled())
  298. result.add ("\"-std=gnu++11\"");
  299. // preprocessor definitions
  300. {
  301. StringPairArray preprocessorDefinitions = getAllPreprocessorDefs();
  302. preprocessorDefinitions.set ("JUCE_ANDROID", "1");
  303. preprocessorDefinitions.set ("JUCE_ANDROID_ACTIVITY_CLASSNAME", getJNIActivityClassName().replaceCharacter ('/', '_'));
  304. preprocessorDefinitions.set ("JUCE_ANDROID_ACTIVITY_CLASSPATH", "\\\"" + getActivityClassPath().replaceCharacter('.', '/') + "\\\"");
  305. const StringArray& keys = preprocessorDefinitions.getAllKeys();
  306. for (int i = 0; i < keys.size(); ++i)
  307. result.add (String ("\"-D") + keys[i] + String ("=") + preprocessorDefinitions[keys[i]] + "\"");
  308. }
  309. // include paths
  310. result.add ("\"-I${project.rootDir}/app\".toString()");
  311. result.add ("\"-I${ext.juceRootDir}\".toString()");
  312. result.add ("\"-I${ext.juceModuleDir}\".toString()");
  313. {
  314. Array<RelativePath> cppFiles;
  315. const Array<Project::Item>& groups = getAllGroups();
  316. struct Predicate
  317. {
  318. bool operator() (const Project::Item& projectItem) const { return projectItem.shouldBeAddedToTargetProject(); }
  319. };
  320. for (int i = 0; i < groups.size(); ++i)
  321. findAllProjectItemsWithPredicate (groups.getReference (i), cppFiles, Predicate());
  322. for (int i = 0; i < cppFiles.size(); ++i)
  323. {
  324. const RelativePath absoluteSourceFile (cppFiles.getReference (i).rebased (getTargetFolder(),
  325. project.getProjectFolder(),
  326. RelativePath::projectFolder));
  327. const String absoluteIncludeFolder (sanitisePath (project.getProjectFolder().getFullPathName() + "/"
  328. + absoluteSourceFile.toUnixStyle().upToLastOccurrenceOf ("/", false, false)));
  329. result.addIfNotAlreadyThere ("\"-I" + absoluteIncludeFolder + "\".toString()");
  330. }
  331. }
  332. return result;
  333. }
  334. StringArray getLDLibs() const
  335. {
  336. StringArray result;
  337. result.add ("android");
  338. result.add ("EGL");
  339. result.add ("GLESv2");
  340. result.add ("log");
  341. result.addArray (StringArray::fromTokens(getExternalLibrariesString(), ";", ""));
  342. return result;
  343. }
  344. String createModelDotAndroidNDK (const String& indent) const
  345. {
  346. String result;
  347. result << "android.ndk {" << newLine
  348. << indent << "moduleName = \"juce_jni\"" << newLine
  349. << indent << "stl = \"gnustl_static\"" << newLine
  350. << indent << "toolchainVersion = 4.9" << newLine
  351. << indent << "ext {" << newLine
  352. << indent << indent << "juceRootDir = \"" << "${project.rootDir}/../../../../" << "\".toString()" << newLine
  353. << indent << indent << "juceModuleDir = \"" << "${juceRootDir}/modules" << "\".toString()" << newLine
  354. << indent << "}" << newLine;
  355. // CPP flags
  356. {
  357. StringArray cppFlags (getCPPFlags());
  358. for (int i = 0; i < cppFlags.size(); ++i)
  359. result << indent << "cppFlags += " << cppFlags[i] << newLine;
  360. }
  361. // libraries
  362. {
  363. StringArray libraries (getLDLibs());
  364. result << indent << "ldLibs += [";
  365. for (int i = 0; i < libraries.size(); ++i)
  366. {
  367. result << "\"" << libraries[i] << "\"";
  368. if (i + 1 != libraries.size())
  369. result << ", ";
  370. }
  371. result << "]" << newLine;
  372. }
  373. result << "}" << newLine;
  374. return result;
  375. }
  376. String getGradleCPPFlags (const String& indent, const ConstConfigIterator& config) const
  377. {
  378. String result;
  379. StringArray rootFlags;
  380. StringArray ndkFlags;
  381. if (config->isDebug())
  382. {
  383. ndkFlags.add ("debuggable = true");
  384. ndkFlags.add ("cppFlags += \"-g\"");
  385. ndkFlags.add ("cppFlags += \"-DDEBUG=1\"");
  386. ndkFlags.add ("cppFlags += \"-D_DEBUG=1\"");
  387. }
  388. else
  389. {
  390. rootFlags.add ("minifyEnabled = true");
  391. rootFlags.add ("proguardFiles += 'proguard-android-optimize.txt'");
  392. ndkFlags.add ("cppFlags += \"-DNDEBUG=1\"");
  393. }
  394. {
  395. StringArray extraFlags (StringArray::fromTokens (getExtraCompilerFlagsString(), " ", ""));
  396. for (int i = 0; extraFlags.size(); ++i)
  397. ndkFlags.add (String ("cppFlags += \"") + extraFlags[i] + "\"");
  398. }
  399. // there appears to be an issue with build types that have a name other than
  400. // "debug" or "release". Apparently this is hard coded in Android Studio ...
  401. {
  402. const String configName (config->getName());
  403. if (configName != "Debug" && configName != "Release")
  404. throw SaveError ("Build configurations other than Debug and Release are not yet support for Android Studio");
  405. result << configName.toLowerCase() << " {" << newLine;
  406. }
  407. for (int i = 0; i < rootFlags.size(); ++i)
  408. result << indent << rootFlags[i] << newLine;
  409. result << indent << "ndk.with {" << newLine;
  410. for (int i = 0; i < ndkFlags.size(); ++i)
  411. result << indent << indent << ndkFlags[i] << newLine;
  412. result << indent << "}" << newLine
  413. << "}" << newLine;
  414. return result;
  415. }
  416. String createModelDotAndroidDotBuildTypes (const String& indent) const
  417. {
  418. String result;
  419. result << "android.buildTypes {" << newLine;
  420. for (ConstConfigIterator config (*this); config.next();)
  421. result << CodeHelpers::indent (getGradleCPPFlags (indent, config), indent.length(), true);
  422. result << "}";
  423. return result;
  424. }
  425. String createModelDotAndroidDotProductFlavors (const String& indent) const
  426. {
  427. String result;
  428. result << "android.productFlavors {" << newLine;
  429. // TODO! - this needs to be changed so that it generates seperate flags for debug and release ...
  430. // at present, it just generates all ABIs for all build types
  431. StringArray architectures (StringArray::fromTokens (getABIs<AndroidStudioBuildConfiguration> (true), " ", ""));
  432. architectures.mergeArray (StringArray::fromTokens (getABIs<AndroidStudioBuildConfiguration> (false), " ", ""));
  433. if (architectures.size() == 0)
  434. throw SaveError ("Can't build for no architectures!");
  435. for (int i = 0; i < architectures.size(); ++i)
  436. {
  437. String architecture (architectures[i].trim());
  438. if (architecture.isEmpty())
  439. continue;
  440. result << indent << "create(\"" << architecture << "\") {" << newLine
  441. << indent << indent << "ndk.abiFilters += \"" << architecture << "\"" << newLine
  442. << indent << "}" << newLine;
  443. }
  444. result << "}" << newLine;
  445. return result;
  446. }
  447. void writeBuildDotGradleApp (const File& folder) const
  448. {
  449. MemoryOutputStream memoryOutputStream;
  450. const String indent = getIndentationString();
  451. const String minimumSDKVersion = getMinimumSDKVersionString();
  452. const String bundleIdentifier = project.getBundleIdentifier().toString();
  453. memoryOutputStream << "apply plugin: 'com.android.model.application'" << newLine
  454. << newLine
  455. << "model {" << newLine
  456. << CodeHelpers::indent (createModelDotAndroid (indent, minimumSDKVersion, bundleIdentifier), indent.length(), true)
  457. << newLine
  458. << CodeHelpers::indent (createModelDotCompileOptions (indent), indent.length(), true)
  459. << newLine
  460. << CodeHelpers::indent (createModelDotAndroidSources (indent), indent.length(), true)
  461. << newLine
  462. << CodeHelpers::indent (createModelDotAndroidNDK (indent), indent.length(), true)
  463. << newLine
  464. << CodeHelpers::indent (createModelDotAndroidDotBuildTypes (indent), indent.length(), true)
  465. << newLine
  466. << CodeHelpers::indent (createModelDotAndroidDotProductFlavors (indent), indent.length(), true)
  467. << "}";
  468. overwriteFileIfDifferentOrThrow (folder.getChildFile ("app/build.gradle"), memoryOutputStream);
  469. }
  470. static const char* getIndentationString() noexcept
  471. {
  472. return " ";
  473. }
  474. const File androidStudioExecutable;
  475. JUCE_DECLARE_NON_COPYABLE (AndroidStudioProjectExporter)
  476. };