-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
BaseProcessorUnit.kt
477 lines (411 loc) · 22.4 KB
/
BaseProcessorUnit.kt
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
package permissions.dispatcher.processor.impl
import com.squareup.javapoet.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.processor.ProcessorUnit
import permissions.dispatcher.processor.RequestCodeProvider
import permissions.dispatcher.processor.RuntimePermissionsElement
import permissions.dispatcher.processor.impl.helper.SystemAlertWindowHelper
import permissions.dispatcher.processor.impl.helper.WriteSettingsHelper
import permissions.dispatcher.processor.util.*
import java.util.*
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
/**
* Base class for ProcessorUnit implementations.
* <p>
* This generates the parts of code independent from specific permission method signatures for different target objects.
*/
abstract class BaseProcessorUnit : ProcessorUnit {
protected val PERMISSION_UTILS = ClassName.get("permissions.dispatcher", "PermissionUtils")
private val BUILD = ClassName.get("android.os", "Build")
private val MANIFEST_WRITE_SETTING = "android.permission.WRITE_SETTINGS"
private val MANIFEST_SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW"
private val ADD_WITH_CHECK_BODY_MAP = hashMapOf(MANIFEST_SYSTEM_ALERT_WINDOW to SystemAlertWindowHelper(), MANIFEST_WRITE_SETTING to WriteSettingsHelper())
/**
* Creates the JavaFile for the provided @RuntimePermissions element.
* <p>
* This will delegate to other methods that compose generated code.
*/
override final fun createJavaFile(rpe: RuntimePermissionsElement, requestCodeProvider: RequestCodeProvider): JavaFile {
// Check the prerequisites for creating a Java file for this element
checkPrerequisites(rpe)
return JavaFile.builder(rpe.packageName, createTypeSpec(rpe, requestCodeProvider))
.addFileComment(FILE_COMMENT)
.build()
}
/* Begin abstract */
abstract fun checkPrerequisites(rpe: RuntimePermissionsElement)
abstract fun addRequestPermissionsStatement(builder: MethodSpec.Builder, targetParam: String, permissionField: String, requestCodeField: String)
abstract fun addShouldShowRequestPermissionRationaleCondition(builder: MethodSpec.Builder, targetParam: String, permissionField: String, isPositiveCondition: Boolean = true)
abstract fun getActivityName(targetParam: String): String
/* Begin private */
private fun createTypeSpec(rpe: RuntimePermissionsElement, requestCodeProvider: RequestCodeProvider): TypeSpec {
return TypeSpec.classBuilder(rpe.generatedClassName)
.addModifiers(Modifier.FINAL)
.addFields(createFields(rpe.needsElements, requestCodeProvider))
.addMethod(createConstructor())
.addMethods(createWithCheckMethods(rpe))
.addMethods(createPermissionHandlingMethods(rpe))
.addTypes(createPermissionRequestClasses(rpe))
.build()
}
private fun createFields(needsElements: List<ExecutableElement>, requestCodeProvider: RequestCodeProvider): List<FieldSpec> {
val fields: ArrayList<FieldSpec> = arrayListOf()
needsElements.forEach {
// For each method annotated with @NeedsPermission, add REQUEST integer and PERMISSION String[] fields
fields.add(createRequestCodeField(it, requestCodeProvider.nextRequestCode()))
fields.add(createPermissionField(it))
if (it.parameters.isNotEmpty()) {
fields.add(createPendingRequestField(it))
}
}
return fields
}
private fun createRequestCodeField(e: ExecutableElement, index: Int): FieldSpec {
return FieldSpec.builder(Int::class.java, requestCodeFieldName(e))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("\$L", index)
.build()
}
private fun createPermissionField(e: ExecutableElement): FieldSpec {
val permissionValue: List<String> = e.getAnnotation(NeedsPermission::class.java).permissionValue()
val formattedValue: String = permissionValue.joinToString(
separator = ",",
prefix = "{",
postfix = "}",
transform = { "\"$it\"" }
)
return FieldSpec.builder(ArrayTypeName.of(String::class.java), permissionFieldName(e))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("\$N", "new String[] $formattedValue")
.build()
}
private fun createPendingRequestField(e: ExecutableElement): FieldSpec {
return FieldSpec.builder(ClassName.get("permissions.dispatcher", "GrantableRequest"), pendingRequestFieldName(e))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.build()
}
private fun createConstructor(): MethodSpec {
return MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.build()
}
private fun createWithCheckMethods(rpe: RuntimePermissionsElement): List<MethodSpec> {
val methods: ArrayList<MethodSpec> = arrayListOf()
rpe.needsElements.forEach {
// For each @NeedsPermission method, create the "WithCheck" equivalent
methods.add(createWithCheckMethod(rpe, it))
}
return methods
}
private fun createWithCheckMethod(rpe: RuntimePermissionsElement, method: ExecutableElement): MethodSpec {
val targetParam = "target"
val builder = MethodSpec.methodBuilder(withCheckMethodName(method))
.addTypeVariables(rpe.typeVariables)
.addModifiers(Modifier.STATIC)
.returns(TypeName.VOID)
.addParameter(rpe.typeName, targetParam)
// If the method has parameters, add those as well
method.parameters.forEach {
builder.addParameter(typeNameOf(it), it.simpleString())
}
// Delegate method body generation to implementing classes
addWithCheckBody(builder, method, rpe, targetParam)
return builder.build()
}
fun addWithCheckBody(builder: MethodSpec.Builder, needsMethod: ExecutableElement, rpe: RuntimePermissionsElement, targetParam: String) {
// Create field names for the constants to use
val requestCodeField = requestCodeFieldName(needsMethod)
val permissionField = permissionFieldName(needsMethod)
// if maxSdkVersion is lower than os level does nothing
val needsPermissionMaxSdkVersion = needsMethod.getAnnotation(NeedsPermission::class.java).maxSdkVersion
if (needsPermissionMaxSdkVersion > 0) {
builder.beginControlFlow("if (\$T.VERSION.SDK_INT > \$L)", BUILD, needsPermissionMaxSdkVersion)
.addCode(CodeBlock.builder()
.add("\$N.\$N(", targetParam, needsMethod.simpleString())
.add(varargsParametersCodeBlock(needsMethod))
.addStatement(")")
.addStatement("return")
.build())
.endControlFlow()
}
// Add the conditional for when permission has already been granted
val needsPermissionParameter = needsMethod.getAnnotation(NeedsPermission::class.java).value[0]
val activityVar = getActivityName(targetParam)
ADD_WITH_CHECK_BODY_MAP[needsPermissionParameter]?.addHasSelfPermissionsCondition(builder, activityVar, permissionField) ?: builder.beginControlFlow("if (\$T.hasSelfPermissions(\$N, \$N))", PERMISSION_UTILS, activityVar, permissionField)
builder.addCode(CodeBlock.builder()
.add("\$N.\$N(", targetParam, needsMethod.simpleString())
.add(varargsParametersCodeBlock(needsMethod))
.addStatement(")")
.build()
)
builder.nextControlFlow("else")
// Add the conditional for "OnShowRationale", if present
val onRationale: ExecutableElement? = rpe.findOnRationaleForNeeds(needsMethod)
val hasParameters: Boolean = needsMethod.parameters.isNotEmpty()
if (hasParameters) {
// If the method has parameters, precede the potential OnRationale call with
// an instantiation of the temporary Request object
val varargsCall = CodeBlock.builder()
.add("\$N = new \$N(\$N, ",
pendingRequestFieldName(needsMethod),
permissionRequestTypeName(needsMethod),
targetParam
)
.add(varargsParametersCodeBlock(needsMethod))
.addStatement(")")
builder.addCode(varargsCall.build())
}
if (onRationale != null) {
addShouldShowRequestPermissionRationaleCondition(builder, targetParam, permissionField)
if (hasParameters) {
// For methods with parameters, use the PermissionRequest instantiated above
builder.addStatement("\$N.\$N(\$N)", targetParam, onRationale.simpleString(), pendingRequestFieldName(needsMethod))
} else {
// Otherwise, create a new PermissionRequest on-the-fly
builder.addStatement("\$N.\$N(new \$N(\$N))", targetParam, onRationale.simpleString(), permissionRequestTypeName(needsMethod), targetParam)
}
builder.nextControlFlow("else")
}
// Add the branch for "request permission"
ADD_WITH_CHECK_BODY_MAP[needsPermissionParameter]?.addRequestPermissionsStatement(builder, activityVar, requestCodeField) ?: addRequestPermissionsStatement(builder, targetParam, permissionField, requestCodeField)
if (onRationale != null) {
builder.endControlFlow()
}
builder.endControlFlow()
}
private fun createPermissionHandlingMethods(rpe: RuntimePermissionsElement): List<MethodSpec> {
val methods: ArrayList<MethodSpec> = arrayListOf()
if (hasNormalPermission(rpe)) {
methods.add(createPermissionResultMethod(rpe))
}
if (hasSystemAlertWindowPermission(rpe) || hasWriteSettingPermission(rpe)) {
methods.add(createOnActivityResultMethod(rpe))
}
return methods
}
private fun createOnActivityResultMethod(rpe: RuntimePermissionsElement): MethodSpec {
val targetParam = "target"
val requestCodeParam = "requestCode"
val grantResultsParam = "grantResults"
val builder = MethodSpec.methodBuilder("onActivityResult")
.addTypeVariables(rpe.typeVariables)
.addModifiers(Modifier.STATIC)
.returns(TypeName.VOID)
.addParameter(rpe.typeName, targetParam)
.addParameter(TypeName.INT, requestCodeParam)
builder.beginControlFlow("switch (\$N)", requestCodeParam)
for (needsMethod in rpe.needsElements) {
val needsPermissionParameter = needsMethod.getAnnotation(NeedsPermission::class.java).value[0]
if (!ADD_WITH_CHECK_BODY_MAP.containsKey(needsPermissionParameter)) {
continue
}
builder.addCode("case \$N:\n", requestCodeFieldName(needsMethod))
addResultCaseBody(builder, needsMethod, rpe, targetParam, grantResultsParam)
}
builder
.addCode("default:\n")
.addStatement("break")
.endControlFlow();
return builder.build()
}
private fun createPermissionResultMethod(rpe: RuntimePermissionsElement): MethodSpec {
val targetParam = "target"
val requestCodeParam = "requestCode"
val grantResultsParam = "grantResults"
val builder = MethodSpec.methodBuilder("onRequestPermissionsResult")
.addTypeVariables(rpe.typeVariables)
.addModifiers(Modifier.STATIC)
.returns(TypeName.VOID)
.addParameter(rpe.typeName, targetParam)
.addParameter(TypeName.INT, requestCodeParam)
.addParameter(ArrayTypeName.of(TypeName.INT), grantResultsParam)
// For each @NeedsPermission method, add a switch case
builder.beginControlFlow("switch (\$N)", requestCodeParam)
for (needsMethod in rpe.needsElements) {
val needsPermissionParameter = needsMethod.getAnnotation(NeedsPermission::class.java).value[0]
if (ADD_WITH_CHECK_BODY_MAP.containsKey(needsPermissionParameter)) {
continue
}
builder.addCode("case \$N:\n", requestCodeFieldName(needsMethod))
// Delegate switch-case generation to implementing classes
addResultCaseBody(builder, needsMethod, rpe, targetParam, grantResultsParam)
}
// Add the default case
builder
.addCode("default:\n")
.addStatement("break")
.endControlFlow();
return builder.build()
}
private fun addResultCaseBody(builder: MethodSpec.Builder, needsMethod: ExecutableElement, rpe: RuntimePermissionsElement, targetParam: String, grantResultsParam: String) {
// just workaround, see https://github.com/hotchemi/PermissionsDispatcher/issues/45
val onDenied: ExecutableElement? = rpe.findOnDeniedForNeeds(needsMethod)
val hasDenied = onDenied != null
val needsPermissionParameter = needsMethod.getAnnotation(NeedsPermission::class.java).value[0]
val permissionField = permissionFieldName(needsMethod)
if (!ADD_WITH_CHECK_BODY_MAP.containsKey(needsPermissionParameter)) {
builder.beginControlFlow("if (\$T.getTargetSdkVersion(\$N) < 23 && !\$T.hasSelfPermissions(\$N, \$N))",
PERMISSION_UTILS, getActivityName(targetParam), PERMISSION_UTILS, getActivityName(targetParam), permissionField)
if (hasDenied) {
builder.addStatement("\$N.\$N()", targetParam, onDenied!!.simpleString())
}
builder.addStatement("return")
builder.endControlFlow()
}
// Add the conditional for "permission verified"
ADD_WITH_CHECK_BODY_MAP[needsPermissionParameter]?.addHasSelfPermissionsCondition(builder, getActivityName(targetParam), permissionField) ?: builder.beginControlFlow("if (\$T.verifyPermissions(\$N))", PERMISSION_UTILS, grantResultsParam)
// Based on whether or not the method has parameters, delegate to the "pending request" object or invoke the method directly
val hasParameters = needsMethod.parameters.isNotEmpty()
if (hasParameters) {
val pendingField = pendingRequestFieldName(needsMethod)
builder.beginControlFlow("if (\$N != null)", pendingField)
builder.addStatement("\$N.grant()", pendingField)
builder.endControlFlow()
} else {
builder.addStatement("target.\$N()", needsMethod.simpleString())
}
// Add the conditional for "permission denied" and/or "never ask again", if present
val onNeverAsk: ExecutableElement? = rpe.findOnNeverAskForNeeds(needsMethod)
val hasNeverAsk = onNeverAsk != null
if (hasDenied || hasNeverAsk) {
builder.nextControlFlow("else")
}
if (hasNeverAsk) {
// Split up the "else" case with another if condition checking for "never ask again" first
addShouldShowRequestPermissionRationaleCondition(builder, targetParam, permissionFieldName(needsMethod), false)
builder.addStatement("target.\$N()", onNeverAsk!!.simpleString())
// If a "permission denied" is present as well, go into an else case, otherwise close this temporary branch
if (hasDenied) {
builder.nextControlFlow("else")
} else {
builder.endControlFlow()
}
}
if (hasDenied) {
// Add the "permissionDenied" statement
builder.addStatement("\$N.\$N()", targetParam, onDenied!!.simpleString())
// Close the additional control flow potentially opened by a "never ask again" method
if (hasNeverAsk) {
builder.endControlFlow()
}
}
// Close the "switch" control flow
builder.endControlFlow()
// Remove the temporary pending request field, in case it was used for a method with parameters
if (hasParameters) {
builder.addStatement("\$N = null", pendingRequestFieldName(needsMethod))
}
builder.addStatement("break");
}
private fun hasNormalPermission(rpe: RuntimePermissionsElement): Boolean {
rpe.needsElements.forEach {
val permissionValue: List<String> = it.getAnnotation(NeedsPermission::class.java).permissionValue()
if (!permissionValue.contains(MANIFEST_SYSTEM_ALERT_WINDOW) && !permissionValue.contains(MANIFEST_WRITE_SETTING)) {
return true;
}
}
return false;
}
private fun hasSystemAlertWindowPermission(rpe: RuntimePermissionsElement): Boolean {
return isDefinePermission(rpe, MANIFEST_SYSTEM_ALERT_WINDOW)
}
private fun hasWriteSettingPermission(rpe: RuntimePermissionsElement): Boolean {
return isDefinePermission(rpe, MANIFEST_WRITE_SETTING)
}
private fun isDefinePermission(rpe: RuntimePermissionsElement, permissionName: String): Boolean {
rpe.needsElements.forEach {
val permissionValue: List<String> = it.getAnnotation(NeedsPermission::class.java).permissionValue()
if (permissionValue.contains(permissionName)) {
return true;
}
}
return false;
}
private fun createPermissionRequestClasses(rpe: RuntimePermissionsElement): List<TypeSpec> {
val classes: ArrayList<TypeSpec> = arrayListOf()
rpe.needsElements.forEach {
val onRationale = rpe.findOnRationaleForNeeds(it)
if (onRationale != null || it.parameters.isNotEmpty()) {
classes.add(createPermissionRequestClass(rpe, it))
}
}
return classes
}
private fun createPermissionRequestClass(rpe: RuntimePermissionsElement, needsMethod: ExecutableElement): TypeSpec {
// Select the superinterface of the generated class
// based on whether or not the annotated method has parameters
val hasParameters: Boolean = needsMethod.parameters.isNotEmpty()
val superInterfaceName: String = if (hasParameters) "GrantableRequest" else "PermissionRequest"
val targetType = rpe.typeName
val builder = TypeSpec.classBuilder(permissionRequestTypeName(needsMethod))
.addTypeVariables(rpe.typeVariables)
.addSuperinterface(ClassName.get("permissions.dispatcher", superInterfaceName))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
// Add required fields to the target
val weakFieldName: String = "weakTarget"
val weakFieldType = ParameterizedTypeName.get(ClassName.get("java.lang.ref", "WeakReference"), targetType)
builder.addField(weakFieldType, weakFieldName, Modifier.PRIVATE, Modifier.FINAL)
needsMethod.parameters.forEach {
builder.addField(typeNameOf(it), it.simpleString(), Modifier.PRIVATE, Modifier.FINAL)
}
// Add constructor
val targetParam = "target"
val constructorBuilder = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addParameter(targetType, targetParam)
.addStatement("this.\$L = new WeakReference<>(\$N)", weakFieldName, targetParam)
needsMethod.parameters.forEach {
val fieldName = it.simpleString()
constructorBuilder
.addParameter(typeNameOf(it), fieldName)
.addStatement("this.\$L = \$N", fieldName, fieldName)
}
builder.addMethod(constructorBuilder.build())
// Add proceed() override
val proceedMethod: MethodSpec.Builder = MethodSpec.methodBuilder("proceed")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.returns(TypeName.VOID)
.addStatement("\$T target = \$N.get()", targetType, weakFieldName)
.addStatement("if (target == null) return")
val requestCodeField = requestCodeFieldName(needsMethod)
ADD_WITH_CHECK_BODY_MAP[needsMethod.getAnnotation(NeedsPermission::class.java).value[0]]?.addRequestPermissionsStatement(proceedMethod, getActivityName(targetParam), requestCodeField) ?: addRequestPermissionsStatement(proceedMethod, targetParam, permissionFieldName(needsMethod), requestCodeField)
builder.addMethod(proceedMethod.build())
// Add cancel() override method
val cancelMethod: MethodSpec.Builder = MethodSpec.methodBuilder("cancel")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.returns(TypeName.VOID)
val onDenied = rpe.findOnDeniedForNeeds(needsMethod)
if (onDenied != null) {
cancelMethod
.addStatement("\$T target = \$N.get()", targetType, weakFieldName)
.addStatement("if (target == null) return")
.addStatement("target.\$N()", onDenied.simpleString())
}
builder.addMethod(cancelMethod.build())
// For classes with additional parameters, add a "grant()" method
if (hasParameters) {
val grantMethod: MethodSpec.Builder = MethodSpec.methodBuilder("grant")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.returns(TypeName.VOID)
grantMethod
.addStatement("\$T target = \$N.get()", targetType, weakFieldName)
.addStatement("if (target == null) return")
// Compose the call to the permission-protected method;
// since the number of parameters is variable, utilize the low-level CodeBlock here
// to compose the method call and its parameters
grantMethod.addCode(
CodeBlock.builder()
.add("target.\$N(", needsMethod.simpleString())
.add(varargsParametersCodeBlock(needsMethod))
.addStatement(")")
.build()
)
builder.addMethod(grantMethod.build())
}
return builder.build()
}
}