1 /*
2  * Copyright (C) 2022 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.quicksearchbox.ui
18 
19 import android.content.Context
20 import android.view.View
21 import android.view.ViewGroup
22 import com.android.quicksearchbox.Suggestion
23 import com.android.quicksearchbox.SuggestionCursor
24 import java.util.LinkedList
25 
26 /** Suggestion view factory for Google suggestions. */
27 class DefaultSuggestionViewFactory(context: Context?) : SuggestionViewFactory {
28   private val mFactories: LinkedList<SuggestionViewFactory> = LinkedList<SuggestionViewFactory>()
29   private val mDefaultFactory: SuggestionViewFactory
30   private var mViewTypes: HashSet<String>? = null
31 
32   /** Must only be called from the constructor */
addFactorynull33   protected fun addFactory(factory: SuggestionViewFactory?) {
34     mFactories.addFirst(factory)
35   }
36 
37   @get:Override
38   override val suggestionViewTypes: Collection<String>
39     get() {
40       if (mViewTypes == null) {
41         mViewTypes = hashSetOf()
42         mViewTypes?.addAll(mDefaultFactory.suggestionViewTypes)
43         for (factory in mFactories) {
44           mViewTypes?.addAll(factory.suggestionViewTypes)
45         }
46       }
47       return mViewTypes as Collection<String>
48     }
49 
50   @Override
getViewnull51   override fun getView(
52     suggestion: SuggestionCursor?,
53     userQuery: String?,
54     convertView: View?,
55     parent: ViewGroup?
56   ): View? {
57     for (factory in mFactories) {
58       if (factory.canCreateView(suggestion)) {
59         return factory.getView(suggestion, userQuery, convertView, parent)
60       }
61     }
62     return mDefaultFactory.getView(suggestion, userQuery, convertView, parent)
63   }
64 
65   @Override
getViewTypenull66   override fun getViewType(suggestion: Suggestion?): String {
67     for (factory in mFactories) {
68       if (factory.canCreateView(suggestion)) {
69         return factory.getViewType(suggestion)!!
70       }
71     }
72     return mDefaultFactory.getViewType(suggestion)!!
73   }
74 
75   @Override
canCreateViewnull76   override fun canCreateView(suggestion: Suggestion?): Boolean {
77     return true
78   }
79 
80   init {
81     mDefaultFactory = DefaultSuggestionView.Factory(context)
82     addFactory(WebSearchSuggestionView.Factory(context))
83   }
84 }
85