1 /*
<lambda>null2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.content.res.loader.cts
18 
19 import android.content.Context
20 import android.content.res.AssetFileDescriptor
21 import android.content.res.Resources
22 import android.os.ParcelFileDescriptor
23 import android.util.TypedValue
24 import org.mockito.Answers
25 import org.mockito.stubbing.Answer
26 import org.xmlpull.v1.XmlPullParser
27 import java.io.File
28 
29 object Utils {
30     val ANSWER_THROWS = Answer<Any> {
31         when (val name = it.method.name) {
32             "toString" -> return@Answer Answers.CALLS_REAL_METHODS.answer(it)
33             else -> throw UnsupportedOperationException("$name with " +
34                     "${it.arguments?.joinToString()} should not be called")
35         }
36     }
37 }
38 
dpToPxnull39 fun Int.dpToPx(resources: Resources) = TypedValue.applyDimension(
40         TypedValue.COMPLEX_UNIT_DIP,
41         this.toFloat(),
42         resources.displayMetrics
43 ).toInt()
44 
45 fun AssetFileDescriptor.readText() = createInputStream().reader().readText()
46 
47 fun XmlPullParser.advanceToRoot() = apply {
48     while (next() != XmlPullParser.START_TAG) {
49         // Empty
50     }
51 }
52 
Contextnull53 fun Context.copiedAssetFile(fileName: String): ParcelFileDescriptor {
54     return resources.assets.open(fileName).use { input ->
55         // AssetManager doesn't expose a direct file descriptor to the asset, so copy it to
56         // an individual file so one can be created manually.
57         val copiedFile = File(filesDir, fileName)
58         copiedFile.outputStream().use { output ->
59             input.copyTo(output)
60         }
61         ParcelFileDescriptor.open(copiedFile, ParcelFileDescriptor.MODE_READ_WRITE)
62     }
63 }
64