-
Notifications
You must be signed in to change notification settings - Fork 356
/
Copy pathPlayServicesResolver.cs
2913 lines (2704 loc) · 144 KB
/
PlayServicesResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <copyright file="PlayServicesResolver.cs" company="Google Inc.">
// Copyright (C) 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayServices {
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Google;
using Google.JarResolver;
using UnityEditor;
using UnityEngine;
// Unforunately, SettingsDialog is a public method of this object so collides with
// GooglePlayServices.SettingsDialog when used from this class, so alias this as
// SettingsDialogObj.
using SettingsDialogObj = GooglePlayServices.SettingsDialog;
/// <summary>
/// Play services resolver. This is a background post processor
/// that copies over the Google play services .aar files that
/// plugins have declared as dependencies. If the Unity version is less than
/// 5, aar files are not supported so this class 'explodes' the aar file into
/// a plugin directory. Once the version of Unity is upgraded, the exploded
/// files are removed in favor of the .aar files.
/// </summary>
[InitializeOnLoad]
public class PlayServicesResolver : AssetPostprocessor {
/// <summary>
/// Saves the current state of dependencies in the project and allows the caller to
/// compare the current state vs. the previous state of dependencies in the project.
/// </summary>
internal class DependencyState {
/// <summary>
/// Set of dependencies and the expected files in the project.
/// </summary>
private static string DEPENDENCY_STATE_FILE = Path.Combine(
"ProjectSettings", "AndroidResolverDependencies.xml");
/// <summary>
/// Set of Android packages (AARs / JARs) referenced by this DependencyState.
/// These are in the Maven style format "group:artifact:version".
/// </summary>
public HashSet<string> Packages { get; internal set; }
/// <summary>
/// Set of files referenced by this DependencyState.
/// </summary>
public HashSet<string> Files { get; internal set; }
/// <summary>
/// Settings used to resolve these dependencies.
/// </summary>
public Dictionary<string, string> Settings { get; internal set; }
/// <summary>
/// Determine the current state of the project.
/// </summary>
/// <returns>DependencyState instance with data derived from the current
/// project.</returns>
public static DependencyState GetState() {
return new DependencyState {
Packages = new HashSet<string>(PlayServicesSupport.GetAllDependencies().Keys),
Files = new HashSet<string>(PlayServicesResolver.FindLabeledAssets()),
Settings = PlayServicesResolver.GetResolutionSettings(),
};
}
/// <summary>
/// Sort a string hashset.
/// </summary>
/// <param name="setToSort">Set to sort and return via an enumerable.</param>
private static IEnumerable<string> SortSet(IEnumerable<string> setToSort) {
var sorted = new SortedDictionary<string, bool>();
foreach (var value in setToSort) sorted[value] = true;
return sorted.Keys;
}
/// <summary>
/// Write this object to DEPENDENCY_STATE_FILE.
/// </summary>
public void WriteToFile() {
try {
Directory.CreateDirectory(Path.GetDirectoryName(DEPENDENCY_STATE_FILE));
if (!FileUtils.CheckoutFile(DEPENDENCY_STATE_FILE, logger)) {
logger.Log(String.Format(
"Unable to checkout '{0}'. Resolution results can't be saved, " +
"disabling auto-resolution.", DEPENDENCY_STATE_FILE), LogLevel.Error);
SettingsDialogObj.EnableAutoResolution = false;
return;
}
using (var writer = new XmlTextWriter(new StreamWriter(DEPENDENCY_STATE_FILE)) {
Formatting = Formatting.Indented,
}) {
writer.WriteStartElement("dependencies");
writer.WriteStartElement("packages");
foreach (var dependencyKey in SortSet(Packages)) {
writer.WriteStartElement("package");
writer.WriteValue(dependencyKey);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteStartElement("files");
foreach (var assetPath in SortSet(Files)) {
writer.WriteStartElement("file");
writer.WriteValue(FileUtils.PosixPathSeparators(assetPath));
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteStartElement("settings");
foreach (var settingKey in SortSet(Settings.Keys)) {
writer.WriteStartElement("setting");
writer.WriteAttributeString("name", settingKey);
writer.WriteAttributeString("value", Settings[settingKey]);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
writer.Close();
}
} catch (Exception e) {
Log(String.Format(
"Unable to update dependency file {0} ({1})\n" +
"If auto-resolution is enabled, it is likely to be retriggered " +
"when any operation triggers resolution.", DEPENDENCY_STATE_FILE, e),
level: LogLevel.Warning);
}
}
/// <summary>
/// Read the state from DEPENDENCY_STATE_FILE.
/// </summary>
/// <returns>DependencyState instance read from DEPENDENCY_STATE_FILE. null is
/// returned if the file isn't found.</returns>
///
/// This parses files in the following format:
/// <dependencies>
/// <packages>
/// <package>group:artifact:version</package>
/// ...
/// </packages>
/// <files>
/// <file>package_filename</file>
/// ...
/// </files>
/// </dependencies>
public static DependencyState ReadFromFile() {
var packages = new HashSet<string>();
var files = new HashSet<string>();
var settings = new Dictionary<string, string>();
if (!XmlUtilities.ParseXmlTextFileElements(
DEPENDENCY_STATE_FILE, logger,
(reader, elementName, isStart, parentElementName, elementNameStack) => {
if (isStart) {
if (elementName == "dependencies" && parentElementName == "") {
return true;
} else if ((elementName == "packages" || elementName == "files" ||
elementName == "settings") &&
parentElementName == "dependencies") {
return true;
} else if (elementName == "package" &&
parentElementName == "packages") {
if (isStart && reader.Read() &&
reader.NodeType == XmlNodeType.Text) {
packages.Add(reader.ReadContentAsString());
}
return true;
} else if (elementName == "file" && parentElementName == "files") {
if (isStart && reader.Read() &&
reader.NodeType == XmlNodeType.Text) {
files.Add(reader.ReadContentAsString());
}
return true;
} else if (elementName == "setting" &&
parentElementName == "settings") {
if (isStart) {
string name = reader.GetAttribute("name");
string value = reader.GetAttribute("value");
if (!String.IsNullOrEmpty(name) &&
!String.IsNullOrEmpty(value)) {
settings[name] = value;
}
}
return true;
}
}
return true;
})) {
return null;
}
return new DependencyState() {
Packages = packages,
Files = files,
Settings = settings
};
}
/// <summary>
/// Compare with this object.
/// </summary>
/// <param name="obj">Object to compare with.</param>
/// <returns>true if both objects have the same contents, false otherwise.</returns>
public override bool Equals(System.Object obj) {
var state = obj as DependencyState;
bool settingsTheSame = state != null && Settings.Count == state.Settings.Count;
if (settingsTheSame) {
foreach (var kv in Settings) {
string value;
settingsTheSame = state.Settings.TryGetValue(kv.Key, out value) &&
value == kv.Value;
if (!settingsTheSame) break;
}
}
return settingsTheSame && Packages.SetEquals(state.Packages) &&
Files.SetEquals(state.Files);
}
/// <summary>
/// Generate a hash of this object.
/// </summary>
/// <returns>Hash of this object.</returns>
public override int GetHashCode() {
int hash = 0;
foreach (var file in Files) {
hash ^= file.GetHashCode();
}
foreach (var pkg in Packages) {
hash ^= pkg.GetHashCode();
}
foreach (var setting in Settings.Values) {
hash ^= setting.GetHashCode();
}
return hash;
}
/// <summary>
/// Convert a hashset to a sorted comma separated string.
/// </summary>
/// <returns>Comma separated string.</returns>
private static string SetToString(HashSet<string> setToConvert) {
return String.Join(", ", (new List<string>(SortSet(setToConvert))).ToArray());
}
/// <summary>
/// Convert a dictionary to a sorted comma separated string.
/// </summary>
/// <returns>Comma separated string in the form key=value.</returns>
private static string DictionaryToString(Dictionary<string, string> dict) {
var components = new List<string>();
foreach (var key in SortSet(dict.Keys)) {
components.Add(String.Format("{0}={1}", key, dict[key]));
}
return String.Join(", ", components.ToArray());
}
/// <summary>
/// Display dependencies as a string.
/// </summary>
/// <returns>Human readable string.</returns>
public override string ToString() {
return String.Format("packages=({0}), files=({1}) settings=({2})",
SetToString(Packages), SetToString(Files),
DictionaryToString(Settings));
}
}
/// <summary>
/// Polls a value and signals a callback with the change after the specified delay
/// time.
/// </summary>
internal class PropertyPoller<T> {
/// <summary>
/// Delegate that is called when a value changes.
/// </summary>
/// <param name="previousValue">Previous value of the property that
/// changed.</param>
/// <param name="currentValue">Current value of the property that
/// changed.</param>
public delegate void Changed(T previousValue, T currentValue);
// Whether the previous value has been initialized.
private bool previousValueInitialized = false;
// Previous value of the property.
private T previousValue = default(T);
// Previous value of the property when it was last polled.
private T previousPollValue = default(T);
// Last time the property was polled.
private DateTime previousPollTime = DateTime.Now;
// Time to wait before signalling a change.
private int delayTimeInSeconds;
// Name of the property being polled.
private string propertyName;
// Previous time we checked the property value for a change.
private DateTime previousCheckTime = DateTime.Now;
// Time to wait before checking a property.
private int checkIntervalInSeconds;
/// <summary>
/// Create the poller.
/// </summary>
/// <param name="propertyName">Name of the property being polled.</param>
/// <param name="delayTimeInSeconds">Time to wait before signalling that the value
/// has changed.</param>
/// <param name="checkIntervalInSeconds">Time to check the value of the property for
/// changes.</param>
public PropertyPoller(string propertyName,
int delayTimeInSeconds = 3,
int checkIntervalInSeconds = 1) {
this.propertyName = propertyName;
this.delayTimeInSeconds = delayTimeInSeconds;
this.checkIntervalInSeconds = checkIntervalInSeconds;
}
/// <summary>
/// Poll the specified value for changes.
/// </summary>
/// <param name="getCurrentValue">Delegate that returns the value being polled.</param>
/// <param name="changed">Delegate that is called if the value changes.</param>
public void Poll(Func<T> getCurrentValue, Changed changed) {
var currentTime = DateTime.Now;
if (currentTime.Subtract(previousCheckTime).TotalSeconds <
checkIntervalInSeconds) {
return;
}
previousCheckTime = currentTime;
T currentValue = getCurrentValue();
// If the poller isn't initailized, store the current value before polling for
// changes.
if (!previousValueInitialized) {
previousValueInitialized = true;
previousValue = currentValue;
return;
}
if (!currentValue.Equals(previousValue)) {
if (currentValue.Equals(previousPollValue)) {
if (currentTime.Subtract(previousPollTime).TotalSeconds >=
delayTimeInSeconds) {
Log(String.Format("{0} changed: {1} -> {2}", propertyName,
previousValue, currentValue),
level: LogLevel.Verbose);
changed(previousValue, currentValue);
previousValue = currentValue;
}
} else {
previousPollValue = currentValue;
previousPollTime = currentTime;
}
}
}
}
/// <summary>
/// Namespace for embedded resources packaged from the PlayServicesResolver/scripts
/// directory.
/// </summary>
internal const string EMBEDDED_RESOURCES_NAMESPACE = "PlayServicesResolver.scripts.";
// Silence the unused variable warning, as this holds a reference to the
// PlayServicesSupport singleton.
#pragma warning disable 414
/// <summary>
/// The instance to the play services support object.
/// </summary>
private static PlayServicesSupport svcSupport;
#pragma warning restore 414
/// <summary>
/// Resolver that uses Gradle to download libraries and embed them within a Unity project.
/// Lazy initialize it only when current build target is Android.
/// </summary>
private static GradleResolver GradleResolverInstance {
get {
if (gradleResolverInstance == null &&
EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android) {
gradleResolverInstance = new GradleResolver();
}
return gradleResolverInstance;
}
}
/// <summary>
/// Instance of GradleResolver.
/// </summary>
private static GradleResolver gradleResolverInstance = null;
/// <summary>
/// Resoluton job.
/// This class is used to enqueue a resolution job to execute on the main thread by
/// ScheduleResolve().
/// It keeps track of whether the job was started via auto-resolution or explicitly.
/// If the job was started via auto-resolution it is removed from the currently scheduled
/// set of jobs when a new job is started via ScheduleResolve().
/// </summary>
private class ResolutionJob {
/// <summary>
/// Whether this is an auto-resolution job,
/// </summary>
public bool IsAutoResolveJob { get; private set; }
/// <summary>
/// Action to execute to resolve.
/// </summary>
public Action Job { get; private set; }
/// <summary>
/// Initialize this instance.
/// </summary>
/// <param name="isAutoResolveJob">Whether this is an auto-resolution job.</param>
/// <param name="job">Action to execute to resolve.</param>
public ResolutionJob(bool isAutoResolveJob, Action job) {
IsAutoResolveJob = isAutoResolveJob;
Job = job;
}
}
/// <summary>
/// Queue of resolution jobs to execute.
/// </summary>
private static List<ResolutionJob> resolutionJobs = new List<ResolutionJob>();
/// <summary>
/// Flag used to prevent re-entrant auto-resolution.
/// </summary>
private static bool autoResolving = false;
/// <summary>
/// ID of the job that executes AutoResolve.
/// </summary>
private static int autoResolveJobId = 0;
/// <summary>
/// Polls for changes in the bundle ID.
/// </summary>
private static PropertyPoller<string> bundleIdPoller =
new PropertyPoller<string>("Bundle ID");
/// <summary>
/// Arguments for the bundle ID update event.
/// </summary>
public class BundleIdChangedEventArgs : EventArgs {
/// <summary>
/// Current project Bundle ID.
/// </summary>
public string BundleId { get; set; }
/// <summary>
/// Bundle ID when this event was last fired.
/// </summary>
public string PreviousBundleId { get; set; }
}
/// <summary>
/// Event which is fired when the bundle ID is updated.
/// </summary>
public static event EventHandler<BundleIdChangedEventArgs> BundleIdChanged;
/// <summary>
/// Asset label applied to files managed by this plugin.
/// </summary>
internal const string ManagedAssetLabel = "gpsr";
/// <summary>
/// Get a boolean property from UnityEditor.EditorUserBuildSettings.
/// </summary>
/// Properties are introduced over successive versions of Unity so use reflection to
/// retrieve them.
private static object GetEditorUserBuildSettingsProperty(string name,
object defaultValue) {
var editorUserBuildSettingsType = typeof(UnityEditor.EditorUserBuildSettings);
var property = editorUserBuildSettingsType.GetProperty(name);
if (property != null) {
var value = property.GetValue(null, null);
if (value != null) return value;
}
return defaultValue;
}
/// <summary>
/// Whether the Gradle build system is enabled.
/// </summary>
public static bool GradleBuildEnabled {
get {
return GetEditorUserBuildSettingsProperty(
"androidBuildSystem", "").ToString().Equals("Gradle");
}
}
/// <summary>
/// Whether the Gradle template is enabled.
/// </summary>
public static bool GradleTemplateEnabled {
get {
return GradleBuildEnabled && File.Exists(GradleTemplateResolver.GradleTemplatePath);
}
}
/// <summary>
/// Whether the Gradle Properties template is enabled. (Unity 2019.3 and above)
/// </summary>
public static bool GradlePropertiesTemplateEnabled {
get {
return GradleBuildEnabled &&
File.Exists(GradleTemplateResolver.GradlePropertiesTemplatePath);
}
}
/// <summary>
/// Whether the Gradle Settings template is enabled.
/// </summary>
public static bool GradleSettingsTemplateEnabled {
get {
return GradleBuildEnabled &&
File.Exists(GradleTemplateResolver.GradleSettingsTemplatePath);
}
}
// Backing store for GradleVersion property.
private static string gradleVersion = null;
// Extracts a version number from a gradle distribution jar file.
private static Regex gradleJarVersionExtract = new Regex(@"^gradle-core-([0-9.]+)\.jar$");
/// <summary>
/// Get / set the Gradle version.
/// This property is populated when it's first read by parsing the version number of the
/// gradle-core-*.jar in the AndroidPlayer directory.
/// </summary>
public static string GradleVersion {
set { gradleVersion = value; }
get {
if (!String.IsNullOrEmpty(gradleVersion)) return gradleVersion;
string gradleLibDir = null;
// Unity 2019.3 added AndroidExternalToolsSettings which contains the Gradle path
// so try to use that first.
var gradleDir = UnityCompat.AndroidExternalToolsSettingsGradlePath;
if (Directory.Exists(gradleDir)) gradleLibDir = Path.Combine(gradleDir, "lib");
// Fallback to searching for gradle redistributed with Unity in the Android plugin.
if (String.IsNullOrEmpty(gradleDir)) {
var engineDir = AndroidPlaybackEngineDirectory;
if (String.IsNullOrEmpty(engineDir)) return null;
gradleLibDir = Path.Combine(Path.Combine(Path.Combine(engineDir, "Tools"),
"gradle"), "lib");
}
if (!String.IsNullOrEmpty(gradleLibDir) && Directory.Exists(gradleLibDir)) {
foreach (var path in Directory.GetFiles(gradleLibDir, "gradle-core-*.jar",
SearchOption.TopDirectoryOnly)) {
var match = gradleJarVersionExtract.Match(Path.GetFileName(path));
if (match != null && match.Success) {
gradleVersion = match.Result("$1");
break;
}
}
}
return gradleVersion;
}
}
// Backing store for the AndroidGradlePluginVersion property.
private static string androidGradlePluginVersion = null;
// Modification time of mainTemplate.gradle the last time it was searched for the Android
// Gradle plugin version.
private static DateTime mainTemplateLastWriteTime = default(DateTime);
// Extracts an Android Gradle Plugin version number from the contents of a *.gradle file.
// This should work for Unity 2022.1 and below.
// Ex.
// classpath 'com.android.tools.build:gradle:4.0.1'
private static Regex androidGradlePluginVersionExtract_legacy = new Regex(
@"['""]com\.android\.tools\.build:gradle:([^'""]+)['""]$");
// Extracts an Android Gradle Plugin version number from the contents of a *.gradle file for
// Unity 2022.2+ or 2023.1+.
// Ex.
// id 'com.android.application' version '7.1.2' apply false
private static Regex androidGradlePluginVersionExtract = new Regex(
@"['""]com\.android\.application['""] version ['""]([^'""]+)['""]");
/// <summary>
/// Get the Android Gradle Plugin version used by Unity.
/// </summary>
public static string AndroidGradlePluginVersion {
set {
androidGradlePluginVersion = value;
mainTemplateLastWriteTime = DateTime.Now;
}
get {
// If the gradle template changed, read the plugin version again.
var mainTemplateGradlePath = GradleTemplateResolver.GradleTemplatePath;
if (File.Exists(mainTemplateGradlePath)) {
var lastWriteTime = File.GetLastWriteTime(mainTemplateGradlePath);
if (lastWriteTime.CompareTo(mainTemplateLastWriteTime) > 0) {
androidGradlePluginVersion = null;
}
}
// If the plugin version is cached, return it.
if (!String.IsNullOrEmpty(androidGradlePluginVersion)) {
return androidGradlePluginVersion;
}
// Search the gradle templates for the plugin version.
var gradleTemplateDir = GradleTemplateResolver.UnityGradleTemplatesDir;
if (Directory.Exists(gradleTemplateDir)) {
var gradleTemplates = new List<string>();
if (File.Exists(mainTemplateGradlePath)) {
gradleTemplates.Add(mainTemplateGradlePath);
}
gradleTemplates.AddRange(Directory.GetFiles(gradleTemplateDir, "*.gradle",
SearchOption.TopDirectoryOnly));
foreach (var path in gradleTemplates) {
foreach (var line in File.ReadAllLines(path)) {
var match = androidGradlePluginVersionExtract_legacy.Match(line);
if (match != null && match.Success) {
androidGradlePluginVersion = match.Result("$1");
break;
}
match = androidGradlePluginVersionExtract.Match(line);
if (match != null && match.Success) {
androidGradlePluginVersion = match.Result("$1");
break;
}
}
if (!String.IsNullOrEmpty(androidGradlePluginVersion)) break;
}
}
Log(String.Format("Detected Android Gradle Plugin Version {0}.",
androidGradlePluginVersion),
level: LogLevel.Verbose);
return androidGradlePluginVersion;
}
}
/// <summary>
/// Whether project export is enabled.
/// </summary>
public static bool ProjectExportEnabled {
get {
var value = GetEditorUserBuildSettingsProperty("exportAsGoogleAndroidProject",
null);
return value == null ? false : (bool) value;
}
}
/// <summary>
/// If Gradle project export is enabled.
/// </summary>
public static bool GradleProjectExportEnabled {
get {
return PlayServicesResolver.GradleBuildEnabled &&
PlayServicesResolver.ProjectExportEnabled;
}
}
/// <summary>
/// Current build system settings.
/// </summary>
private struct AndroidBuildSystemSettings {
/// <summary>
/// Whether the Gradle build is enabled.
/// </summary>
public bool GradleBuildEnabled { get; private set; }
/// <summary>
/// Whether the Gradle template is enabled.
/// </summary>
public bool GradleTemplateEnabled { get; private set; }
/// <summary>
/// Whether the Gradle properties template is enabled.
/// </summary>
public bool GradlePropertiesTemplateEnabled { get; private set; }
/// <summary>
// Whether project export is enabled.
/// </summary>
public bool ProjectExportEnabled { get; private set; }
/// <summary>
/// Get the current build settings.
/// </summary>
public static AndroidBuildSystemSettings Current {
get {
return new AndroidBuildSystemSettings {
GradleBuildEnabled = PlayServicesResolver.GradleBuildEnabled,
GradleTemplateEnabled = PlayServicesResolver.GradleTemplateEnabled,
GradlePropertiesTemplateEnabled = PlayServicesResolver.GradlePropertiesTemplateEnabled,
ProjectExportEnabled = PlayServicesResolver.ProjectExportEnabled
};
}
}
/// <summary>
/// Compare with another AndroidBuildSystemSettings.
/// </summary>
/// <param name="obj">Object to compare with.</param>
/// <returns>true if the object is the same as this, false otherwise.</returns>
public override bool Equals(System.Object obj) {
var other = (AndroidBuildSystemSettings)obj;
return other.GradleBuildEnabled == GradleBuildEnabled &&
other.GradleTemplateEnabled == GradleTemplateEnabled &&
other.GradlePropertiesTemplateEnabled == GradlePropertiesTemplateEnabled &&
other.ProjectExportEnabled == ProjectExportEnabled;
}
/// <summary>
/// Generate a hash of this object.
/// </summary>
/// <returns>Hash of this object.</returns>
public override int GetHashCode() {
return GradleBuildEnabled.GetHashCode() ^ GradleTemplateEnabled.GetHashCode() ^
GradlePropertiesTemplateEnabled.GetHashCode() ^
ProjectExportEnabled.GetHashCode();
}
/// <summary>
/// Convert this object to a string.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString() {
return String.Format("[GradleBuildEnabled={0} GradleTemplateEnabled={1} " +
"GradlePropertiesTemplateEnabled={2} ProjectExportEnabled={2}]",
GradleBuildEnabled, GradleTemplateEnabled,
GradlePropertiesTemplateEnabled, ProjectExportEnabled);
}
}
/// <summary>
/// Polls for changes in build system settings.
/// </summary>
private static PropertyPoller<AndroidBuildSystemSettings> androidBuildSystemPoller =
new PropertyPoller<AndroidBuildSystemSettings>("Android Build Settings");
/// <summary>
/// Arguments for the Android build system changed event.
/// </summary>
public class AndroidBuildSystemChangedArgs : EventArgs {
/// <summary>
/// Gradle was selected as the build system when this event was fired.
/// </summary>
public bool GradleBuildEnabled { get; set; }
/// <summary>
/// Whether Gradle was selected as the build system the last time this event was fired.
/// </summary>
public bool PreviousGradleBuildEnabled { get; set; }
/// <summary>
/// Whether a custom Gradle template is enabled.
/// This will only be true if GradleBuildEnabled is also true.
/// </summary>
public bool GradleTemplateEnabled { get; set; }
/// <summary>
/// Whether a custom Gradle template was enabled the last time this event was fired.
/// </summary>
public bool PreviousGradleTemplateEnabled { get; set; }
/// <summary>
/// Project export was selected when this event was fired.
/// </summary>
/// <summary>
/// Whether a custom Gradle Properties template is enabled.
/// This will only be true if GradleBuildEnabled is also true.
/// </summary>
public bool GradlePropertiesTemplateEnabled { get; set; }
/// <summary>
/// Whether a custom Gradle Properties Template
/// was enabled the last time this event was fired.
/// </summary>
public bool PreviousGradlePropertiesTemplateEnabled { get; set; }
/// <summary>
/// Project export was selected when this event was fired.
/// </summary>
public bool ProjectExportEnabled { get; set; }
/// <summary>
/// Whether project export was selected when this event was fired.
/// </summary>
public bool PreviousProjectExportEnabled { get; set; }
}
/// <summary>
/// Event which is fired when the Android build system changes.
/// </summary>
public static event EventHandler<AndroidBuildSystemChangedArgs> AndroidBuildSystemChanged;
/// <summary>
/// Polls for changes in the Android device ABI.
/// </summary>
private static PropertyPoller<AndroidAbis> androidAbisPoller =
new PropertyPoller<AndroidAbis>("Android Target Device ABI");
/// <summary>
/// Logger for this module.
/// </summary>
internal static Google.Logger logger = new Google.Logger();
// Analytics reporter.
internal static EditorMeasurement analytics = new EditorMeasurement(
GooglePlayServices.SettingsDialog.projectSettings, logger,
VersionHandlerImpl.GA_TRACKING_ID, VersionHandlerImpl.MEASUREMENT_ID,
VersionHandlerImpl.PLUGIN_SUITE_NAME, "", VersionHandlerImpl.PRIVACY_POLICY) {
BasePath = "/androidresolver/",
BaseQuery = String.Format("version={0}", AndroidResolverVersionNumber.Value.ToString()),
BaseReportName = "Android Resolver: ",
InstallSourceFilename =
System.Reflection.Assembly.GetAssembly(typeof(PlayServicesResolver)).Location,
DataUsageUrl = VersionHandlerImpl.DATA_USAGE_URL
};
/// <summary>
/// Arguments for the Android build system changed event.
/// </summary>
public class AndroidAbisChangedArgs : EventArgs {
/// <summary>
/// Target device ABI before it changed.
/// </summary>
public string PreviousAndroidAbis { get; set; }
/// <summary>
/// Target device ABI when this event was fired.
/// </summary>
public string AndroidAbis { get; set; }
}
/// <summary>
/// Event which is fired when the Android target device ABI changes.
/// </summary>
public static event EventHandler<AndroidAbisChangedArgs> AndroidAbisChanged;
// Parses dependencies from XML dependency files.
private static AndroidXmlDependencies xmlDependencies = new AndroidXmlDependencies();
// Last error logged by LogDelegate().
private static string lastError = null;
/// <summary>
/// Get the Android SDK directory.
/// </summary>
public static string AndroidSdkRoot {
get {
string sdkPath = null;
// Unity 2019.3 added AndroidExternalToolsSettings which contains the Android SDK
// path so try to use that first.
var androidSdkRootPath = UnityCompat.AndroidExternalToolsSettingsSdkRootPath;
if (!String.IsNullOrEmpty(androidSdkRootPath)) {
if (Directory.Exists(androidSdkRootPath)) sdkPath = androidSdkRootPath;
}
// Unity 2019.x added installation of the Android SDK in the AndroidPlayer directory
// so fallback to searching for it there.
if (String.IsNullOrEmpty(sdkPath) || EditorPrefs.GetBool("SdkUseEmbedded")) {
var androidPlayerDir = AndroidPlaybackEngineDirectory;
if (!String.IsNullOrEmpty(androidPlayerDir)) {
var androidPlayerSdkDir = Path.Combine(androidPlayerDir, "SDK");
if (Directory.Exists(androidPlayerSdkDir)) sdkPath = androidPlayerSdkDir;
}
}
// Pre Unity 2019 Android SDK path.
if (String.IsNullOrEmpty(sdkPath)) {
sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
}
return sdkPath;
}
}
/// <summary>
/// Polls for changes in AndroidSdkRoot.
/// </summary>
private static PropertyPoller<string> androidSdkRootPoller =
new PropertyPoller<string>("Android SDK Path");
/// <summary>
/// Arguments for the AndroidSdkRootChanged event.
/// </summary>
public class AndroidSdkRootChangedArgs : EventArgs {
/// <summary>
/// AndroidSdkRoot before it changed.
/// </summary>
public string PreviousAndroidSdkRoot { get; set; }
/// <summary>
/// AndroidSdkRoot when this event was fired.
/// </summary>
public string AndroidSdkRoot { get; set; }
}
/// <summary>
/// Event which is fired when the Android SDK root changes.
/// </summary>
public static event EventHandler<AndroidSdkRootChangedArgs> AndroidSdkRootChanged;
// Backing store to cache AndroidPlaybackEngineDirectory.
// This is set to either null (Android player not installed) or the path of the
// playback engine directory when AndroidPlaybackEngineDirectory is first accessed.
private static string androidPlaybackEngineDirectory = "";
/// <summary>
/// Get the Android playback engine directory.
/// </summary>
/// <returns>Get the playback engine directory.</returns>
public static string AndroidPlaybackEngineDirectory {
get {
if (androidPlaybackEngineDirectory != null &&
androidPlaybackEngineDirectory == "") {
try {
androidPlaybackEngineDirectory =
(string)VersionHandler.InvokeStaticMethod(
typeof(BuildPipeline), "GetPlaybackEngineDirectory",
new object[] { BuildTarget.Android, BuildOptions.None });
} catch (Exception) {
androidPlaybackEngineDirectory = null;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
if (assembly.GetName().Name == "UnityEditor.Android.Extensions") {
androidPlaybackEngineDirectory =
Path.GetDirectoryName(assembly.Location);
break;
}
}
}
}
return androidPlaybackEngineDirectory;
}
}
// Backing store for the GradleWrapper property.
private static GradleWrapper gradleWrapper = new GradleWrapper(
typeof(PlayServicesResolver).Assembly,
PlayServicesResolver.EMBEDDED_RESOURCES_NAMESPACE + "gradle-template.zip",
Path.Combine(FileUtils.ProjectTemporaryDirectory, "PlayServicesResolverGradle"));
/// <summary>
/// Class to interface with the embedded Gradle wrapper.
/// </summary>
internal static GradleWrapper Gradle { get { return gradleWrapper; } }
/// <summary>
/// Returns true if automatic resolution is enabled.
/// Auto-resolution is never enabled in batch mode. Each build setting change must be
/// manually followed by DoResolution().
/// </summary>
public static bool AutomaticResolutionEnabled {
get {
return SettingsDialogObj.EnableAutoResolution &&
!ExecutionEnvironment.InBatchMode;
}
}
/// <summary>
/// Initializes the <see cref="GooglePlayServices.PlayServicesResolver"/> class.
/// </summary>
static PlayServicesResolver() {
// Delay initialization until the build target is Android and the editor is not in play
// mode.
EditorInitializer.InitializeOnMainThread(condition: () => {
return EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android &&
!EditorApplication.isPlayingOrWillChangePlaymode;
}, initializer: Initialize, name: "PlayServicesResolver", logger: logger);
}
/// <summary>
/// Initialize the module. This should be called on the main thread only if
/// current active build target is Android and not in play mode.
/// </summary>
private static bool Initialize() {
if ( EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android ) {
throw new Exception("PlayServiceResolver.Initialize() is called when active " +
"build target is not Android. This should never happen. If it does, " +
"please report to the developer.");
}
// Monitor Android dependency XML files to perform auto-resolution.
AddAutoResolutionFilePatterns(xmlDependencies.fileRegularExpressions);
svcSupport = PlayServicesSupport.CreateInstance(
"PlayServicesResolver",
AndroidSdkRoot,