TestActivity.kt 75.6 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
import android.app.AlertDialog
Amit Kumar's avatar
Amit Kumar committed
11
import android.app.WallpaperManager
Amit Kumar's avatar
Amit Kumar committed
12
13
14
15
import android.app.usage.UsageStats
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.BroadcastReceiver
Amit Kumar's avatar
Amit Kumar committed
16
import android.content.ComponentName
Amit Kumar's avatar
Amit Kumar committed
17
18
import android.content.Context
import android.content.ContextWrapper
Amit Kumar's avatar
Amit Kumar committed
19
import android.content.Intent
Amit Kumar's avatar
Amit Kumar committed
20
import android.content.IntentFilter
Amit Kumar's avatar
Amit Kumar committed
21
import android.content.pm.ActivityInfo
22
23
24
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherActivityInfo
import android.content.pm.LauncherApps
Amit Kumar's avatar
Amit Kumar committed
25
import android.content.pm.PackageManager
26
import android.content.res.Configuration
Amit Kumar's avatar
Amit Kumar committed
27
import android.graphics.Point
28
import android.graphics.Rect
Amit Kumar's avatar
Amit Kumar committed
29
import android.location.LocationManager
30
import android.net.Uri
31
import android.os.Bundle
Amit Kumar's avatar
Amit Kumar committed
32
import android.os.Handler
33
import android.os.Looper
34
import android.os.Process
35
36
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
Amit Kumar's avatar
Amit Kumar committed
37
38
import android.provider.Settings
import android.text.Editable
39
40
import android.text.InputType
import android.text.Selection
Amit Kumar's avatar
Amit Kumar committed
41
import android.text.TextWatcher
42
43
import android.util.Log
import android.view.ContextThemeWrapper
Amit Kumar's avatar
Amit Kumar committed
44
import android.view.KeyEvent
45
import android.view.LayoutInflater
Amit Kumar's avatar
Amit Kumar committed
46
import android.view.MotionEvent
47
import android.view.View
Amit Kumar's avatar
Amit Kumar committed
48
import android.view.View.OnAttachStateChangeListener
49
import android.view.View.OnFocusChangeListener
Amit Kumar's avatar
Amit Kumar committed
50
import android.view.ViewGroup
51
import android.view.animation.AccelerateDecelerateInterpolator
Amit Kumar's avatar
Amit Kumar committed
52
53
54
55
56
57
58
59
60
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
61
import android.widget.TextView.OnEditorActionListener
Amit Kumar's avatar
Amit Kumar committed
62
import android.widget.Toast
Amit Kumar's avatar
Amit Kumar committed
63
import androidx.core.app.ActivityCompat
Amit Kumar's avatar
Amit Kumar committed
64
import androidx.core.view.isVisible
Amit Kumar's avatar
Amit Kumar committed
65
66
67
68
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
69
import androidx.viewpager.widget.ViewPager
Amit Kumar's avatar
Amit Kumar committed
70
import com.jakewharton.rxbinding3.widget.textChanges
Amit Kumar's avatar
Amit Kumar committed
71
import foundation.e.blisslauncher.BlissLauncher
72
import foundation.e.blisslauncher.R
Amit Kumar's avatar
Amit Kumar committed
73
74
import foundation.e.blisslauncher.core.Preferences
import foundation.e.blisslauncher.core.Utilities
Amit Kumar's avatar
Amit Kumar committed
75
76
import foundation.e.blisslauncher.core.blur.BlurWallpaperProvider
import foundation.e.blisslauncher.core.broadcast.WallpaperChangeReceiver
Amit Kumar's avatar
Amit Kumar committed
77
import foundation.e.blisslauncher.core.customviews.AbstractFloatingView
Amit Kumar's avatar
Amit Kumar committed
78
79
import foundation.e.blisslauncher.core.customviews.BlissFrameLayout
import foundation.e.blisslauncher.core.customviews.BlissInput
80
import foundation.e.blisslauncher.core.customviews.FolderTitleInput
81
import foundation.e.blisslauncher.core.customviews.LauncherPagedView
Amit Kumar's avatar
Amit Kumar committed
82
83
84
85
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
86
import foundation.e.blisslauncher.core.database.model.ApplicationItem
Amit Kumar's avatar
Amit Kumar committed
87
import foundation.e.blisslauncher.core.database.model.FolderItem
Amit Kumar's avatar
Amit Kumar committed
88
import foundation.e.blisslauncher.core.database.model.LauncherItem
89
import foundation.e.blisslauncher.core.database.model.ShortcutItem
Amit Kumar's avatar
Amit Kumar committed
90
91
import foundation.e.blisslauncher.core.executors.AppExecutors
import foundation.e.blisslauncher.core.utils.AppUtils
Amit Kumar's avatar
Amit Kumar committed
92
import foundation.e.blisslauncher.core.utils.Constants
93
94
import foundation.e.blisslauncher.core.utils.IntSet
import foundation.e.blisslauncher.core.utils.IntegerArray
Amit Kumar's avatar
Amit Kumar committed
95
import foundation.e.blisslauncher.core.utils.ListUtil
Amit Kumar's avatar
Amit Kumar committed
96
import foundation.e.blisslauncher.core.utils.PackageUserKey
Amit Kumar's avatar
Amit Kumar committed
97
import foundation.e.blisslauncher.core.utils.UserHandle
98
import foundation.e.blisslauncher.features.folder.FolderPagerAdapter
Amit Kumar's avatar
Amit Kumar committed
99
import foundation.e.blisslauncher.features.launcher.Hotseat
Amit Kumar's avatar
Amit Kumar committed
100
import foundation.e.blisslauncher.features.launcher.SearchInputDisposableObserver
Amit Kumar's avatar
Amit Kumar committed
101
102
103
import foundation.e.blisslauncher.features.notification.DotInfo
import foundation.e.blisslauncher.features.notification.NotificationDataProvider
import foundation.e.blisslauncher.features.notification.NotificationListener
104
105
import foundation.e.blisslauncher.features.shortcuts.DeepShortcutManager
import foundation.e.blisslauncher.features.shortcuts.ShortcutKey
Amit Kumar's avatar
Amit Kumar committed
106
107
108
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
109
110
import foundation.e.blisslauncher.features.test.LauncherState.*
import foundation.e.blisslauncher.features.test.RotationHelper.REQUEST_NONE
111
112
import foundation.e.blisslauncher.features.test.dragndrop.DragController
import foundation.e.blisslauncher.features.test.dragndrop.DragLayer
Amit Kumar's avatar
Amit Kumar committed
113
import foundation.e.blisslauncher.features.test.graphics.RotationMode
Amit Kumar's avatar
Amit Kumar committed
114
115
116
117
118
119
120
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
Amit Kumar's avatar
Amit Kumar committed
121
import foundation.e.blisslauncher.features.widgets.WidgetPageLayer
Amit Kumar's avatar
Amit Kumar committed
122
123
import foundation.e.blisslauncher.features.widgets.WidgetViewBuilder
import foundation.e.blisslauncher.features.widgets.WidgetsActivity
124
import foundation.e.blisslauncher.features.widgets.WidgetsRootView
Amit Kumar's avatar
Amit Kumar committed
125
import foundation.e.blisslauncher.uioverrides.OverlayCallbackImpl
126
import foundation.e.blisslauncher.uioverrides.UiFactory
Amit Kumar's avatar
Amit Kumar committed
127
128
import io.reactivex.Observable
import io.reactivex.ObservableSource
Amit Kumar's avatar
Amit Kumar committed
129
130
131
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
Amit Kumar's avatar
Amit Kumar committed
132
import io.reactivex.schedulers.Schedulers
133
import java.net.URISyntaxException
134
import java.util.ArrayList
Amit Kumar's avatar
Amit Kumar committed
135
136
137
138
import java.util.Arrays
import java.util.Comparator
import java.util.Locale
import java.util.concurrent.TimeUnit
Amit Kumar's avatar
Amit Kumar committed
139
import java.util.function.Predicate
Amit Kumar's avatar
Amit Kumar committed
140
import me.relex.circleindicator.CircleIndicator
141

Amit Kumar's avatar
Amit Kumar committed
142
class TestActivity : BaseDraggingActivity(), AutoCompleteAdapter.OnSuggestionClickListener,
143
144
    LauncherModel.Callbacks, OnFocusChangeListener, FolderTitleInput.OnBackKeyListener,
    OnEditorActionListener {
145

146
    private var mIsEditingName: Boolean = false
Amit Kumar's avatar
Amit Kumar committed
147
    private var mModel: LauncherModel? = null
148
149
150
    private lateinit var widgetRootView: WidgetsRootView
    private lateinit var overlayCallbackImpl: OverlayCallbackImpl

151
152
    // Folder start scale
    private var startScaleFinal: Float = 0f
153
    private var mCancelTouchController: Runnable? = null
Amit Kumar's avatar
Amit Kumar committed
154
155
    private var mOnResumeCallback: OnResumeCallback? = null
    private lateinit var mAppTransitionManager: LauncherAppTransitionManager
156
    lateinit var dragController: DragController
157
    private lateinit var mOldConfig: Configuration
Amit Kumar's avatar
Amit Kumar committed
158
159
    private var mCompositeDisposable: CompositeDisposable? = null

Amit Kumar's avatar
Amit Kumar committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    // 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"

175
176
177
178
    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
179
    private lateinit var widgetPage: WidgetPageLayer
Amit Kumar's avatar
Amit Kumar committed
180
181
182
183

    private lateinit var mSearchInput: BlissInput

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

Amit Kumar's avatar
Amit Kumar committed
185
    private lateinit var rotationHelper: RotationHelper
Amit Kumar's avatar
Amit Kumar committed
186
    private var mRotationMode = RotationMode.NORMAL
Amit Kumar's avatar
Amit Kumar committed
187
188
189
190
191
    private lateinit var mStateManager: LauncherStateManager

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

192
193
    private lateinit var folderContainer: RelativeLayout

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

Amit Kumar's avatar
Amit Kumar committed
196
197
    private lateinit var mAppWidgetManager: AppWidgetManager
    private lateinit var mAppWidgetHost: WidgetHost
198
    private lateinit var widgetContainer: LinearLayout
Amit Kumar's avatar
Amit Kumar committed
199
200
201
202
203
204
205
206
207
208
209
210
211
    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

212
213
214
215
216
    private var activeFolder: FolderItem? = null
    private var activeFolderView: IconTextView? = null
    private var activeFolderStartBounds = Rect()

    private var mFolderAppsViewPager: ViewPager? = null
217
    private lateinit var mFolderTitleInput: FolderTitleInput
218

219
220
    private val mainHandler = Handler(Looper.getMainLooper())

Amit Kumar's avatar
Amit Kumar committed
221
222
223
224
225
226
227
228
    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
229
230
231
232
233
    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
234
235
    private val TAG = "TestActivity"

Amit Kumar's avatar
Amit Kumar committed
236
237
    private var wallpaperChangeReceiver: WallpaperChangeReceiver? = null

238
    override fun onCreate(savedInstanceState: Bundle?) {
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        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")

259
        super.onCreate(savedInstanceState)
260
261
        TraceHelper.partitionSection("Launcher-onCreate", "super call")

Amit Kumar's avatar
Amit Kumar committed
262
        val app = LauncherAppState.getInstance(this)
Amit Kumar's avatar
Amit Kumar committed
263
        mModel = app.setLauncher(this)
264
        mOldConfig = Configuration(resources.configuration)
Amit Kumar's avatar
Amit Kumar committed
265
266
267
268

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

Amit Kumar's avatar
Amit Kumar committed
269
        initDeviceProfile(BlissLauncher.getApplication(this).invariantDeviceProfile)
Amit Kumar's avatar
Amit Kumar committed
270
271
        val wm = getSystemService(WALLPAPER_SERVICE) as WallpaperManager
        wm.suggestDesiredDimensions(mDeviceProfile.widthPx, mDeviceProfile.heightPx)
272
        dragController = DragController(this)
273
        rotationHelper = RotationHelper(this)
Amit Kumar's avatar
Amit Kumar committed
274
        mStateManager = LauncherStateManager(this)
275
276
        launcherView = LayoutInflater.from(this).inflate(R.layout.activity_test, null)
        setupViews()
Amit Kumar's avatar
Amit Kumar committed
277

Amit Kumar's avatar
Amit Kumar committed
278
279
280
281
        askForNotificationIfFirstTime()

        notificationDataProvider = NotificationDataProvider(this)

Amit Kumar's avatar
Amit Kumar committed
282
        mAppTransitionManager = LauncherAppTransitionManager.newInstance(this)
283

Amit Kumar's avatar
Amit Kumar committed
284
285
286
287
288
289
290
        val internalStateHandled = InternalStateHandler.handleCreate(this, intent)
        if (internalStateHandled) {
            savedInstanceState?.remove(RUNTIME_STATE)
        }
        restoreState(savedInstanceState)
        mStateManager.reapplyState()

291
        setContentView(launcherView)
Amit Kumar's avatar
Amit Kumar committed
292
293
294
295
        rootView.dispatchInsets()

        systemUiController.updateUiState(
            SystemUiController.UI_STATE_BASE_WINDOW,
Amit Kumar's avatar
Amit Kumar committed
296
            false
Amit Kumar's avatar
Amit Kumar committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
        )
        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
312
313
314
315
316
317
318
319
320
321
322

        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                STORAGE_PERMISSION_REQUEST_CODE
            )
        }
Amit Kumar's avatar
Amit Kumar committed
323
        createOrUpdateIconGrid()
324
325
        overlayCallbackImpl = OverlayCallbackImpl(this)
        setLauncherOverlay(overlayCallbackImpl)
Amit Kumar's avatar
Amit Kumar committed
326
327
    }

Amit Kumar's avatar
Amit Kumar committed
328
329
330
331
332
    private fun askForNotificationIfFirstTime() {
        if (Preferences.shouldAskForNotificationAccess(this)) {
            val cr = contentResolver
            val setting = "enabled_notification_listeners"
            var permissionString = Settings.Secure.getString(cr, setting)
333
334
            val cn = ComponentName(this, NotificationListener::class.java)

335
336
337
338
            val enabled =
                permissionString != null && (permissionString.contains(cn.flattenToString()) || permissionString.contains(
                    cn.flattenToShortString()
                ))
339
340

            if (!enabled) {
341
342
343
344
                val launcherApps: LauncherApps =
                    getSystemService(LAUNCHER_APPS_SERVICE) as LauncherApps
                val launcherInfo =
                    launcherApps.getApplicationInfo(packageName, 0, Process.myUserHandle())
345
                if (launcherInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
346
347
348
349
350
351
                    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
352
                    startActivity(
353
                        intent
Amit Kumar's avatar
Amit Kumar committed
354
                    )
355
                } else {
Amit Kumar's avatar
Amit Kumar committed
356
357
358
359
360
361
                    if (permissionString == null) {
                        permissionString = ""
                    } else {
                        permissionString += ":"
                    }
                    permissionString += cn.flattenToString()
362
363
364

                    // Requires WRITE_SECURE_SETTINGS permission.
                    Settings.Secure.putString(cr, setting, permissionString)
Amit Kumar's avatar
Amit Kumar committed
365
366
                }
            }
367
            Preferences.setNotToAskForNotificationAccess(this)
Amit Kumar's avatar
Amit Kumar committed
368
369
370
371
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
        }
    }

    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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    /**
     * 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
426
            // Folder.setLocaleDependentFields(resources, true /* force */)
Amit Kumar's avatar
Amit Kumar committed
427
428
429
430
            // TODO: Update folder here.
        }

        if (diff and (ActivityInfo.CONFIG_ORIENTATION or ActivityInfo.CONFIG_SCREEN_SIZE) != 0) {
Amit Kumar's avatar
Amit Kumar committed
431
            // onIdpChanged(mDeviceProfile.inv)
Amit Kumar's avatar
Amit Kumar committed
432
433
434
435
436
437
438
439
            // TODO: update device profile here.
        }

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

440
441
442
443
    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
444
        overviewPanel = findViewById(R.id.overview_panel)
445
        hotseat = findViewById(R.id.hotseat)
446
447
448
        folderContainer = findViewById(R.id.folder_window_container)
        mFolderAppsViewPager = findViewById(R.id.folder_apps)
        mFolderTitleInput = findViewById(R.id.folder_title)
449
450
451
452
453
454
455
456
457
458
        mFolderTitleInput.setOnBackKeyListener(this)
        mFolderTitleInput.setOnFocusChangeListener(this)
        mFolderTitleInput.setOnEditorActionListener(this)
        mFolderTitleInput.setSelectAllOnFocus(true)
        mFolderTitleInput.inputType = mFolderTitleInput.inputType and
            InputType.TYPE_TEXT_FLAG_AUTO_CORRECT.inv() and
            InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS.inv() or
            InputType.TYPE_TEXT_FLAG_CAP_WORDS
        mFolderTitleInput.forceDisableSuggestions(true)

459
460
461
462
        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)
463
        mCancelTouchController = UiFactory.enableLiveUIChanges(this)
464
        workspace.setup(dragController)
Amit Kumar's avatar
Amit Kumar committed
465
        setupWidgetPage()
466
467
468
        workspace.bindAndInitFirstScreen(null)
        dragController.addDragListener(workspace)
        dragController.addDropTarget(workspace)
Amit Kumar's avatar
Amit Kumar committed
469
470
471

        // Setup the drag controller (drop targets have to be added in reverse order in priority)
        dragController.setMoveTarget(workspace)
Amit Kumar's avatar
Amit Kumar committed
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
501
502
503
504
505
506
507
508
509
510
511
512
513

        wallpaperChangeReceiver = WallpaperChangeReceiver(workspace)
        workspace.addOnAttachStateChangeListener(object : OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) {
                wallpaperChangeReceiver?.setWindowToken(v.windowToken)
            }

            override fun onViewDetachedFromWindow(v: View) {
                wallpaperChangeReceiver?.setWindowToken(null)
            }
        })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == WeatherPreferences.LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() &&
                grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
                // We only get here if user tried to enable the preference,
                // hence safe to turn it on after permission is granted
                val lm = getSystemService(LOCATION_SERVICE) as LocationManager
                if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    showLocationEnableDialog()
                    Preferences.setEnableLocation(this)
                } else {
                    startService(
                        Intent(this, WeatherUpdateService::class.java)
                            .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)
                    )
                }
            }
        } else if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() &&
                grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
                BlurWallpaperProvider.getInstance(applicationContext).updateAsync()
            }
        } else super.onRequestPermissionsResult(requestCode, permissions, grantResults)
514
515
    }

Amit Kumar's avatar
Amit Kumar committed
516
    private fun setupWidgetPage() {
517
        widgetPage =
Amit Kumar's avatar
Amit Kumar committed
518
            layoutInflater.inflate(R.layout.widgets_page, rootView, false) as WidgetPageLayer
Amit Kumar's avatar
Amit Kumar committed
519
        rootView.addView(widgetPage)
520
521
522

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

523
524
525
        widgetPage.visibility = View.VISIBLE
        widgetPage.post {
            widgetPage.translationX = -(widgetPage.measuredWidth * 1.00f)
Amit Kumar's avatar
Amit Kumar committed
526
        }
527
        widgetRootView = widgetPage.findViewById(R.id.widgets_scroll_container)
Amit Kumar's avatar
Amit Kumar committed
528
        widgetPage.findViewById<View>(R.id.used_apps_layout).clipToOutline = true
529
        widgetPage.tag = "Widget page"
Amit Kumar's avatar
Amit Kumar committed
530
531
532
533

        // TODO: replace with app predictions
        // Prepare app suggestions view
        // [[BEGIN]]
534
535
536
537
        widgetPage.findViewById<View>(R.id.openUsageAccessSettings).setOnClickListener {
            startActivity(
                Intent(
                    Settings.ACTION_USAGE_ACCESS_SETTINGS
Amit Kumar's avatar
Amit Kumar committed
538
                )
539
540
            )
        }
Amit Kumar's avatar
Amit Kumar committed
541
542

        // divided by 2 because of left and right padding.
543
544
545
546
547
        val emptySpace = mDeviceProfile.availableWidthPx - 2 * Utilities.pxFromDp(16, this) - 4 *
            mDeviceProfile.cellWidthPx
        val padding = emptySpace / 10
        widgetPage.findViewById<View>(R.id.suggestedAppGrid)
            .setPadding(padding.toInt(), 0, padding.toInt(), 0)
Amit Kumar's avatar
Amit Kumar committed
548
549
550
551
552
553
554
        // [[END]]

        // Prepare search suggestion view
        // [[BEGIN]]
        mSearchInput = widgetPage.findViewById(R.id.search_input)
        val clearSuggestions: ImageView =
            widgetPage.findViewById(R.id.clearSuggestionImageView)
555
        clearSuggestions.setOnClickListener {
Amit Kumar's avatar
Amit Kumar committed
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
            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()
589
                .switchMap { charSequence: String? ->
Amit Kumar's avatar
Amit Kumar committed
590
591
592
593
594
595
596
                    if (charSequence != null && charSequence.isNotEmpty()) {
                        searchForQuery(charSequence)
                    } else {
                        Observable.just(
                            SuggestionsResult(charSequence)
                        )
                    }
597
                }
Amit Kumar's avatar
Amit Kumar committed
598
599
600
601
602
603
604
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(
                    SearchInputDisposableObserver(this, suggestionAdapter, widgetPage)
                )
        )

605
        mSearchInput.onFocusChangeListener =
606
            OnFocusChangeListener { v: View, hasFocus: Boolean ->
607
608
609
                if (!hasFocus) {
                    hideKeyboard(v)
                }
Amit Kumar's avatar
Amit Kumar committed
610
611
612
613
614
615
616
617
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
644
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
            }

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

702
        val widgetIds: IntArray = mAppWidgetHost.appWidgetIds
Amit Kumar's avatar
Amit Kumar committed
703
704
        Arrays.sort(widgetIds)
        for (id in widgetIds) {
705
            val appWidgetInfo: AppWidgetProviderInfo? = mAppWidgetManager.getAppWidgetInfo(id)
Amit Kumar's avatar
Amit Kumar committed
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
            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)
732
        widgetContainer.addView(widgetView)
Amit Kumar's avatar
Amit Kumar committed
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
    }

    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?> {
809
        val query = charSequence.toString().lowercase(Locale.getDefault())
Amit Kumar's avatar
Amit Kumar committed
810
811
812
813
        val suggestionsResult = SuggestionsResult(
            query
        )
        val launcherItems: MutableList<LauncherItem> = ArrayList()
814
815
816
817
        workspace.mapOverItems(true) { item, _, _ ->
            Log.i(TAG, "searchForLauncherItems: ${item.title}")
            if (item.title.toString().lowercase(Locale.getDefault()).contains(query)) {
                launcherItems.add(item)
Amit Kumar's avatar
Amit Kumar committed
818
            }
819
            false
Amit Kumar's avatar
Amit Kumar committed
820
821
        }
        launcherItems.sortWith(Comparator.comparing { launcherItem: LauncherItem ->
822
            launcherItem.title.toString().lowercase(Locale.getDefault()).indexOf(query)
Amit Kumar's avatar
Amit Kumar committed
823
824
825
826
827
828
        })
        if (launcherItems.size > 4) {
            suggestionsResult.launcherItems = launcherItems.subList(0, 4)
        } else {
            suggestionsResult.launcherItems = launcherItems
        }
829
        Log.i(TAG, "searchForLauncherItems: $suggestionsResult")
Amit Kumar's avatar
Amit Kumar committed
830
        return Observable.just(suggestionsResult)
831
832
            .onErrorReturn {
                it.printStackTrace()
Amit Kumar's avatar
Amit Kumar committed
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
915
916
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
                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
972
973
                val layoutParams =
                    activeRoundedWidgetView!!.layoutParams as LinearLayout.LayoutParams
Amit Kumar's avatar
Amit Kumar committed
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
                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
                )
            }
        })
    }

1000
    override fun <T : View> findViewById(id: Int): T {