TestActivity.kt 68.4 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.Process
32
33
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
Amit Kumar's avatar
Amit Kumar committed
34
35
36
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
37
38
import android.util.Log
import android.view.ContextThemeWrapper
Amit Kumar's avatar
Amit Kumar committed
39
import android.view.KeyEvent
40
import android.view.LayoutInflater
Amit Kumar's avatar
Amit Kumar committed
41
import android.view.MotionEvent
42
import android.view.View
Amit Kumar's avatar
Amit Kumar committed
43
import android.view.ViewGroup
44
import android.view.animation.AccelerateDecelerateInterpolator
Amit Kumar's avatar
Amit Kumar committed
45
46
47
48
49
50
51
52
53
54
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
55
import androidx.core.view.isVisible
Amit Kumar's avatar
Amit Kumar committed
56
57
58
59
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
60
import androidx.viewpager.widget.ViewPager
Amit Kumar's avatar
Amit Kumar committed
61
import com.jakewharton.rxbinding3.widget.textChanges
Amit Kumar's avatar
Amit Kumar committed
62
import foundation.e.blisslauncher.BlissLauncher
63
import foundation.e.blisslauncher.R
Amit Kumar's avatar
Amit Kumar committed
64
65
import foundation.e.blisslauncher.core.Preferences
import foundation.e.blisslauncher.core.Utilities
Amit Kumar's avatar
Amit Kumar committed
66
import foundation.e.blisslauncher.core.customviews.AbstractFloatingView
Amit Kumar's avatar
Amit Kumar committed
67
68
69
import foundation.e.blisslauncher.core.customviews.BlissFrameLayout
import foundation.e.blisslauncher.core.customviews.BlissInput
import foundation.e.blisslauncher.core.customviews.InsettableFrameLayout
70
import foundation.e.blisslauncher.core.customviews.LauncherPagedView
Amit Kumar's avatar
Amit Kumar committed
71
72
73
74
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
75
import foundation.e.blisslauncher.core.database.model.ApplicationItem
Amit Kumar's avatar
Amit Kumar committed
76
import foundation.e.blisslauncher.core.database.model.FolderItem
Amit Kumar's avatar
Amit Kumar committed
77
import foundation.e.blisslauncher.core.database.model.LauncherItem
78
import foundation.e.blisslauncher.core.database.model.ShortcutItem
Amit Kumar's avatar
Amit Kumar committed
79
80
import foundation.e.blisslauncher.core.executors.AppExecutors
import foundation.e.blisslauncher.core.utils.AppUtils
Amit Kumar's avatar
Amit Kumar committed
81
import foundation.e.blisslauncher.core.utils.Constants
Amit Kumar's avatar
Amit Kumar committed
82
import foundation.e.blisslauncher.core.utils.ListUtil
Amit Kumar's avatar
Amit Kumar committed
83
import foundation.e.blisslauncher.core.utils.PackageUserKey
Amit Kumar's avatar
Amit Kumar committed
84
import foundation.e.blisslauncher.core.utils.UserHandle
85
import foundation.e.blisslauncher.features.folder.FolderPagerAdapter
Amit Kumar's avatar
Amit Kumar committed
86
import foundation.e.blisslauncher.features.launcher.Hotseat
Amit Kumar's avatar
Amit Kumar committed
87
import foundation.e.blisslauncher.features.launcher.SearchInputDisposableObserver
Amit Kumar's avatar
Amit Kumar committed
88
89
90
import foundation.e.blisslauncher.features.notification.DotInfo
import foundation.e.blisslauncher.features.notification.NotificationDataProvider
import foundation.e.blisslauncher.features.notification.NotificationListener
91
92
import foundation.e.blisslauncher.features.shortcuts.DeepShortcutManager
import foundation.e.blisslauncher.features.shortcuts.ShortcutKey
Amit Kumar's avatar
Amit Kumar committed
93
94
95
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
96
97
import foundation.e.blisslauncher.features.test.LauncherState.*
import foundation.e.blisslauncher.features.test.RotationHelper.REQUEST_NONE
98
99
import foundation.e.blisslauncher.features.test.dragndrop.DragController
import foundation.e.blisslauncher.features.test.dragndrop.DragLayer
Amit Kumar's avatar
Amit Kumar committed
100
import foundation.e.blisslauncher.features.test.graphics.RotationMode
Amit Kumar's avatar
Amit Kumar committed
101
102
103
104
105
106
107
108
109
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
110
import foundation.e.blisslauncher.features.widgets.WidgetsRootView
Amit Kumar's avatar
Amit Kumar committed
111
import foundation.e.blisslauncher.uioverrides.OverlayCallbackImpl
112
import foundation.e.blisslauncher.uioverrides.UiFactory
Amit Kumar's avatar
Amit Kumar committed
113
114
import io.reactivex.Observable
import io.reactivex.ObservableSource
Amit Kumar's avatar
Amit Kumar committed
115
116
117
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
Amit Kumar's avatar
Amit Kumar committed
118
import io.reactivex.schedulers.Schedulers
119
import java.net.URISyntaxException
120
import java.util.ArrayList
Amit Kumar's avatar
Amit Kumar committed
121
122
123
124
import java.util.Arrays
import java.util.Comparator
import java.util.Locale
import java.util.concurrent.TimeUnit
Amit Kumar's avatar
Amit Kumar committed
125
import java.util.function.Predicate
126
import me.relex.circleindicator.CircleIndicator
127

Amit Kumar's avatar
Amit Kumar committed
128
class TestActivity : BaseDraggingActivity(), AutoCompleteAdapter.OnSuggestionClickListener {
129

130
131
132
    private lateinit var widgetRootView: WidgetsRootView
    private lateinit var overlayCallbackImpl: OverlayCallbackImpl

133
134
    // Folder start scale
    private var startScaleFinal: Float = 0f
135
    private var mCancelTouchController: Runnable? = null
Amit Kumar's avatar
Amit Kumar committed
136
137
    private var mOnResumeCallback: OnResumeCallback? = null
    private lateinit var mAppTransitionManager: LauncherAppTransitionManager
138
    lateinit var dragController: DragController
139
    private lateinit var mOldConfig: Configuration
Amit Kumar's avatar
Amit Kumar committed
140
141
    private var mCompositeDisposable: CompositeDisposable? = null

Amit Kumar's avatar
Amit Kumar committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    // 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"

157
158
159
160
    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
161
162
163
164
165
    private lateinit var widgetPage: InsettableFrameLayout

    private lateinit var mSearchInput: BlissInput

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

Amit Kumar's avatar
Amit Kumar committed
167
    private lateinit var rotationHelper: RotationHelper
Amit Kumar's avatar
Amit Kumar committed
168
    private var mRotationMode = RotationMode.NORMAL
Amit Kumar's avatar
Amit Kumar committed
169
170
171
172
173
    private lateinit var mStateManager: LauncherStateManager

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

174
175
    private lateinit var folderContainer: RelativeLayout

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

Amit Kumar's avatar
Amit Kumar committed
178
179
    private lateinit var mAppWidgetManager: AppWidgetManager
    private lateinit var mAppWidgetHost: WidgetHost
180
    private lateinit var widgetContainer: LinearLayout
Amit Kumar's avatar
Amit Kumar committed
181
182
183
184
185
186
187
188
189
190
191
192
193
    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

194
195
196
197
198
199
200
    private var activeFolder: FolderItem? = null
    private var activeFolderView: IconTextView? = null
    private var activeFolderStartBounds = Rect()

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

Amit Kumar's avatar
Amit Kumar committed
201
202
203
204
205
206
207
208
    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
209
210
211
212
213
    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
214
215
    private val TAG = "TestActivity"

216
    override fun onCreate(savedInstanceState: Bundle?) {
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        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")

237
        super.onCreate(savedInstanceState)
238
239
        TraceHelper.partitionSection("Launcher-onCreate", "super call")

Amit Kumar's avatar
Amit Kumar committed
240
241
        val app = LauncherAppState.getInstance(this)
        app.launcher = this
242
        mOldConfig = Configuration(resources.configuration)
Amit Kumar's avatar
Amit Kumar committed
243
244
245
246

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

Amit Kumar's avatar
Amit Kumar committed
247
        initDeviceProfile(BlissLauncher.getApplication(this).invariantDeviceProfile)
248
        dragController = DragController(this)
249
        rotationHelper = RotationHelper(this)
Amit Kumar's avatar
Amit Kumar committed
250
        mStateManager = LauncherStateManager(this)
251
252
        launcherView = LayoutInflater.from(this).inflate(R.layout.activity_test, null)
        setupViews()
Amit Kumar's avatar
Amit Kumar committed
253

Amit Kumar's avatar
Amit Kumar committed
254
255
256
257
        askForNotificationIfFirstTime()

        notificationDataProvider = NotificationDataProvider(this)

Amit Kumar's avatar
Amit Kumar committed
258
        mAppTransitionManager = LauncherAppTransitionManager.newInstance(this)
259

Amit Kumar's avatar
Amit Kumar committed
260
261
262
263
264
265
266
        val internalStateHandled = InternalStateHandler.handleCreate(this, intent)
        if (internalStateHandled) {
            savedInstanceState?.remove(RUNTIME_STATE)
        }
        restoreState(savedInstanceState)
        mStateManager.reapplyState()

267
        setContentView(launcherView)
Amit Kumar's avatar
Amit Kumar committed
268
269
270
271
        rootView.dispatchInsets()

        systemUiController.updateUiState(
            SystemUiController.UI_STATE_BASE_WINDOW,
Amit Kumar's avatar
Amit Kumar committed
272
            true
Amit Kumar's avatar
Amit Kumar committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        )
        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
288
        createOrUpdateIconGrid()
289
290
        overlayCallbackImpl = OverlayCallbackImpl(this)
        setLauncherOverlay(overlayCallbackImpl)
Amit Kumar's avatar
Amit Kumar committed
291
292
    }

Amit Kumar's avatar
Amit Kumar committed
293
294
295
296
297
    private fun askForNotificationIfFirstTime() {
        if (Preferences.shouldAskForNotificationAccess(this)) {
            val cr = contentResolver
            val setting = "enabled_notification_listeners"
            var permissionString = Settings.Secure.getString(cr, setting)
298
299
            val cn = ComponentName(this, NotificationListener::class.java)

300
301
302
303
            val enabled =
                permissionString != null && (permissionString.contains(cn.flattenToString()) || permissionString.contains(
                    cn.flattenToShortString()
                ))
304
305

            if (!enabled) {
306
307
308
309
                val launcherApps: LauncherApps =
                    getSystemService(LAUNCHER_APPS_SERVICE) as LauncherApps
                val launcherInfo =
                    launcherApps.getApplicationInfo(packageName, 0, Process.myUserHandle())
310
                if (launcherInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
311
312
313
314
315
316
                    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
317
                    startActivity(
318
                        intent
Amit Kumar's avatar
Amit Kumar committed
319
                    )
320
                } else {
Amit Kumar's avatar
Amit Kumar committed
321
322
323
324
325
326
                    if (permissionString == null) {
                        permissionString = ""
                    } else {
                        permissionString += ":"
                    }
                    permissionString += cn.flattenToString()
327
328
329

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

    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
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
    /**
     * 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
391
            // Folder.setLocaleDependentFields(resources, true /* force */)
Amit Kumar's avatar
Amit Kumar committed
392
393
394
395
            // TODO: Update folder here.
        }

        if (diff and (ActivityInfo.CONFIG_ORIENTATION or ActivityInfo.CONFIG_SCREEN_SIZE) != 0) {
Amit Kumar's avatar
Amit Kumar committed
396
            // onIdpChanged(mDeviceProfile.inv)
Amit Kumar's avatar
Amit Kumar committed
397
398
399
400
401
402
403
404
            // TODO: update device profile here.
        }

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

405
406
407
408
    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
409
        overviewPanel = findViewById(R.id.overview_panel)
410
        hotseat = findViewById(R.id.hotseat)
411
412
413
        folderContainer = findViewById(R.id.folder_window_container)
        mFolderAppsViewPager = findViewById(R.id.folder_apps)
        mFolderTitleInput = findViewById(R.id.folder_title)
414
415
416
417
        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)
418
        mCancelTouchController = UiFactory.enableLiveUIChanges(this)
419
        workspace.setup(dragController)
Amit Kumar's avatar
Amit Kumar committed
420
        setupWidgetPage()
421
422
423
        workspace.bindAndInitFirstScreen(null)
        dragController.addDragListener(workspace)
        dragController.addDropTarget(workspace)
Amit Kumar's avatar
Amit Kumar committed
424
425
426

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

Amit Kumar's avatar
Amit Kumar committed
429
    private fun setupWidgetPage() {
430
431
        widgetPage =
            layoutInflater.inflate(R.layout.widgets_page, rootView, false) as InsettableFrameLayout
Amit Kumar's avatar
Amit Kumar committed
432
        rootView.addView(widgetPage)
433
434
435

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

436
437
438
        widgetPage.visibility = View.VISIBLE
        widgetPage.post {
            widgetPage.translationX = -(widgetPage.measuredWidth * 1.00f)
Amit Kumar's avatar
Amit Kumar committed
439
        }
440
        widgetRootView = widgetPage.findViewById(R.id.widgets_scroll_container)
Amit Kumar's avatar
Amit Kumar committed
441
        widgetPage.findViewById<View>(R.id.used_apps_layout).clipToOutline = true
442
        widgetPage.tag = "Widget page"
Amit Kumar's avatar
Amit Kumar committed
443
444
445
446

        // TODO: replace with app predictions
        // Prepare app suggestions view
        // [[BEGIN]]
447
448
449
450
        widgetPage.findViewById<View>(R.id.openUsageAccessSettings).setOnClickListener {
            startActivity(
                Intent(
                    Settings.ACTION_USAGE_ACCESS_SETTINGS
Amit Kumar's avatar
Amit Kumar committed
451
                )
452
453
            )
        }
Amit Kumar's avatar
Amit Kumar committed
454
455
456
457

        // divided by 2 because of left and right padding.
        val padding = (mDeviceProfile.availableWidthPx / 2 - Utilities.pxFromDp(8, this) -
            (2 *
458
                mDeviceProfile.cellWidthPx)).toInt()
Amit Kumar's avatar
Amit Kumar committed
459
460
461
462
463
464
465
466
        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)
467
        clearSuggestions.setOnClickListener {
Amit Kumar's avatar
Amit Kumar committed
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
500
            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()
501
                .switchMap { charSequence: String? ->
Amit Kumar's avatar
Amit Kumar committed
502
503
504
505
506
507
508
                    if (charSequence != null && charSequence.isNotEmpty()) {
                        searchForQuery(charSequence)
                    } else {
                        Observable.just(
                            SuggestionsResult(charSequence)
                        )
                    }
509
                }
Amit Kumar's avatar
Amit Kumar committed
510
511
512
513
514
515
516
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(
                    SearchInputDisposableObserver(this, suggestionAdapter, widgetPage)
                )
        )

517
518
519
520
521
        mSearchInput.onFocusChangeListener =
            View.OnFocusChangeListener { v: View, hasFocus: Boolean ->
                if (!hasFocus) {
                    hideKeyboard(v)
                }
Amit Kumar's avatar
Amit Kumar committed
522
523
524
525
526
527
528
529
530
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
            }

        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]]

614
        val widgetIds: IntArray = mAppWidgetHost.appWidgetIds
Amit Kumar's avatar
Amit Kumar committed
615
616
        Arrays.sort(widgetIds)
        for (id in widgetIds) {
617
            val appWidgetInfo: AppWidgetProviderInfo? = mAppWidgetManager.getAppWidgetInfo(id)
Amit Kumar's avatar
Amit Kumar committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
            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)
644
        widgetContainer.addView(widgetView)
Amit Kumar's avatar
Amit Kumar committed
645
646
647
648
649
650
651
652
653
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
    }

    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
906
907
                val layoutParams =
                    activeRoundedWidgetView!!.layoutParams as LinearLayout.LayoutParams
Amit Kumar's avatar
Amit Kumar committed
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
                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
                )
            }
        })
    }

934
935
936
937
    override fun <T : View> findViewById(id: Int): T {
        return launcherView.findViewById(id)
    }

Amit Kumar's avatar
Amit Kumar committed
938
939
    fun getRotationHelper() = rotationHelper

Amit Kumar's avatar
Amit Kumar committed
940
941
    private fun initDeviceProfile(idp: InvariantDeviceProfile) {
        // Load device specific profile
942
        mDeviceProfile = idp.getDeviceProfile(this)
Amit Kumar's avatar
Amit Kumar committed
943
944
945
946
947
948
949
        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
950
951
952
        onDeviceProfileInitiated()
    }

Amit Kumar's avatar
Amit Kumar committed
953
954
955
956
957
958
    override fun onPause() {
        super.onPause()
        dragController.cancelDrag()
        dragController.resetLastGestureUpTime()
    }

959
960
    override fun onResume() {
        super.onResume()
Amit Kumar's avatar
Amit Kumar committed
961
962
963
        mHandler.removeCallbacks(mHandleDeferredResume)
        Utilities.postAsyncCallback(mHandler, mHandleDeferredResume)

964
965
966
967
968
969
970
971
        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
972
973
974
975
976
977
978
979
980
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
                        }
                    }
                }
                id = widgetManager.dequeRemoveId()
            }
            var widgetView = widgetManager.dequeAddWidgetView()
            while (widgetView != null) {
                widgetView = WidgetViewBuilder.create(this, widgetView)
                addWidgetToContainer(widgetView)