-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExtensions.kt
502 lines (444 loc) · 15.8 KB
/
Extensions.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.Context
import android.content.res.Resources
import android.content.res.Resources.getSystem
import android.graphics.*
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Build
import android.os.SystemClock
import android.provider.MediaStore
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.annotation.*
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.viewpager2.widget.ViewPager2
import com.demo.BuildConfig
import com.demo.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.time.DayOfWeek
import java.time.temporal.WeekFields
import java.util.*
///Initiate and Return CameraController and display camera feed in PreviewView - CameraX
///Change use cases as you require, Activity or Fragment can be lifecycleOwner
fun LifecycleOwner.initCameraController(
context: Context,
previewView: PreviewView,
hasZoom: Boolean = true,
hasTapToFocus: Boolean = true,
vararg useCases: Int = intArrayOf(CameraController.IMAGE_CAPTURE,CameraController.IMAGE_ANALYSIS)
): CameraController {
val cameraController = LifecycleCameraController(context)
cameraController.bindToLifecycle(this)
previewView.controller = cameraController
cameraController.isPinchToZoomEnabled = hasZoom
cameraController.isTapToFocusEnabled = hasTapToFocus
useCases.forEach { cameraController.setEnabledUseCases(it) }
return cameraController
}
///Init CameraController and generate a PreviewView for Compose
///Change Use cases as required, use the resulting PreviewView as required
@Composable
fun InitCameraController(
hasZoom: Boolean = true,
hasTapToFocus: Boolean = true,
onInitialized: (PreviewView, CameraController)->Unit,
vararg useCases: Int = intArrayOf(CameraController.IMAGE_CAPTURE,CameraController.IMAGE_ANALYSIS)
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val previewView: PreviewView = remember { PreviewView(context) }
val cameraController = LifecycleCameraController(context)
LaunchedEffect(Unit) {
cameraController.bindToLifecycle(lifecycleOwner)
previewView.controller = cameraController
useCases.forEach { cameraController.setEnabledUseCases(it) }
cameraController.isPinchToZoomEnabled = hasZoom
cameraController.isTapToFocusEnabled = hasTapToFocus
onInitialized(previewView,cameraController)
}
}
///Init CameraController with Predefined previewView in Compose
///Change Use cases as required, use the resulting PreviewView as required
@Composable
fun InitCameraController(
previewView: PreviewView,
hasZoom: Boolean = true,
hasTapToFocus: Boolean = true,
onInitialized: (CameraController)->Unit,
vararg useCases: Int = intArrayOf(CameraController.IMAGE_CAPTURE,CameraController.IMAGE_ANALYSIS)
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val cameraController = LifecycleCameraController(context)
LaunchedEffect(Unit) {
cameraController.bindToLifecycle(lifecycleOwner)
previewView.controller = cameraController
useCases.forEach { cameraController.setEnabledUseCases(it) }
cameraController.isPinchToZoomEnabled = hasZoom
cameraController.isTapToFocusEnabled = hasTapToFocus
onInitialized(cameraController)
}
}
///Format any Int value to INR - change fractions as needed
fun Int.formatAsINR(): String {
val formatter = NumberFormat.getCurrencyInstance()
formatter.maximumFractionDigits = 0
formatter.currency = Currency.getInstance(Locale("en", "IN"))
return formatter.format(this)
}
///Format any Int value to USD - change fractions as needed
fun Int.formatAsUSD(): String {
val formatter = NumberFormat.getCurrencyInstance()
formatter.maximumFractionDigits = 0
formatter.currency = Currency.getInstance(Locale.US)
return formatter.format(this)
}
///Check If a PDF is password Protected
fun checkIfPdfIsPasswordProtected(file: File): Boolean {
val parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
?: return false
return try {
PdfRenderer(parcelFileDescriptor)
false
} catch (securityException: SecurityException) {
true
} catch (invalidPassword: InvalidPasswordException) {
true
}
}
///getAppIcon of any app installed with just packagename and context
///your app must declare the target app in queries or have query all packages permission
fun getAppIcon(packageName: String?, context: Context): Drawable? {
return packageName?.let {
try {
context.packageManager.getApplicationIcon(packageName)
} catch (e: Exception) {
null
}
}
}
///get color Int From attr name (example: R.attr.colorPrimary)
@ColorInt
fun Context.themeColor(@AttrRes attrRes: Int): Int = TypedValue()
.apply { theme.resolveAttribute(attrRes, this, true) }
.data
///get Uri of any resource
internal fun Context.getResourceUri(@AnyRes resourceId: Int): Uri = Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(packageName)
.path(resourceId.toString())
.build()
///get resource id by name
internal fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
///get drawable by id
internal fun Context.drawableIdByName(resIdName: String?): Int {
return if (resIdName != null) {
resources.getIdentifier(resIdName, "drawable", packageName)
} else
R.drawable.adaptive_icon_foreground
}
///inflate a layout
internal fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
return context.layoutInflater.inflate(layoutRes, this, attachToRoot)
}
///get inflater from context
internal val Context.layoutInflater: LayoutInflater
get() = LayoutInflater.from(this)
///get IMM
internal val Context.inputMethodManager
get() = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
///i am just lazy
internal /*inline*/ fun Boolean?.orFalse(): Boolean = this ?: false
///get drawable compat
internal fun Context.getDrawableCompat(@DrawableRes drawable: Int) = ContextCompat.getDrawable(
this,
drawable
)
///get Color compat
internal fun Context.getColorCompat(@ColorRes color: Int) = ContextCompat.getColor(this, color)
///set color to textView, but why? => cause I am LAZY
internal fun TextView.setTextColorRes(@ColorRes color: Int) = setTextColor(
context.getColorCompat(
color
)
)
///int to dp or px
val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt()
val Int.px: Int get() = (this * getSystem().displayMetrics.density).toInt()
///dp to px
fun dpToPx(dp: Int, context: Context): Int =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(),
context.resources.displayMetrics
).toInt()
///Copy input stream to file
fun File.copyInputStreamToFile(inputStream: InputStream): Boolean {
return try {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
true
} catch (_: Exception) {
false
}
}
///There will be multiple functions for the same task use as per your requirement
///Write a Bitmap into a file
fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85) {
outputStream().use { out ->
bitmap.compress(format, quality, out)
out.flush()
}
}
///Save a bitmap into path
fun Bitmap.save(path: String, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85): Boolean {
return try {
val output = FileOutputStream(path)
this.compress(format, quality, output)
output.close()
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
///Save a bitmap into file
fun Bitmap.saveToFile(file: File, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85): Boolean {
return try {
FileOutputStream(file).use { out ->
this.compress(format, quality, out)
}
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
///Convert a view into bitmap without drawing cache
fun View.toBitmap(): Bitmap {
var bitmap = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
this.draw(canvas)
return bitmap
}
@Suppress("DEPRECATION")
fun Uri.getBitmap(context: Context): Bitmap{
return if(Build.VERSION.SDK_INT < 28) {
MediaStore.Images.Media.getBitmap(
context.contentResolver,
this
)
} else {
val source = ImageDecoder.createSource(context.contentResolver, this)
ImageDecoder.decodeBitmap(source)
}
}
// Get average color of a bitmap
fun calculateAverageColor(bitmap: Bitmap, pixelSpacing: Int): Int {
var r = 0
var g = 0
var b = 0
val height = bitmap.height
val width = bitmap.width
var n = 0
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
var i = 0
while (i < pixels.size) {
val color = pixels[i]
r += Color.red(color)
g += Color.green(color)
b += Color.blue(color)
n++
i += pixelSpacing
}
return Color.rgb(r / n, g / n, b / n)
}
///Correct orientation of a bitmap
///In some devices orientation might be wrong in those cases use this fun
fun Bitmap.rotateBitmap(contentResolver: ContentResolver, uri: Uri): Bitmap? {
val matrix = Matrix()
var exif: ExifInterface?
return try {
val inputStream = contentResolver.openInputStream(uri)
inputStream?.let {
exif = ExifInterface(inputStream)
val orientation = exif!!.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return this
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return this
}
} ?: return this
val bmRotated = Bitmap.createBitmap(this, 0, 0, this.width, this.height, matrix, true)
this.recycle()
bmRotated.copy(Bitmap.Config.ARGB_8888, true)
} catch (e: Exception) {
e.printStackTrace()
null
}
}
val screenWidth: Int = Resources.getSystem().displayMetrics.widthPixels
val screenHeight: Int = Resources.getSystem().displayMetrics.heightPixels
///Scale Bitmap but keep aspect ratio
fun Bitmap.scaleBitmapAndKeepRation(
reqHeight: Int = screenHeight,
reqWidth: Int = screenWidth
): Bitmap {
val matrix = Matrix()
matrix.setRectToRect(
RectF(
0f, 0f, width.toFloat(),
height.toFloat()
),
RectF(0f, 0f, reqWidth.toFloat(), reqHeight.toFloat()),
Matrix.ScaleToFit.CENTER
)
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
///Rotate bitmap by angle
fun Bitmap.rotate(angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(this, 0, 0, this.width / 2, this.height / 2, matrix, true)
}
///get Uri form file using file provider please check authority first
fun File.getUri(context: Context): Uri{
return FileProvider.getUriForFile(
context,
"${BuildConfig.APPLICATION_ID}.provider",
this
)
}
///Copy content of an uri to another file
fun Uri.copyTo(file: File, context: Context): Boolean {
return try {
context.contentResolver.openInputStream(this).use { input ->
file.outputStream().use { output ->
input?.copyTo(output)
}
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
///Copy contents of a file to another file
fun File.copyTo(file: File): Boolean {
return try {
file.outputStream().use { output ->
this.inputStream().copyTo(output)
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
///set Corners to gradient drawables
fun GradientDrawable.setCornerRadius(
topLeft: Float = 0F,
topRight: Float = 0F,
bottomRight: Float = 0F,
bottomLeft: Float = 0F
) {
cornerRadii = arrayOf(
topLeft, topLeft,
topRight, topRight,
bottomRight, bottomRight,
bottomLeft, bottomLeft
).toFloatArray()
}
///Copy a string to clipBoard
fun String.copyToClipBoard(context: Context, label: String = ""): Boolean {
return try {
val clipboard = ContextCompat.getSystemService(context, ClipboardManager::class.java)
val clip = ClipData.newPlainText(label, this)
clipboard?.setPrimaryClip(clip)
true
} catch (e: Exception) {
false
}
}
///perform touch on view at x, y. x & y are optional
fun View.performBasicTouchAt(x: Float = 0f, y: Float = 0f) {
dispatchTouchEvent(
MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_MOVE,
x, y, 0
)
)
}
///Share a String
fun String.share(subject: String = "Subject", shareHint: String = "Choose One",context: Context): Boolean {
return try {
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
shareIntent.putExtra(Intent.EXTRA_TEXT, this)
context.startActivity(Intent.createChooser(shareIntent, shareHint))
true
} catch (e: java.lang.Exception) {
e.printStackTrace()
false
}
}
///hide softkeyboard
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
@RequiresApi(Build.VERSION_CODES.O)
fun daysOfWeekFromLocale(): Array<DayOfWeek> {
val firstDayOfWeek = WeekFields.of(Locale.getDefault()).firstDayOfWeek
var daysOfWeek = DayOfWeek.values()
// Order `daysOfWeek` array so that firstDayOfWeek is at index 0.
// Only necessary if firstDayOfWeek != DayOfWeek.MONDAY which has ordinal 0.
if (firstDayOfWeek != DayOfWeek.MONDAY) {
val rhs = daysOfWeek.sliceArray(firstDayOfWeek.ordinal..daysOfWeek.indices.last)
val lhs = daysOfWeek.sliceArray(0 until firstDayOfWeek.ordinal)
daysOfWeek = rhs + lhs
}
return daysOfWeek
}