1 /* Based on code by Leonardo Fischer
2 * See https://github.com/lgfischer/WidgetHostExample
4 * Copyright 2016 Braden Farmer
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 package com.farmerbb.taskbar.ui;
21 import android.animation.Animator;
22 import android.animation.AnimatorListenerAdapter;
23 import android.annotation.SuppressLint;
24 import android.annotation.TargetApi;
25 import android.appwidget.AppWidgetHost;
26 import android.appwidget.AppWidgetHostView;
27 import android.appwidget.AppWidgetManager;
28 import android.appwidget.AppWidgetProviderInfo;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.SharedPreferences;
35 import android.content.pm.PackageManager;
36 import android.content.res.Configuration;
37 import android.graphics.Color;
38 import android.graphics.ColorMatrix;
39 import android.graphics.ColorMatrixColorFilter;
40 import android.graphics.drawable.Drawable;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.os.Handler;
44 import android.os.Process;
45 import android.support.v4.content.LocalBroadcastManager;
46 import android.support.v4.graphics.ColorUtils;
47 import android.util.SparseArray;
48 import android.view.MotionEvent;
49 import android.view.PointerIcon;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.view.WindowManager;
53 import android.widget.FrameLayout;
54 import android.widget.ImageView;
55 import android.widget.LinearLayout;
56 import android.widget.TextView;
57 import android.widget.Toast;
59 import com.farmerbb.taskbar.R;
60 import com.farmerbb.taskbar.activity.DashboardActivity;
61 import com.farmerbb.taskbar.activity.HomeActivityDelegate;
62 import com.farmerbb.taskbar.activity.dark.DashboardActivityDark;
63 import com.farmerbb.taskbar.util.DashboardHelper;
64 import com.farmerbb.taskbar.widget.DashboardCell;
65 import com.farmerbb.taskbar.util.FreeformHackHelper;
66 import com.farmerbb.taskbar.util.LauncherHelper;
67 import com.farmerbb.taskbar.util.U;
69 import java.util.List;
71 public class DashboardController implements Controller {
73 private AppWidgetManager mAppWidgetManager;
74 private AppWidgetHost mAppWidgetHost;
76 private Context context;
77 private LinearLayout layout;
79 private SparseArray<DashboardCell> cells = new SparseArray<>();
80 private SparseArray<AppWidgetHostView> widgets = new SparseArray<>();
82 private final int APPWIDGET_HOST_ID = 123;
87 private int previouslySelectedCell = -1;
89 private View.OnClickListener ocl = view -> toggleDashboard();
91 private View.OnClickListener cellOcl = view -> cellClick(view, true);
93 private View.OnHoverListener cellOhl = (v, event) -> {
96 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
97 v.setPointerIcon(PointerIcon.getSystemIcon(context, PointerIcon.TYPE_DEFAULT));
102 private View.OnLongClickListener olcl = v -> {
107 private View.OnGenericMotionListener ogml = (view, motionEvent) -> {
108 if(motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
109 && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY)
115 private DashboardCell.OnInterceptedLongPressListener listener = this::cellLongClick;
117 private BroadcastReceiver toggleReceiver = new BroadcastReceiver() {
119 public void onReceive(Context context, Intent intent) {
124 private BroadcastReceiver addWidgetReceiver = new BroadcastReceiver() {
126 public void onReceive(Context context, Intent intent) {
129 if(intent.hasExtra("appWidgetId") && intent.hasExtra("cellId")) {
130 int appWidgetId = intent.getExtras().getInt("appWidgetId", -1);
131 int cellId = intent.getExtras().getInt("cellId", -1);
133 addWidget(appWidgetId, cellId, true);
138 private BroadcastReceiver removeWidgetReceiver = new BroadcastReceiver() {
140 public void onReceive(Context context, Intent intent) {
143 if(intent.hasExtra("cellId")) {
144 int cellId = intent.getExtras().getInt("cellId", -1);
146 removeWidget(cellId, false);
151 private BroadcastReceiver hideReceiver = new BroadcastReceiver() {
153 public void onReceive(Context context, Intent intent) {
158 public DashboardController(Context context) {
159 this.context = context;
162 @TargetApi(Build.VERSION_CODES.M)
164 public void onCreateHost(Host host) {
165 SharedPreferences pref = U.getSharedPreferences(context);
166 if(pref.getBoolean("dashboard", false)) {
167 if(pref.getBoolean("taskbar_active", false) || LauncherHelper.getInstance().isOnHomeScreen()) {
168 if(U.canDrawOverlays(context, host instanceof HomeActivityDelegate))
171 pref.edit().putBoolean("taskbar_active", false).apply();
175 } else host.terminate();
176 } else host.terminate();
179 @SuppressLint("RtlHardcoded")
180 private void drawDashboard(Host host) {
181 final ViewParams params = new ViewParams(
182 WindowManager.LayoutParams.MATCH_PARENT,
183 WindowManager.LayoutParams.MATCH_PARENT,
185 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
189 layout = new LinearLayout(context);
190 layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
191 layout.setVisibility(View.GONE);
194 SharedPreferences pref = U.getSharedPreferences(context);
195 int width = pref.getInt("dashboard_width", context.getApplicationContext().getResources().getInteger(R.integer.dashboard_width));
196 int height = pref.getInt("dashboard_height", context.getApplicationContext().getResources().getInteger(R.integer.dashboard_height));
198 boolean isPortrait = context.getApplicationContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
199 boolean isLandscape = context.getApplicationContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
211 maxSize = columns * rows;
213 int backgroundTint = U.getBackgroundTint(context);
214 int accentColor = U.getAccentColor(context);
215 int accentColorAlt = accentColor;
216 accentColorAlt = ColorUtils.setAlphaComponent(accentColorAlt, Color.alpha(accentColorAlt) / 2);
220 for(int i = 0; i < columns; i++) {
221 LinearLayout layout2 = new LinearLayout(context);
222 layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
223 layout2.setOrientation(LinearLayout.VERTICAL);
225 for(int j = 0; j < rows; j++) {
226 DashboardCell cellLayout = (DashboardCell) View.inflate(context, R.layout.dashboard, null);
227 cellLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
228 cellLayout.setBackgroundColor(backgroundTint);
229 cellLayout.setOnClickListener(cellOcl);
230 cellLayout.setOnHoverListener(cellOhl);
232 TextView empty = cellLayout.findViewById(R.id.empty);
233 empty.setBackgroundColor(accentColorAlt);
234 empty.setTextColor(accentColor);
236 Bundle bundle = new Bundle();
237 bundle.putInt("cellId", cellCount);
239 cellLayout.setTag(bundle);
240 cells.put(cellCount, cellLayout);
243 layout2.addView(cellLayout);
246 layout.addView(layout2);
249 mAppWidgetManager = AppWidgetManager.getInstance(context);
250 mAppWidgetHost = new AppWidgetHost(context, APPWIDGET_HOST_ID);
251 mAppWidgetHost.startListening();
253 for(int i = 0; i < maxSize; i++) {
254 int appWidgetId = pref.getInt("dashboard_widget_" + i, -1);
255 if(appWidgetId != -1)
256 addWidget(appWidgetId, i, false);
257 else if(pref.getBoolean("dashboard_widget_" + i + "_placeholder", false))
261 mAppWidgetHost.stopListening();
263 LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
265 lbm.unregisterReceiver(toggleReceiver);
266 lbm.unregisterReceiver(addWidgetReceiver);
267 lbm.unregisterReceiver(removeWidgetReceiver);
268 lbm.unregisterReceiver(hideReceiver);
270 lbm.registerReceiver(toggleReceiver, new IntentFilter("com.farmerbb.taskbar.TOGGLE_DASHBOARD"));
271 lbm.registerReceiver(addWidgetReceiver, new IntentFilter("com.farmerbb.taskbar.ADD_WIDGET_COMPLETED"));
272 lbm.registerReceiver(removeWidgetReceiver, new IntentFilter("com.farmerbb.taskbar.REMOVE_WIDGET_COMPLETED"));
273 lbm.registerReceiver(hideReceiver, new IntentFilter("com.farmerbb.taskbar.HIDE_DASHBOARD"));
275 host.addView(layout, params);
277 new Handler().postDelayed(() -> {
278 int paddingSize = context.getResources().getDimensionPixelSize(R.dimen.icon_size);
280 switch(U.getTaskbarPosition(context)) {
281 case "top_vertical_left":
282 case "bottom_vertical_left":
283 layout.setPadding(paddingSize, 0, 0, 0);
287 layout.setPadding(0, paddingSize, 0, 0);
289 case "top_vertical_right":
290 case "bottom_vertical_right":
291 layout.setPadding(0, 0, paddingSize, 0);
295 layout.setPadding(0, 0, 0, paddingSize);
301 private void toggleDashboard() {
302 if(layout.getVisibility() == View.GONE)
308 @SuppressWarnings("deprecation")
309 @TargetApi(Build.VERSION_CODES.N)
310 private void showDashboard() {
311 if(layout.getVisibility() == View.GONE) {
312 layout.setOnClickListener(ocl);
315 LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.DASHBOARD_APPEARING"));
316 LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
318 boolean inFreeformMode = FreeformHackHelper.getInstance().isInFreeformWorkspace();
320 final SharedPreferences pref = U.getSharedPreferences(context);
321 Intent intent = null;
323 switch(pref.getString("theme", "light")) {
325 intent = new Intent(context, DashboardActivity.class);
328 intent = new Intent(context, DashboardActivityDark.class);
333 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
334 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
338 if(intent != null && U.hasBrokenSetLaunchBoundsApi())
339 intent.putExtra("context_menu_fix", true);
341 U.startActivityMaximized(context, intent);
343 context.startActivity(intent);
345 for(int i = 0; i < maxSize; i++) {
346 final DashboardCell cellLayout = cells.get(i);
347 final AppWidgetHostView hostView = widgets.get(i);
349 if(hostView != null) {
351 context.getPackageManager().getApplicationInfo(hostView.getAppWidgetInfo().provider.getPackageName(), 0);
352 hostView.post(() -> {
353 ViewGroup.LayoutParams params = hostView.getLayoutParams();
354 params.width = cellLayout.getWidth();
355 params.height = cellLayout.getHeight();
356 hostView.setLayoutParams(params);
357 hostView.updateAppWidgetSize(null, cellLayout.getWidth(), cellLayout.getHeight(), cellLayout.getWidth(), cellLayout.getHeight());
359 } catch (PackageManager.NameNotFoundException e) {
360 removeWidget(i, false);
361 } catch (NullPointerException e) {
362 removeWidget(i, true);
367 if(!pref.getBoolean("dashboard_tutorial_shown", false)) {
368 U.showToastLong(context, R.string.dashboard_tutorial);
369 pref.edit().putBoolean("dashboard_tutorial_shown", true).apply();
374 private void hideDashboard() {
375 if(layout.getVisibility() == View.VISIBLE) {
376 layout.setOnClickListener(null);
379 for(int i = 0; i < maxSize; i++) {
380 FrameLayout frameLayout = cells.get(i);
381 frameLayout.findViewById(R.id.empty).setVisibility(View.GONE);
384 previouslySelectedCell = -1;
388 private void fadeIn() {
389 mAppWidgetHost.startListening();
391 DashboardHelper.getInstance().setDashboardOpen(true);
393 layout.setVisibility(View.VISIBLE);
396 .setDuration(context.getResources().getInteger(android.R.integer.config_shortAnimTime))
400 private void fadeOut(final boolean sendIntent) {
401 mAppWidgetHost.stopListening();
403 DashboardHelper.getInstance().setDashboardOpen(false);
407 .setDuration(context.getResources().getInteger(android.R.integer.config_shortAnimTime))
408 .setListener(new AnimatorListenerAdapter() {
410 public void onAnimationEnd(Animator animation) {
411 layout.setVisibility(View.GONE);
412 if(sendIntent) LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.DASHBOARD_DISAPPEARING"));
417 @TargetApi(Build.VERSION_CODES.M)
419 public void onRecreateHost(Host host) {
422 host.removeView(layout);
423 } catch (IllegalArgumentException e) { /* Gracefully fail */ }
425 SharedPreferences pref = U.getSharedPreferences(context);
426 if(U.canDrawOverlays(context, host instanceof HomeActivityDelegate))
429 pref.edit().putBoolean("taskbar_active", false).apply();
437 public void onDestroyHost(Host host) {
440 host.removeView(layout);
441 } catch (IllegalArgumentException e) { /* Gracefully fail */ }
443 LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
445 lbm.unregisterReceiver(toggleReceiver);
446 lbm.unregisterReceiver(addWidgetReceiver);
447 lbm.unregisterReceiver(removeWidgetReceiver);
448 lbm.unregisterReceiver(hideReceiver);
450 lbm.sendBroadcast(new Intent("com.farmerbb.taskbar.DASHBOARD_DISAPPEARING"));
453 private void cellClick(View view, boolean isActualClick) {
454 Bundle bundle = (Bundle) view.getTag();
455 int cellId = bundle.getInt("cellId");
456 int appWidgetId = bundle.getInt("appWidgetId", -1);
458 int currentlySelectedCell = appWidgetId == -1 ? cellId : -1;
460 SharedPreferences pref = U.getSharedPreferences(context);
461 boolean shouldShowPlaceholder = pref.getBoolean("dashboard_widget_" + cellId + "_placeholder", false);
462 if(isActualClick && ((appWidgetId == -1 && currentlySelectedCell == previouslySelectedCell) || shouldShowPlaceholder)) {
465 FrameLayout frameLayout = cells.get(currentlySelectedCell);
466 frameLayout.findViewById(R.id.empty).setVisibility(View.GONE);
468 Intent intent = new Intent("com.farmerbb.taskbar.ADD_WIDGET_REQUESTED");
469 intent.putExtra("appWidgetId", APPWIDGET_HOST_ID);
470 intent.putExtra("cellId", cellId);
471 LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
473 if(shouldShowPlaceholder) {
474 String providerName = pref.getString("dashboard_widget_" + cellId + "_provider", "null");
475 if(!providerName.equals("null")) {
476 ComponentName componentName = ComponentName.unflattenFromString(providerName);
478 List<AppWidgetProviderInfo> providerInfoList = mAppWidgetManager.getInstalledProvidersForProfile(Process.myUserHandle());
479 for(AppWidgetProviderInfo info : providerInfoList) {
480 if(info.provider.equals(componentName)) {
481 U.showToast(context, context.getString(R.string.widget_restore_toast, info.loadLabel(context.getPackageManager())), Toast.LENGTH_SHORT);
488 previouslySelectedCell = -1;
490 for(int i = 0; i < maxSize; i++) {
491 FrameLayout frameLayout = cells.get(i);
492 frameLayout.findViewById(R.id.empty).setVisibility(i == currentlySelectedCell && !shouldShowPlaceholder ? View.VISIBLE : View.GONE);
495 previouslySelectedCell = currentlySelectedCell;
499 private void cellLongClick(View view) {
502 Bundle bundle = (Bundle) view.getTag();
503 int cellId = bundle.getInt("cellId");
505 Intent intent = new Intent("com.farmerbb.taskbar.REMOVE_WIDGET_REQUESTED");
506 intent.putExtra("cellId", cellId);
507 LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
510 private void addWidget(int appWidgetId, int cellId, boolean shouldSave) {
511 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
513 final DashboardCell cellLayout = cells.get(cellId);
514 final AppWidgetHostView hostView = mAppWidgetHost.createView(context, appWidgetId, appWidgetInfo);
515 hostView.setAppWidget(appWidgetId, appWidgetInfo);
517 Bundle bundle = new Bundle();
518 bundle.putInt("cellId", cellId);
519 hostView.setTag(bundle);
521 cellLayout.findViewById(R.id.empty).setVisibility(View.GONE);
522 cellLayout.findViewById(R.id.placeholder).setVisibility(View.GONE);
523 cellLayout.setOnLongClickListener(olcl);
524 cellLayout.setOnGenericMotionListener(ogml);
525 cellLayout.setOnInterceptedLongPressListener(listener);
527 LinearLayout linearLayout = cellLayout.findViewById(R.id.dashboard);
528 linearLayout.addView(hostView);
530 Bundle bundle2 = (Bundle) cellLayout.getTag();
531 bundle2.putInt("appWidgetId", appWidgetId);
532 cellLayout.setTag(bundle2);
534 widgets.put(cellId, hostView);
537 SharedPreferences pref = U.getSharedPreferences(context);
538 SharedPreferences.Editor editor = pref.edit();
539 editor.putInt("dashboard_widget_" + cellId, appWidgetId);
540 editor.putString("dashboard_widget_" + cellId + "_provider", appWidgetInfo.provider.flattenToString());
541 editor.remove("dashboard_widget_" + cellId + "_placeholder");
545 new Handler().post(() -> {
546 ViewGroup.LayoutParams params = hostView.getLayoutParams();
547 params.width = cellLayout.getWidth();
548 params.height = cellLayout.getHeight();
549 hostView.setLayoutParams(params);
550 hostView.updateAppWidgetSize(null, cellLayout.getWidth(), cellLayout.getHeight(), cellLayout.getWidth(), cellLayout.getHeight());
554 private void removeWidget(int cellId, boolean tempRemove) {
555 widgets.remove(cellId);
557 DashboardCell cellLayout = cells.get(cellId);
558 Bundle bundle = (Bundle) cellLayout.getTag();
560 mAppWidgetHost.deleteAppWidgetId(bundle.getInt("appWidgetId"));
561 bundle.remove("appWidgetId");
563 LinearLayout linearLayout = cellLayout.findViewById(R.id.dashboard);
564 linearLayout.removeAllViews();
566 cellLayout.setTag(bundle);
567 cellLayout.setOnClickListener(cellOcl);
568 cellLayout.setOnHoverListener(cellOhl);
569 cellLayout.setOnLongClickListener(null);
570 cellLayout.setOnGenericMotionListener(null);
571 cellLayout.setOnInterceptedLongPressListener(null);
573 SharedPreferences pref = U.getSharedPreferences(context);
574 SharedPreferences.Editor editor = pref.edit();
575 editor.remove("dashboard_widget_" + cellId);
578 editor.putBoolean("dashboard_widget_" + cellId + "_placeholder", true);
579 addPlaceholder(cellId);
581 editor.remove("dashboard_widget_" + cellId + "_provider");
586 private void addPlaceholder(int cellId) {
587 FrameLayout placeholder = cells.get(cellId).findViewById(R.id.placeholder);
588 SharedPreferences pref = U.getSharedPreferences(context);
589 String providerName = pref.getString("dashboard_widget_" + cellId + "_provider", "null");
591 if(!providerName.equals("null")) {
592 ImageView imageView = placeholder.findViewById(R.id.placeholder_image);
593 ComponentName componentName = ComponentName.unflattenFromString(providerName);
595 List<AppWidgetProviderInfo> providerInfoList = mAppWidgetManager.getInstalledProvidersForProfile(Process.myUserHandle());
596 for(AppWidgetProviderInfo info : providerInfoList) {
597 if(info.provider.equals(componentName)) {
598 Drawable drawable = info.loadPreviewImage(context, -1);
599 if(drawable == null) drawable = info.loadIcon(context, -1);
601 ColorMatrix matrix = new ColorMatrix();
602 matrix.setSaturation(0);
604 imageView.setImageDrawable(drawable);
605 imageView.setColorFilter(new ColorMatrixColorFilter(matrix));
611 placeholder.setVisibility(View.VISIBLE);