1 /*
2  * 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 
17 package com.android.launcher3.dagger
18 
19 import android.content.Context
20 import android.view.LayoutInflater
21 import com.android.launcher3.LauncherApplication
22 
23 /**
24  * Utility class to extract LauncherAppComponent from a context.
25  *
26  * If the context doesn't provide LauncherAppComponent by default, it creates a new one and
27  * associate it with that context
28  */
29 object LauncherComponentProvider {
30 
31     @JvmStatic
getnull32     fun get(c: Context): LauncherAppComponent {
33         val app = c.applicationContext
34         if (app is LauncherApplication) return app.appComponent
35 
36         val inflater = LayoutInflater.from(app)
37         val existingFilter = inflater.filter
38         if (existingFilter is Holder) return existingFilter.component
39 
40         // Create a new component
41         return Holder(
42                 DaggerLauncherAppComponent.builder().appContext(app).build()
43                     as LauncherAppComponent,
44                 existingFilter,
45             )
46             .apply { inflater.filter = this }
47             .component
48     }
49 
50     private data class Holder(
51         val component: LauncherAppComponent,
52         private val filter: LayoutInflater.Filter?,
53     ) : LayoutInflater.Filter {
54 
onLoadClassnull55         override fun onLoadClass(clazz: Class<*>?) = filter?.onLoadClass(clazz) ?: true
56     }
57 }
58