TestActivity.kt 70.8 KB
Newer Older
1
2
package foundation.e.blisslauncher.features.test

Amit Kumar's avatar
Amit Kumar committed
3
4
5
6
7
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
8
import android.animation.ValueAnimator
9
import android.app.ActivityOptions
Amit Kumar's avatar
Amit Kumar committed
10
11
12
13
14
import android.app.AlertDialog
import android.app.usage.UsageStats
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.BroadcastReceiver
Amit Kumar's avatar
Amit Kumar committed
15
import android.content.ComponentName
Amit Kumar's avatar
Amit Kumar committed
16
17
import android.content.Context
import android.content.ContextWrapper
Amit Kumar's avatar
Amit Kumar committed
18
import android.content.Intent
Amit Kumar's avatar
Amit Kumar committed
19
import android.content.IntentFilter
Amit Kumar's avatar
Amit Kumar committed
20
import android.content.pm.ActivityInfo
21
22
23
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherActivityInfo
import android.content.pm.LauncherApps
24
import android.content.res.Configuration
Amit Kumar's avatar
Amit Kumar committed
25
import android.graphics.Point
26
import android.graphics.Rect
Amit Kumar's avatar
Amit Kumar committed
27
import android.location.LocationManager
28
import android.net.Uri
29
import android.os.Bundle
Amit Kumar's avatar
Amit Kumar committed
30
import android.os.Handler
31
import android.os.Looper
32
import android.os.Process
33
34
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
Amit Kumar's avatar
Amit Kumar committed
35
36
37
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
38
39
import android.util.Log
import android.view.ContextThemeWrapper
Amit Kumar's avatar
Amit Kumar committed
40
import android.view.KeyEvent
41
import android.view.LayoutInflater
Amit Kumar's avatar
Amit Kumar committed
42
import android.view.MotionEvent
43
import android.view.View
Amit Kumar's avatar
Amit Kumar committed
44
import android.view.ViewGroup
45
import android.view.animation.AccelerateDecelerateInterpolator
Amit Kumar's avatar
Amit Kumar committed
46
47
48
49
50
51
52
53
54
55
import android.view.animation.LinearInterpolator
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
Amit Kumar's avatar
Amit Kumar committed
56
import androidx.core.view.isVisible
Amit Kumar's avatar
Amit Kumar committed
57
58
59
60
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
61
import androidx.viewpager.widget.ViewPager
Amit Kumar's avatar
Amit Kumar committed
62
import com.jakewharton.rxbinding3.widget.textChanges
Amit Kumar's avatar
Amit Kumar committed
63
import foundation.e.blisslauncher.BlissLauncher
64
import foundation.e.blisslauncher.R
Amit Kumar's avatar
Amit Kumar committed
65
66
import foundation.e.blisslauncher.core.Preferences
import foundation.e.blisslauncher.core.Utilities
Amit Kumar's avatar
Amit Kumar committed
67
import foundation.e.blisslauncher.core.customviews.AbstractFloatingView
Amit Kumar's avatar
Amit Kumar committed
68
69
70
import foundation.e.blisslauncher.core.customviews.BlissFrameLayout
import foundation.e.blisslauncher.core.customviews.BlissInput
import foundation.e.blisslauncher.core.customviews.InsettableFrameLayout
71
import foundation.e.blisslauncher.core.customviews.LauncherPagedView
Amit Kumar's avatar
Amit Kumar committed
72
73
74
75
import foundation.e.blisslauncher.core.customviews.RoundedWidgetView
import foundation.e.blisslauncher.core.customviews.SquareFrameLayout
import foundation.e.blisslauncher.core.customviews.WidgetHost
import foundation.e.blisslauncher.core.database.DatabaseManager
76
import foundation.e.blisslauncher.core.database.model.ApplicationItem
Amit Kumar's avatar
Amit Kumar committed
77
import foundation.e.blisslauncher.core.database.model.FolderItem
Amit Kumar's avatar
Amit Kumar committed
78
import foundation.e.blisslauncher.core.database.model.LauncherItem
79
import foundation.e.blisslauncher.core.database.model.ShortcutItem
Amit Kumar's avatar
Amit Kumar committed
80
81
import foundation.e.blisslauncher.core.executors.AppExecutors
import foundation.e.blisslauncher.core.utils.AppUtils
Amit Kumar's avatar
Amit Kumar committed
82
import foundation.e.blisslauncher.core.utils.Constants
83
84
import foundation.e.blisslauncher.core.utils.IntSet
import foundation.e.blisslauncher.core.utils.IntegerArray
Amit Kumar's avatar
Amit Kumar committed
85
import foundation.e.blisslauncher.core.utils.ItemInfoMatcher
Amit Kumar's avatar
Amit Kumar committed
86
import foundation.e.blisslauncher.core.utils.ListUtil
Amit Kumar's avatar
Amit Kumar committed
87
import foundation.e.blisslauncher.core.utils.PackageUserKey
Amit Kumar's avatar
Amit Kumar committed
88
import foundation.e.blisslauncher.core.utils.UserHandle
89
import foundation.e.blisslauncher.features.folder.FolderPagerAdapter
Amit Kumar's avatar
Amit Kumar committed
90
import foundation.e.blisslauncher.features.launcher.Hotseat
Amit Kumar's avatar
Amit Kumar committed
91
import foundation.e.blisslauncher.features.launcher.SearchInputDisposableObserver
Amit Kumar's avatar
Amit Kumar committed
92
93
94
import foundation.e.blisslauncher.features.notification.DotInfo
import foundation.e.blisslauncher.features.notification.NotificationDataProvider
import foundation.e.blisslauncher.features.notification.NotificationListener
95
96
import foundation.e.blisslauncher.features.shortcuts.DeepShortcutManager
import foundation.e.blisslauncher.features.shortcuts.ShortcutKey
Amit Kumar's avatar
Amit Kumar committed
97
98
99
import foundation.e.blisslauncher.features.suggestions.AutoCompleteAdapter
import foundation.e.blisslauncher.features.suggestions.SearchSuggestionUtil
import foundation.e.blisslauncher.features.suggestions.SuggestionsResult
Amit Kumar's avatar
Amit Kumar committed
100
101
import foundation.e.blisslauncher.features.test.LauncherState.*
import foundation.e.blisslauncher.features.test.RotationHelper.REQUEST_NONE
102
103
import foundation.e.blisslauncher.features.test.dragndrop.DragController
import foundation.e.blisslauncher.features.test.dragndrop.DragLayer
Amit Kumar's avatar
Amit Kumar committed
104
import foundation.e.blisslauncher.features.test.graphics.RotationMode
Amit Kumar's avatar
Amit Kumar committed
105
106
107
108
109
110
111
112
113
import foundation.e.blisslauncher.features.usagestats.AppUsageStats
import foundation.e.blisslauncher.features.weather.DeviceStatusService
import foundation.e.blisslauncher.features.weather.ForecastBuilder
import foundation.e.blisslauncher.features.weather.WeatherPreferences
import foundation.e.blisslauncher.features.weather.WeatherSourceListenerService
import foundation.e.blisslauncher.features.weather.WeatherUpdateService
import foundation.e.blisslauncher.features.widgets.WidgetManager
import foundation.e.blisslauncher.features.widgets.WidgetViewBuilder
import foundation.e.blisslauncher.features.widgets.WidgetsActivity
114
import foundation.e.blisslauncher.features.widgets.WidgetsRootView
Amit Kumar's avatar
Amit Kumar committed
115
import foundation.e.blisslauncher.uioverrides.OverlayCallbackImpl
116
import foundation.e.blisslauncher.uioverrides.UiFactory
Amit Kumar's avatar
Amit Kumar committed
117
118
import io.reactivex.Observable
import io.reactivex.ObservableSource
Amit Kumar's avatar
Amit Kumar committed
119
120
121
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
Amit Kumar's avatar
Amit Kumar committed
122
import io.reactivex.schedulers.Schedulers
Amit Kumar's avatar
Amit Kumar committed
123
import java.lang.Exception
124
import java.net.URISyntaxException
125
import java.util.ArrayList
Amit Kumar's avatar
Amit Kumar committed
126
127
128
129
import java.util.Arrays
import java.util.Comparator
import java.util.Locale
import java.util.concurrent.TimeUnit
Amit Kumar's avatar
Amit Kumar committed
130
import java.util.function.Predicate
131
import me.relex.circleindicator.CircleIndicator
132

Amit Kumar's avatar
Amit Kumar committed
133
134
class TestActivity : BaseDraggingActivity(), AutoCompleteAdapter.OnSuggestionClickListener,
    LauncherModel.Callbacks {
135

Amit Kumar's avatar
Amit Kumar committed
136
    private var mModel: LauncherModel? = null
137
138
139
    private lateinit var widgetRootView: WidgetsRootView
    private lateinit var overlayCallbackImpl: OverlayCallbackImpl

140
141
    // Folder start scale
    private var startScaleFinal: Float = 0f
142
    private var mCancelTouchController: Runnable? = null
Amit Kumar's avatar
Amit Kumar committed
143
144
    private var mOnResumeCallback: OnResumeCallback? = null
    private lateinit var mAppTransitionManager: LauncherAppTransitionManager
145
    lateinit var dragController: DragController
146
    private lateinit var mOldConfig: Configuration
Amit Kumar's avatar
Amit Kumar committed
147
148
    private var mCompositeDisposable: CompositeDisposable? = null

Amit Kumar's avatar
Amit Kumar committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    // Type: int
    private val RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"

    // Type: int
    private val RUNTIME_STATE = "launcher.state"

    // Type: PendingRequestArgs
    private val RUNTIME_STATE_PENDING_REQUEST_ARGS = "launcher.request_args"

    // Type: int
    private val RUNTIME_STATE_PENDING_REQUEST_CODE = "launcher.request_code"

    // Type: ActivityResultInfo
    private val RUNTIME_STATE_PENDING_ACTIVITY_RESULT = "launcher.activity_result"

164
165
166
167
    private lateinit var launcherView: View
    private lateinit var dragLayer: DragLayer
    private lateinit var workspace: LauncherPagedView
    private lateinit var hotseat: Hotseat
Amit Kumar's avatar
Amit Kumar committed
168
169
170
171
172
    private lateinit var widgetPage: InsettableFrameLayout

    private lateinit var mSearchInput: BlissInput

    private val REQUEST_LOCATION_SOURCE_SETTING = 267
Amit Kumar's avatar
Amit Kumar committed
173

Amit Kumar's avatar
Amit Kumar committed
174
    private lateinit var rotationHelper: RotationHelper
Amit Kumar's avatar
Amit Kumar committed
175
    private var mRotationMode = RotationMode.NORMAL
Amit Kumar's avatar
Amit Kumar committed
176
177
178
179
180
    private lateinit var mStateManager: LauncherStateManager

    // UI and state for the overview panel
    private lateinit var overviewPanel: View

181
182
    private lateinit var folderContainer: RelativeLayout

183
    private val mOnResumeCallbacks = ArrayList<OnResumeCallback>()
Amit Kumar's avatar
Amit Kumar committed
184

Amit Kumar's avatar
Amit Kumar committed
185
186
    private lateinit var mAppWidgetManager: AppWidgetManager
    private lateinit var mAppWidgetHost: WidgetHost
187
    private lateinit var widgetContainer: LinearLayout
Amit Kumar's avatar
Amit Kumar committed
188
189
190
191
192
193
194
195
196
197
198
199
200
    private var activeRoundedWidgetView: RoundedWidgetView? = null

    private lateinit var mWeatherPanel: View
    private lateinit var mWeatherSetupTextView: View
    private val allAppsDisplayed = false
    private val forceRefreshSuggestedApps = false

    private var mUsageStats: List<UsageStats>? = null

    private var enableLocationDialog: AlertDialog? = null

    private var currentAnimator: AnimatorSet? = null

201
202
203
204
205
206
207
    private var activeFolder: FolderItem? = null
    private var activeFolderView: IconTextView? = null
    private var activeFolderStartBounds = Rect()

    private var mFolderAppsViewPager: ViewPager? = null
    private var mFolderTitleInput: BlissInput? = null

208
209
    private val mainHandler = Handler(Looper.getMainLooper())

Amit Kumar's avatar
Amit Kumar committed
210
211
212
213
214
215
216
217
    private val mWeatherReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (!intent.getBooleanExtra(WeatherUpdateService.EXTRA_UPDATE_CANCELLED, false)) {
                updateWeatherPanel()
            }
        }
    }

Amit Kumar's avatar
Amit Kumar committed
218
219
220
221
222
    private lateinit var notificationDataProvider: NotificationDataProvider
    val mHandler = Handler()
    private val mHandleDeferredResume = Runnable { this.handleDeferredResume() }
    private var mDeferredResumePending = false

Amit Kumar's avatar
Amit Kumar committed
223
224
    private val TAG = "TestActivity"

225
    override fun onCreate(savedInstanceState: Bundle?) {
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        if (DEBUG_STRICT_MODE) {
            StrictMode.setThreadPolicy(
                StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork() // or .detectAll() for all detectable problems
                    .penaltyLog()
                    .build()
            )
            StrictMode.setVmPolicy(
                VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects()
                    .detectLeakedClosableObjects()
                    .penaltyLog()
                    .penaltyDeath()
                    .build()
            )
        }
        TraceHelper.beginSection("Launcher-onCreate")

246
        super.onCreate(savedInstanceState)
247
248
        TraceHelper.partitionSection("Launcher-onCreate", "super call")

Amit Kumar's avatar
Amit Kumar committed
249
        val app = LauncherAppState.getInstance(this)
Amit Kumar's avatar
Amit Kumar committed
250
        mModel = app.setLauncher(this)
251
        mOldConfig = Configuration(resources.configuration)
Amit Kumar's avatar
Amit Kumar committed
252
253
254
255

        mAppWidgetManager = BlissLauncher.getApplication(this).appWidgetManager
        mAppWidgetHost = BlissLauncher.getApplication(this).appWidgetHost

Amit Kumar's avatar
Amit Kumar committed
256
        initDeviceProfile(BlissLauncher.getApplication(this).invariantDeviceProfile)
257
        dragController = DragController(this)
258
        rotationHelper = RotationHelper(this)
Amit Kumar's avatar
Amit Kumar committed
259
        mStateManager = LauncherStateManager(this)
260
261
        launcherView = LayoutInflater.from(this).inflate(R.layout.activity_test, null)
        setupViews()
Amit Kumar's avatar
Amit Kumar committed
262

Amit Kumar's avatar
Amit Kumar committed
263
264
265
266
        askForNotificationIfFirstTime()

        notificationDataProvider = NotificationDataProvider(this)

Amit Kumar's avatar
Amit Kumar committed
267
        mAppTransitionManager = LauncherAppTransitionManager.newInstance(this)
268

Amit Kumar's avatar
Amit Kumar committed
269
270
271
272
273
274
275
        val internalStateHandled = InternalStateHandler.handleCreate(this, intent)
        if (internalStateHandled) {
            savedInstanceState?.remove(RUNTIME_STATE)
        }
        restoreState(savedInstanceState)
        mStateManager.reapplyState()

276
        setContentView(launcherView)
Amit Kumar's avatar
Amit Kumar committed
277
278
279
280
        rootView.dispatchInsets()

        systemUiController.updateUiState(
            SystemUiController.UI_STATE_BASE_WINDOW,
Amit Kumar's avatar
Amit Kumar committed
281
            true
Amit Kumar's avatar
Amit Kumar committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
        )
        rotationHelper.initialize()
        TraceHelper.endSection("Launcher-onCreate")
        mStateManager.addStateListener(object : LauncherStateManager.StateListener {
            override fun onStateTransitionStart(toState: LauncherState?) {}
            override fun onStateTransitionComplete(finalState: LauncherState) {
                if (finalState === NORMAL) {
                    // TODO: may use later
                } else if (finalState === OVERVIEW || finalState === OVERVIEW_PEEK) {
                    // TODO: may use later
                } else {
                    // TODO: may use later
                }
            }
        })
Amit Kumar's avatar
Amit Kumar committed
297
        createOrUpdateIconGrid()
298
299
        overlayCallbackImpl = OverlayCallbackImpl(this)
        setLauncherOverlay(overlayCallbackImpl)
Amit Kumar's avatar
Amit Kumar committed
300
301
    }

Amit Kumar's avatar
Amit Kumar committed
302
303
304
305
306
    private fun askForNotificationIfFirstTime() {
        if (Preferences.shouldAskForNotificationAccess(this)) {
            val cr = contentResolver
            val setting = "enabled_notification_listeners"
            var permissionString = Settings.Secure.getString(cr, setting)
307
308
            val cn = ComponentName(this, NotificationListener::class.java)

309
310
311
312
            val enabled =
                permissionString != null && (permissionString.contains(cn.flattenToString()) || permissionString.contains(
                    cn.flattenToShortString()
                ))
313
314

            if (!enabled) {
315
316
317
318
                val launcherApps: LauncherApps =
                    getSystemService(LAUNCHER_APPS_SERVICE) as LauncherApps
                val launcherInfo =
                    launcherApps.getApplicationInfo(packageName, 0, Process.myUserHandle())
319
                if (launcherInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
320
321
322
323
324
325
                    val args = Bundle()
                    args.putString(":settings:fragment_args_key", cn.flattenToString())
                    val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .putExtra(":settings:fragment_args_key", cn.flattenToString())
                        .putExtra(":settings:show_fragment_args", args)
Amit Kumar's avatar
Amit Kumar committed
326
                    startActivity(
327
                        intent
Amit Kumar's avatar
Amit Kumar committed
328
                    )
329
                } else {
Amit Kumar's avatar
Amit Kumar committed
330
331
332
333
334
335
                    if (permissionString == null) {
                        permissionString = ""
                    } else {
                        permissionString += ":"
                    }
                    permissionString += cn.flattenToString()
336
337
338

                    // Requires WRITE_SECURE_SETTINGS permission.
                    Settings.Secure.putString(cr, setting, permissionString)
Amit Kumar's avatar
Amit Kumar committed
339
340
                }
            }
341
            Preferences.setNotToAskForNotificationAccess(this)
Amit Kumar's avatar
Amit Kumar committed
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
        }
    }

    private fun handleDeferredResume() {
        mDeferredResumePending = if (hasBeenResumed() && !mStateManager.state.disableInteraction) {
            UiFactory.onLauncherStateOrResumeChanged(this)

            // Process any items that were added while Launcher was away.
            // TODO: Enable it when adding folder support
            /*InstallShortcutReceiver.disableAndFlushInstallQueue(
                InstallShortcutReceiver.FLAG_ACTIVITY_PAUSED, this
            )*/

            // Refresh shortcuts if the permission changed.
            // mModel.refreshShortcutsIfRequired()

            // Set the notification listener and fetch updated notifications when we resume
            NotificationListener.setNotificationsChangedListener(notificationDataProvider)
            false
        } else {
            true
        }
    }

    fun onStateSet(state: LauncherState) {
        if (mDeferredResumePending) {
            handleDeferredResume()
        }
    }

Amit Kumar's avatar
Amit Kumar committed
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
    /**
     * Restores the previous state, if it exists.
     *
     * @param savedState The previous state.
     */
    private fun restoreState(savedState: Bundle?) {
        if (savedState == null) {
            return
        }
        val stateOrdinal =
            savedState.getInt(RUNTIME_STATE, NORMAL.ordinal)
        val stateValues = LauncherState.values()
        val state = stateValues[stateOrdinal]
        if (!state.disableRestore) {
            mStateManager.goToState(state, false /* animated */)
        }
    }

    override fun onEnterAnimationComplete() {
        super.onEnterAnimationComplete()
        UiFactory.onEnterAnimationComplete(this)
        rotationHelper.setCurrentTransitionRequest(REQUEST_NONE)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        val diff = newConfig.diff(mOldConfig)

        if (diff and ActivityInfo.CONFIG_LOCALE != 0) {
Amit Kumar's avatar
Amit Kumar committed
400
            // Folder.setLocaleDependentFields(resources, true /* force */)
Amit Kumar's avatar
Amit Kumar committed
401
402
403
404
            // TODO: Update folder here.
        }

        if (diff and (ActivityInfo.CONFIG_ORIENTATION or ActivityInfo.CONFIG_SCREEN_SIZE) != 0) {
Amit Kumar's avatar
Amit Kumar committed
405
            // onIdpChanged(mDeviceProfile.inv)
Amit Kumar's avatar
Amit Kumar committed
406
407
408
409
410
411
412
413
            // TODO: update device profile here.
        }

        mOldConfig.setTo(newConfig)
        UiFactory.onLauncherStateOrResumeChanged(this)
        super.onConfigurationChanged(newConfig)
    }

414
415
416
417
    private fun setupViews() {
        dragLayer = findViewById(R.id.drag_layer)
        workspace = dragLayer.findViewById(R.id.workspace)
        workspace.initParentViews(dragLayer)
Amit Kumar's avatar
Amit Kumar committed
418
        overviewPanel = findViewById(R.id.overview_panel)
419
        hotseat = findViewById(R.id.hotseat)
420
421
422
        folderContainer = findViewById(R.id.folder_window_container)
        mFolderAppsViewPager = findViewById(R.id.folder_apps)
        mFolderTitleInput = findViewById(R.id.folder_title)
423
424
425
426
        launcherView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        dragLayer.setup(dragController, workspace)
427
        mCancelTouchController = UiFactory.enableLiveUIChanges(this)
428
        workspace.setup(dragController)
Amit Kumar's avatar
Amit Kumar committed
429
        setupWidgetPage()
430
431
432
        workspace.bindAndInitFirstScreen(null)
        dragController.addDragListener(workspace)
        dragController.addDropTarget(workspace)
Amit Kumar's avatar
Amit Kumar committed
433
434
435

        // Setup the drag controller (drop targets have to be added in reverse order in priority)
        dragController.setMoveTarget(workspace)
436
437
    }

Amit Kumar's avatar
Amit Kumar committed
438
    private fun setupWidgetPage() {
439
440
        widgetPage =
            layoutInflater.inflate(R.layout.widgets_page, rootView, false) as InsettableFrameLayout
Amit Kumar's avatar
Amit Kumar committed
441
        rootView.addView(widgetPage)
442
443
444

        widgetContainer = widgetPage.findViewById(R.id.widget_container)

445
446
447
        widgetPage.visibility = View.VISIBLE
        widgetPage.post {
            widgetPage.translationX = -(widgetPage.measuredWidth * 1.00f)
Amit Kumar's avatar
Amit Kumar committed
448
        }
449
        widgetRootView = widgetPage.findViewById(R.id.widgets_scroll_container)
Amit Kumar's avatar
Amit Kumar committed
450
        widgetPage.findViewById<View>(R.id.used_apps_layout).clipToOutline = true
451
        widgetPage.tag = "Widget page"
Amit Kumar's avatar
Amit Kumar committed
452
453
454
455

        // TODO: replace with app predictions
        // Prepare app suggestions view
        // [[BEGIN]]
456
457
458
459
        widgetPage.findViewById<View>(R.id.openUsageAccessSettings).setOnClickListener {
            startActivity(
                Intent(
                    Settings.ACTION_USAGE_ACCESS_SETTINGS
Amit Kumar's avatar
Amit Kumar committed
460
                )
461
462
            )
        }
Amit Kumar's avatar
Amit Kumar committed
463
464
465
466

        // divided by 2 because of left and right padding.
        val padding = (mDeviceProfile.availableWidthPx / 2 - Utilities.pxFromDp(8, this) -
            (2 *
467
                mDeviceProfile.cellWidthPx)).toInt()
Amit Kumar's avatar
Amit Kumar committed
468
469
470
471
472
473
474
475
        widgetPage.findViewById<View>(R.id.suggestedAppGrid).setPadding(padding, 0, padding, 0)
        // [[END]]

        // Prepare search suggestion view
        // [[BEGIN]]
        mSearchInput = widgetPage.findViewById(R.id.search_input)
        val clearSuggestions: ImageView =
            widgetPage.findViewById(R.id.clearSuggestionImageView)
476
        clearSuggestions.setOnClickListener {
Amit Kumar's avatar
Amit Kumar committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
            mSearchInput.setText("")
            mSearchInput.clearFocus()
        }

        mSearchInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.toString().trim { it <= ' ' }.isEmpty()) {
                    clearSuggestions.visibility = View.GONE
                } else {
                    clearSuggestions.visibility = View.VISIBLE
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })
        val suggestionRecyclerView: RecyclerView =
            widgetPage.findViewById(R.id.suggestionRecyclerView)
        val suggestionAdapter = AutoCompleteAdapter(this)
        suggestionRecyclerView.setHasFixedSize(true)
        suggestionRecyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        suggestionRecyclerView.adapter = suggestionAdapter
        val dividerItemDecoration = DividerItemDecoration(
            this,
            DividerItemDecoration.VERTICAL
        )
        suggestionRecyclerView.addItemDecoration(dividerItemDecoration)
        getCompositeDisposable().add(
            mSearchInput.textChanges()
                .debounce(300, TimeUnit.MILLISECONDS)
                .map { obj: CharSequence -> obj.toString() }
                .distinctUntilChanged()
510
                .switchMap { charSequence: String? ->
Amit Kumar's avatar
Amit Kumar committed
511
512
513
514
515
516
517
                    if (charSequence != null && charSequence.isNotEmpty()) {
                        searchForQuery(charSequence)
                    } else {
                        Observable.just(
                            SuggestionsResult(charSequence)
                        )
                    }
518
                }
Amit Kumar's avatar
Amit Kumar committed
519
520
521
522
523
524
525
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(
                    SearchInputDisposableObserver(this, suggestionAdapter, widgetPage)
                )
        )

526
527
528
529
530
        mSearchInput.onFocusChangeListener =
            View.OnFocusChangeListener { v: View, hasFocus: Boolean ->
                if (!hasFocus) {
                    hideKeyboard(v)
                }
Amit Kumar's avatar
Amit Kumar committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
            }

        mSearchInput.setOnEditorActionListener { _: TextView?, action: Int, _: KeyEvent? ->
            if (action == EditorInfo.IME_ACTION_SEARCH) {
                hideKeyboard(mSearchInput)
                runSearch(mSearchInput.text.toString())
                mSearchInput.setText("")
                mSearchInput.clearFocus()
                return@setOnEditorActionListener true
            }
            false
        }
        // [[END]]

        // Prepare edit widgets button
        findViewById<View>(R.id.edit_widgets_button).setOnClickListener { view: View? ->
            startActivity(
                Intent(
                    this,
                    WidgetsActivity::class.java
                )
            )
        }

        // Prepare weather widget view
        // [[BEGIN]]
        findViewById<View>(R.id.weather_setting_imageview).setOnClickListener { v: View? ->
            startActivity(
                Intent(
                    this,
                    WeatherPreferences::class.java
                )
            )
        }

        mWeatherSetupTextView = findViewById<View>(R.id.weather_setup_textview)
        mWeatherPanel = findViewById(R.id.weather_panel)
        mWeatherPanel.setOnClickListener(View.OnClickListener { v: View? ->
            val launchIntent =
                packageManager.getLaunchIntentForPackage(
                    "foundation.e.weather"
                )
            if (launchIntent != null) {
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(launchIntent)
            }
        })
        updateWeatherPanel()

        if (foundation.e.blisslauncher.features.weather.WeatherUtils.isWeatherServiceAvailable(
                this
            )
        ) {
            startService(Intent(this, WeatherSourceListenerService::class.java))
            startService(Intent(this, DeviceStatusService::class.java))
        }

        LocalBroadcastManager.getInstance(this).registerReceiver(
            mWeatherReceiver, IntentFilter(
                WeatherUpdateService.ACTION_UPDATE_FINISHED
            )
        )

        if (!Preferences.useCustomWeatherLocation(this)) {
            if (!WeatherPreferences.hasLocationPermission(this)) {
                val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
                requestPermissions(
                    permissions,
                    WeatherPreferences.LOCATION_PERMISSION_REQUEST_CODE
                )
            } else {
                val lm = getSystemService(LOCATION_SERVICE) as LocationManager
                if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) &&
                    Preferences.getEnableLocation(this)
                ) {
                    showLocationEnableDialog()
                    Preferences.setEnableLocation(this)
                } else {
                    startService(
                        Intent(this, WeatherUpdateService::class.java)
                            .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)
                    )
                }
            }
        } else {
            startService(
                Intent(this, WeatherUpdateService::class.java)
                    .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)
            )
        }
        // [[END]]

623
        val widgetIds: IntArray = mAppWidgetHost.appWidgetIds
Amit Kumar's avatar
Amit Kumar committed
624
625
        Arrays.sort(widgetIds)
        for (id in widgetIds) {
626
            val appWidgetInfo: AppWidgetProviderInfo? = mAppWidgetManager.getAppWidgetInfo(id)
Amit Kumar's avatar
Amit Kumar committed
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
            if (appWidgetInfo != null) {
                val hostView: RoundedWidgetView = mAppWidgetHost.createView(
                    applicationContext, id,
                    appWidgetInfo
                ) as RoundedWidgetView
                hostView.setAppWidget(id, appWidgetInfo)
                getCompositeDisposable().add(DatabaseManager.getManager(this).getHeightOfWidget(id)
                    .subscribeOn(Schedulers.from(AppExecutors.getInstance().diskIO()))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ height: Int ->
                        val widgetView = WidgetViewBuilder.create(this, hostView)
                        if (height != 0) {
                            val minHeight = hostView.appWidgetInfo.minResizeHeight
                            val maxHeight = mDeviceProfile.availableHeightPx * 3 / 4
                            val normalisedDifference = (maxHeight - minHeight) / 100
                            val newHeight = minHeight + normalisedDifference * height
                            widgetView.layoutParams.height = newHeight
                        }
                        addWidgetToContainer(widgetView)
                    }) { obj: Throwable -> obj.printStackTrace() })
            }
        }
    }

    private fun addWidgetToContainer(widgetView: RoundedWidgetView) {
        widgetView.setPadding(0, 0, 0, 0)
653
        widgetContainer.addView(widgetView)
Amit Kumar's avatar
Amit Kumar committed
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
    }

    private fun updateWeatherPanel() {
        if (Preferences.getCachedWeatherInfo(this) == null) {
            mWeatherSetupTextView.visibility = View.VISIBLE
            mWeatherPanel.visibility = View.GONE
            mWeatherSetupTextView.setOnClickListener { v: View? ->
                startActivity(
                    Intent(this, WeatherPreferences::class.java)
                )
            }
            return
        }
        mWeatherSetupTextView.visibility = View.GONE
        mWeatherPanel.visibility = View.VISIBLE
        ForecastBuilder.buildLargePanel(
            this, mWeatherPanel,
            Preferences.getCachedWeatherInfo(this)
        )
    }

    private fun showLocationEnableDialog() {
        val builder = AlertDialog.Builder(this)
        // Build and show the dialog
        builder.setTitle(R.string.weather_retrieve_location_dialog_title)
        builder.setMessage(R.string.weather_retrieve_location_dialog_message)
        builder.setCancelable(false)
        builder.setPositiveButton(
            R.string.weather_retrieve_location_dialog_enable_button
        ) { dialog1, whichButton ->
            val intent =
                Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivityForResult(
                intent, REQUEST_LOCATION_SOURCE_SETTING
            )
        }
        builder.setNegativeButton(R.string.cancel, null)
        enableLocationDialog = builder.create()
        enableLocationDialog?.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_LOCATION_SOURCE_SETTING) {
            val lm = getSystemService(LOCATION_SERVICE) as LocationManager
            if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                Toast.makeText(
                    this, "Set custom location in weather settings.",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                startService(
                    Intent(this, WeatherUpdateService::class.java)
                        .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)
                )
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun searchForQuery(
        charSequence: CharSequence
    ): ObservableSource<SuggestionsResult?>? {
        val launcherItems = searchForLauncherItems(
            charSequence.toString()
        ).subscribeOn(Schedulers.io())
        val networkItems = searchForNetworkItems(
            charSequence
        ).subscribeOn(Schedulers.io())
        return launcherItems.mergeWith(networkItems)
    }

    private fun searchForLauncherItems(
        charSequence: CharSequence
    ): Observable<SuggestionsResult?> {
        val query = charSequence.toString().toLowerCase()
        val suggestionsResult = SuggestionsResult(
            query
        )
        val launcherItems: MutableList<LauncherItem> = ArrayList()
        workspace.mWorkspaceScreens.forEach { gridLayout: GridLayout ->
            for (i in 0 until gridLayout.childCount) {
                val blissFrameLayout = gridLayout.getChildAt(i) as BlissFrameLayout
                val launcherItem = blissFrameLayout.launcherItem
                if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) {
                    val folderItem = launcherItem as FolderItem
                    for (item in folderItem.items) {
                        if (item.title.toString().toLowerCase().contains(query)) {
                            launcherItems.add(item)
                        }
                    }
                } else if (launcherItem.title.toString().toLowerCase().contains(query)) {
                    launcherItems.add(launcherItem)
                }
            }
        }
        val hotseat = getHotseat()
        for (i in 0 until hotseat.childCount) {
            val blissFrameLayout = hotseat.getChildAt(i) as BlissFrameLayout
            val launcherItem = blissFrameLayout.launcherItem
            if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) {
                val folderItem = launcherItem as FolderItem
                for (item in folderItem.items) {
                    if (item.title.toString().toLowerCase().contains(query)) {
                        launcherItems.add(item)
                    }
                }
            } else if (launcherItem.title.toString().toLowerCase().contains(query)) {
                launcherItems.add(launcherItem)
            }
        }
        launcherItems.sortWith(Comparator.comparing { launcherItem: LauncherItem ->
            launcherItem.title.toString().toLowerCase().indexOf(query)
        })
        if (launcherItems.size > 4) {
            suggestionsResult.launcherItems = launcherItems.subList(0, 4)
        } else {
            suggestionsResult.launcherItems = launcherItems
        }
        return Observable.just(suggestionsResult)
            .onErrorReturn { throwable: Throwable? ->
                suggestionsResult.launcherItems = ArrayList()
                suggestionsResult
            }
    }

    private fun searchForNetworkItems(charSequence: CharSequence): Observable<SuggestionsResult?> {
        val query = charSequence.toString().lowercase(Locale.getDefault()).trim { it <= ' ' }
        val suggestionProvider = SearchSuggestionUtil().getSuggestionProvider(
            this
        )
        return suggestionProvider.query(query).toObservable()
    }

    fun hideWidgetResizeContainer() {
        val widgetResizeContainer: RelativeLayout = widgetPage.findViewById<RelativeLayout>(
            R.id.widget_resizer_container
        )
        if (widgetResizeContainer.visibility == View.VISIBLE) {
            currentAnimator?.cancel()
            val set = AnimatorSet()
            set.play(
                ObjectAnimator.ofFloat(
                    widgetResizeContainer, View.Y,
                    mDeviceProfile.availableHeightPx
                        .toFloat()
                )
            )
            set.duration = 200
            set.interpolator = LinearInterpolator()
            set.addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationStart(animation: Animator) {
                    super.onAnimationStart(animation)
                    (widgetPage.findViewById<View>(
                        R.id.widget_resizer_seekbar
                    ) as SeekBar).setOnSeekBarChangeListener(null)
                }

                override fun onAnimationCancel(animation: Animator) {
                    super.onAnimationCancel(animation)
                    currentAnimator = null
                    widgetResizeContainer.visibility = View.VISIBLE
                }

                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    currentAnimator = null
                    widgetResizeContainer.visibility = View.GONE
                    activeRoundedWidgetView?.removeBorder()
                }
            }
            )
            set.start()
            currentAnimator = set
        }
    }

    fun hideKeyboard(view: View) {
        val inputMethodManager = (getSystemService(
            INPUT_METHOD_SERVICE
        ) as InputMethodManager)
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun showKeyboard(view: View?) {
        val inputMethodManager = (getSystemService(
            INPUT_METHOD_SERVICE
        ) as InputMethodManager)
        inputMethodManager.showSoftInput(view, 0)
    }

    private fun runSearch(query: String) {
        val intent = Intent(
            Intent.ACTION_VIEW,
            SearchSuggestionUtil().getUriForQuery(this, query)
        )
        startActivity(intent)
    }

    fun showWidgetResizeContainer(roundedWidgetView: RoundedWidgetView) {
        val widgetResizeContainer: RelativeLayout = widgetPage.findViewById<RelativeLayout>(
            R.id.widget_resizer_container
        )
        if (widgetResizeContainer.visibility != View.VISIBLE) {
            activeRoundedWidgetView = roundedWidgetView
            val seekBar = widgetResizeContainer.findViewById<SeekBar>(R.id.widget_resizer_seekbar)
            if (currentAnimator != null) {
                currentAnimator!!.cancel()
            }
            seekBar.setOnTouchListener { v: View?, event: MotionEvent? ->
                seekBar.parent.requestDisallowInterceptTouchEvent(true)
                false
            }
            val set = AnimatorSet()
            set.play(
                ObjectAnimator.ofFloat(
                    widgetResizeContainer, View.Y,
                    mDeviceProfile.availableHeightPx.toFloat(),
                    mDeviceProfile.availableHeightPx - Utilities.pxFromDp(48, this)
                )
            )
            set.duration = 200
            set.interpolator = LinearInterpolator()
            set.addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationStart(animation: Animator) {
                    super.onAnimationStart(animation)
                    widgetResizeContainer.visibility = View.VISIBLE
                }

                override fun onAnimationCancel(animation: Animator) {
                    super.onAnimationCancel(animation)
                    currentAnimator = null
                    widgetResizeContainer.visibility = View.GONE
                    roundedWidgetView.removeBorder()
                }

                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    currentAnimator = null
                    prepareWidgetResizeSeekBar(seekBar)
                    roundedWidgetView.addBorder()
                }
            }
            )
            set.start()
            currentAnimator = set
        }
    }

    private fun prepareWidgetResizeSeekBar(seekBar: SeekBar) {
        val minHeight = activeRoundedWidgetView!!.appWidgetInfo.minResizeHeight
        val maxHeight = mDeviceProfile.availableHeightPx * 3 / 4
        val normalisedDifference = (maxHeight - minHeight) / 100
        val defaultHeight = activeRoundedWidgetView!!.height
        val currentProgress = (defaultHeight - minHeight) * 100 / (maxHeight - minHeight)
        seekBar.max = 100
        seekBar.progress = currentProgress
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                val newHeight = minHeight + normalisedDifference * progress
915
916
                val layoutParams =
                    activeRoundedWidgetView!!.layoutParams as LinearLayout.LayoutParams
Amit Kumar's avatar
Amit Kumar committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
                layoutParams.height = newHeight
                activeRoundedWidgetView!!.layoutParams = layoutParams
                val newOps = Bundle()
                newOps.putInt(
                    AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,
                    mDeviceProfile.maxWidgetWidth
                )
                newOps.putInt(
                    AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,
                    mDeviceProfile.maxWidgetWidth
                )
                newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, newHeight)
                newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, newHeight)
                activeRoundedWidgetView!!.updateAppWidgetOptions(newOps)
                activeRoundedWidgetView!!.requestLayout()
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                DatabaseManager.getManager(this@TestActivity).saveWidget(
                    activeRoundedWidgetView!!.appWidgetId, seekBar.progress
                )
            }
        })
    }

943
944
945
946
    override fun <T : View> findViewById(id: Int): T {
        return launcherView.findViewById(id)
    }

Amit Kumar's avatar
Amit Kumar committed
947
948
    fun getRotationHelper() = rotationHelper

Amit Kumar's avatar
Amit Kumar committed
949
950
    private fun initDeviceProfile(idp: InvariantDeviceProfile) {
        // Load device specific profile
951
        mDeviceProfile = idp.getDeviceProfile(this)
Amit Kumar's avatar
Amit Kumar committed
952
953
954
955
956
957
958
        if (isInMultiWindowMode) {
            val display = windowManager.defaultDisplay
            val mwSize = Point()
            display.getSize(mwSize)
            mDeviceProfile = mDeviceProfile.getMultiWindowProfile(this, mwSize)
        }
        mRotationMode = RotationMode.NORMAL
Amit Kumar's avatar
Amit Kumar committed
959
960
961
        onDeviceProfileInitiated()
    }

Amit Kumar's avatar
Amit Kumar committed
962
963
964
965
966
967
    override fun onPause() {
        super.onPause()
        dragController.cancelDrag()
        dragController.resetLastGestureUpTime()
    }

968
969
    override fun onResume() {
        super.onResume()
Amit Kumar's avatar
Amit Kumar committed
970
971
972
        mHandler.removeCallbacks(mHandleDeferredResume)
        Utilities.postAsyncCallback(mHandler, mHandleDeferredResume)

973
974
975
976
977
978
979
980
        if (mOnResumeCallbacks.isNotEmpty()) {
            val resumeCallbacks = ArrayList(mOnResumeCallbacks)
            mOnResumeCallbacks.clear()
            for (i in resumeCallbacks.indices.reversed()) {
                resumeCallbacks[i].onLauncherResume()
            }
            resumeCallbacks.clear()
        }
Amit Kumar's avatar
Amit Kumar committed
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

        if (mWeatherPanel != null) {
            updateWeatherPanel()
        }

        if (widgetPage != null) {
            refreshSuggestedApps(widgetPage, forceRefreshSuggestedApps)
        }

        if (widgetContainer != null) {
            val widgetManager = WidgetManager.getInstance()
            var id = widgetManager.dequeRemoveId()
            while (id != null) {
                for (i in 0 until widgetContainer.childCount) {
                    if (widgetContainer.getChildAt(i) is RoundedWidgetView) {
                        val appWidgetHostView = widgetContainer.getChildAt(i) as RoundedWidgetView
                        if (appWidgetHostView.appWidgetId == id) {
                            widgetContainer.removeViewAt(i)
                            DatabaseManager.getManager(this).removeWidget(id)
                            break
For faster browsing, not all history is shown. View entire blame