1 /* <lambda>null2 * Copyright (C) 2024 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 package com.android.intentresolver.ui.viewmodel 17 18 import android.content.Intent 19 import android.content.IntentFilter 20 import android.content.IntentFilter.MalformedMimeTypeException 21 import android.net.Uri 22 import android.os.PatternMatcher 23 24 /** Collects Uris from standard locations within the Intent. */ 25 fun Intent.collectUris(): Set<Uri> = buildSet { 26 data?.also { add(it) } 27 @Suppress("DEPRECATION") 28 when (val stream = extras?.get(Intent.EXTRA_STREAM)) { 29 is Uri -> add(stream) 30 is ArrayList<*> -> addAll(stream.mapNotNull { it as? Uri }) 31 else -> Unit 32 } 33 clipData?.apply { (0..<itemCount).mapNotNull { getItemAt(it).uri }.forEach(::add) } 34 } 35 IntentFilternull36fun IntentFilter.addUri(uri: Uri) { 37 uri.scheme?.also { addDataScheme(it) } 38 uri.host?.also { addDataAuthority(it, null) } 39 uri.path?.also { addDataPath(it, PatternMatcher.PATTERN_LITERAL) } 40 } 41 createIntentFilternull42fun Intent.createIntentFilter(): IntentFilter? { 43 val uris = collectUris() 44 if (action == null && uris.isEmpty()) { 45 // at least one is required to be meaningful 46 return null 47 } 48 return IntentFilter().also { filter -> 49 type?.also { 50 try { 51 filter.addDataType(it) 52 } catch (_: MalformedMimeTypeException) { // ignore malformed type 53 } 54 } 55 action?.also { filter.addAction(it) } 56 uris.forEach(filter::addUri) 57 } 58 } 59