1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher3;
18
19import android.annotation.TargetApi;
20import android.app.Activity;
21import android.app.SearchManager;
22import android.appwidget.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
24import android.content.ActivityNotFoundException;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.SharedPreferences;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
32import android.content.pm.PackageManager.NameNotFoundException;
33import android.content.pm.ResolveInfo;
34import android.content.res.Resources;
35import android.database.Cursor;
36import android.graphics.Bitmap;
37import android.graphics.BitmapFactory;
38import android.graphics.Canvas;
39import android.graphics.Color;
40import android.graphics.Matrix;
41import android.graphics.Paint;
42import android.graphics.PaintFlagsDrawFilter;
43import android.graphics.Rect;
44import android.graphics.drawable.BitmapDrawable;
45import android.graphics.drawable.Drawable;
46import android.graphics.drawable.PaintDrawable;
47import android.os.Build;
48import android.os.Bundle;
49import android.os.Process;
50import android.text.TextUtils;
51import android.util.DisplayMetrics;
52import android.util.Log;
53import android.util.Pair;
54import android.util.SparseArray;
55import android.util.TypedValue;
56import android.view.View;
57import android.widget.Toast;
58
59import java.io.ByteArrayOutputStream;
60import java.io.IOException;
61import java.util.ArrayList;
62import java.util.Locale;
63import java.util.Set;
64import java.util.regex.Matcher;
65import java.util.regex.Pattern;
66
67/**
68 * Various utilities shared amongst the Launcher's classes.
69 */
70public final class Utilities {
71
72    private static final String TAG = "Launcher.Utilities";
73
74    private static final Rect sOldBounds = new Rect();
75    private static final Canvas sCanvas = new Canvas();
76
77    private static final Pattern sTrimPattern =
78            Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
79
80    static {
81        sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
82                Paint.FILTER_BITMAP_FLAG));
83    }
84    static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
85    static int sColorIndex = 0;
86
87    private static final int[] sLoc0 = new int[2];
88    private static final int[] sLoc1 = new int[2];
89
90    // TODO: use Build.VERSION_CODES when available
91    public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
92
93    public static final boolean ATLEAST_LOLLIPOP_MR1 =
94            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
95
96    public static final boolean ATLEAST_LOLLIPOP =
97            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
98
99    public static final boolean ATLEAST_KITKAT =
100            Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
101
102    public static final boolean ATLEAST_JB_MR1 =
103            Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
104
105    public static final boolean ATLEAST_JB_MR2 =
106            Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
107
108    // To turn on these properties, type
109    // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
110    private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
111    private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
112
113    public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
114
115    public static boolean isPropertyEnabled(String propertyName) {
116        return Log.isLoggable(propertyName, Log.VERBOSE);
117    }
118
119    public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
120        SharedPreferences sharedPrefs = context.getSharedPreferences(
121                LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
122                        Context.MODE_MULTI_PROCESS : 0));
123        boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
124        return sForceEnableRotation || allowRotationPref;
125    }
126
127    public static boolean isRotationAllowedForDevice(Context context) {
128        return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
129    }
130
131    public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
132        byte[] data = c.getBlob(iconIndex);
133        try {
134            return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
135        } catch (Exception e) {
136            return null;
137        }
138    }
139
140    /**
141     * Returns a bitmap suitable for the all apps view. If the package or the resource do not
142     * exist, it returns null.
143     */
144    public static Bitmap createIconBitmap(String packageName, String resourceName,
145            Context context) {
146        PackageManager packageManager = context.getPackageManager();
147        // the resource
148        try {
149            Resources resources = packageManager.getResourcesForApplication(packageName);
150            if (resources != null) {
151                final int id = resources.getIdentifier(resourceName, null, null);
152                return createIconBitmap(
153                        resources.getDrawableForDensity(id, LauncherAppState.getInstance()
154                                .getInvariantDeviceProfile().fillResIconDpi), context);
155            }
156        } catch (Exception e) {
157            // Icon not found.
158        }
159        return null;
160    }
161
162    private static int getIconBitmapSize() {
163        return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
164    }
165
166    /**
167     * Returns a bitmap which is of the appropriate size to be displayed as an icon
168     */
169    public static Bitmap createIconBitmap(Bitmap icon, Context context) {
170        final int iconBitmapSize = getIconBitmapSize();
171        if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
172            return icon;
173        }
174        return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
175    }
176
177    /**
178     * Returns a bitmap suitable for the all apps view.
179     */
180    public static Bitmap createIconBitmap(Drawable icon, Context context) {
181        synchronized (sCanvas) {
182            final int iconBitmapSize = getIconBitmapSize();
183
184            int width = iconBitmapSize;
185            int height = iconBitmapSize;
186
187            if (icon instanceof PaintDrawable) {
188                PaintDrawable painter = (PaintDrawable) icon;
189                painter.setIntrinsicWidth(width);
190                painter.setIntrinsicHeight(height);
191            } else if (icon instanceof BitmapDrawable) {
192                // Ensure the bitmap has a density.
193                BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
194                Bitmap bitmap = bitmapDrawable.getBitmap();
195                if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
196                    bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
197                }
198            }
199            int sourceWidth = icon.getIntrinsicWidth();
200            int sourceHeight = icon.getIntrinsicHeight();
201            if (sourceWidth > 0 && sourceHeight > 0) {
202                // Scale the icon proportionally to the icon dimensions
203                final float ratio = (float) sourceWidth / sourceHeight;
204                if (sourceWidth > sourceHeight) {
205                    height = (int) (width / ratio);
206                } else if (sourceHeight > sourceWidth) {
207                    width = (int) (height * ratio);
208                }
209            }
210
211            // no intrinsic size --> use default size
212            int textureWidth = iconBitmapSize;
213            int textureHeight = iconBitmapSize;
214
215            final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
216                    Bitmap.Config.ARGB_8888);
217            final Canvas canvas = sCanvas;
218            canvas.setBitmap(bitmap);
219
220            final int left = (textureWidth-width) / 2;
221            final int top = (textureHeight-height) / 2;
222
223            @SuppressWarnings("all") // suppress dead code warning
224            final boolean debug = false;
225            if (debug) {
226                // draw a big box for the icon for debugging
227                canvas.drawColor(sColors[sColorIndex]);
228                if (++sColorIndex >= sColors.length) sColorIndex = 0;
229                Paint debugPaint = new Paint();
230                debugPaint.setColor(0xffcccc00);
231                canvas.drawRect(left, top, left+width, top+height, debugPaint);
232            }
233
234            sOldBounds.set(icon.getBounds());
235            icon.setBounds(left, top, left+width, top+height);
236            icon.draw(canvas);
237            icon.setBounds(sOldBounds);
238            canvas.setBitmap(null);
239
240            return bitmap;
241        }
242    }
243
244    /**
245     * Given a coordinate relative to the descendant, find the coordinate in a parent view's
246     * coordinates.
247     *
248     * @param descendant The descendant to which the passed coordinate is relative.
249     * @param root The root view to make the coordinates relative to.
250     * @param coord The coordinate that we want mapped.
251     * @param includeRootScroll Whether or not to account for the scroll of the descendant:
252     *          sometimes this is relevant as in a child's coordinates within the descendant.
253     * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
254     *         this scale factor is assumed to be equal in X and Y, and so if at any point this
255     *         assumption fails, we will need to return a pair of scale factors.
256     */
257    public static float getDescendantCoordRelativeToParent(View descendant, View root,
258                                                           int[] coord, boolean includeRootScroll) {
259        ArrayList<View> ancestorChain = new ArrayList<View>();
260
261        float[] pt = {coord[0], coord[1]};
262
263        View v = descendant;
264        while(v != root && v != null) {
265            ancestorChain.add(v);
266            v = (View) v.getParent();
267        }
268        ancestorChain.add(root);
269
270        float scale = 1.0f;
271        int count = ancestorChain.size();
272        for (int i = 0; i < count; i++) {
273            View v0 = ancestorChain.get(i);
274            // For TextViews, scroll has a meaning which relates to the text position
275            // which is very strange... ignore the scroll.
276            if (v0 != descendant || includeRootScroll) {
277                pt[0] -= v0.getScrollX();
278                pt[1] -= v0.getScrollY();
279            }
280
281            v0.getMatrix().mapPoints(pt);
282            pt[0] += v0.getLeft();
283            pt[1] += v0.getTop();
284            scale *= v0.getScaleX();
285        }
286
287        coord[0] = (int) Math.round(pt[0]);
288        coord[1] = (int) Math.round(pt[1]);
289        return scale;
290    }
291
292    /**
293     * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
294     */
295    public static float mapCoordInSelfToDescendent(View descendant, View root,
296                                                   int[] coord) {
297        ArrayList<View> ancestorChain = new ArrayList<View>();
298
299        float[] pt = {coord[0], coord[1]};
300
301        View v = descendant;
302        while(v != root) {
303            ancestorChain.add(v);
304            v = (View) v.getParent();
305        }
306        ancestorChain.add(root);
307
308        float scale = 1.0f;
309        Matrix inverse = new Matrix();
310        int count = ancestorChain.size();
311        for (int i = count - 1; i >= 0; i--) {
312            View ancestor = ancestorChain.get(i);
313            View next = i > 0 ? ancestorChain.get(i-1) : null;
314
315            pt[0] += ancestor.getScrollX();
316            pt[1] += ancestor.getScrollY();
317
318            if (next != null) {
319                pt[0] -= next.getLeft();
320                pt[1] -= next.getTop();
321                next.getMatrix().invert(inverse);
322                inverse.mapPoints(pt);
323                scale *= next.getScaleX();
324            }
325        }
326
327        coord[0] = (int) Math.round(pt[0]);
328        coord[1] = (int) Math.round(pt[1]);
329        return scale;
330    }
331
332    /**
333     * Utility method to determine whether the given point, in local coordinates,
334     * is inside the view, where the area of the view is expanded by the slop factor.
335     * This method is called while processing touch-move events to determine if the event
336     * is still within the view.
337     */
338    public static boolean pointInView(View v, float localX, float localY, float slop) {
339        return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
340                localY < (v.getHeight() + slop);
341    }
342
343    public static void scaleRect(Rect r, float scale) {
344        if (scale != 1.0f) {
345            r.left = (int) (r.left * scale + 0.5f);
346            r.top = (int) (r.top * scale + 0.5f);
347            r.right = (int) (r.right * scale + 0.5f);
348            r.bottom = (int) (r.bottom * scale + 0.5f);
349        }
350    }
351
352    public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
353        v0.getLocationInWindow(sLoc0);
354        v1.getLocationInWindow(sLoc1);
355
356        sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
357        sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
358        sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
359        sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
360
361        if (delta == null) {
362            delta = new int[2];
363        }
364
365        delta[0] = sLoc1[0] - sLoc0[0];
366        delta[1] = sLoc1[1] - sLoc0[1];
367
368        return delta;
369    }
370
371    public static void scaleRectAboutCenter(Rect r, float scale) {
372        int cx = r.centerX();
373        int cy = r.centerY();
374        r.offset(-cx, -cy);
375        Utilities.scaleRect(r, scale);
376        r.offset(cx, cy);
377    }
378
379    public static void startActivityForResultSafely(
380            Activity activity, Intent intent, int requestCode) {
381        try {
382            activity.startActivityForResult(intent, requestCode);
383        } catch (ActivityNotFoundException e) {
384            Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
385        } catch (SecurityException e) {
386            Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
387            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
388                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
389                    "or use the exported attribute for this activity.", e);
390        }
391    }
392
393    static boolean isSystemApp(Context context, Intent intent) {
394        PackageManager pm = context.getPackageManager();
395        ComponentName cn = intent.getComponent();
396        String packageName = null;
397        if (cn == null) {
398            ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
399            if ((info != null) && (info.activityInfo != null)) {
400                packageName = info.activityInfo.packageName;
401            }
402        } else {
403            packageName = cn.getPackageName();
404        }
405        if (packageName != null) {
406            try {
407                PackageInfo info = pm.getPackageInfo(packageName, 0);
408                return (info != null) && (info.applicationInfo != null) &&
409                        ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
410            } catch (NameNotFoundException e) {
411                return false;
412            }
413        } else {
414            return false;
415        }
416    }
417
418    /**
419     * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
420     * @param bitmap The bitmap to scan
421     * @param samples The approximate max number of samples to use.
422     */
423    static int findDominantColorByHue(Bitmap bitmap, int samples) {
424        final int height = bitmap.getHeight();
425        final int width = bitmap.getWidth();
426        int sampleStride = (int) Math.sqrt((height * width) / samples);
427        if (sampleStride < 1) {
428            sampleStride = 1;
429        }
430
431        // This is an out-param, for getting the hsv values for an rgb
432        float[] hsv = new float[3];
433
434        // First get the best hue, by creating a histogram over 360 hue buckets,
435        // where each pixel contributes a score weighted by saturation, value, and alpha.
436        float[] hueScoreHistogram = new float[360];
437        float highScore = -1;
438        int bestHue = -1;
439
440        for (int y = 0; y < height; y += sampleStride) {
441            for (int x = 0; x < width; x += sampleStride) {
442                int argb = bitmap.getPixel(x, y);
443                int alpha = 0xFF & (argb >> 24);
444                if (alpha < 0x80) {
445                    // Drop mostly-transparent pixels.
446                    continue;
447                }
448                // Remove the alpha channel.
449                int rgb = argb | 0xFF000000;
450                Color.colorToHSV(rgb, hsv);
451                // Bucket colors by the 360 integer hues.
452                int hue = (int) hsv[0];
453                if (hue < 0 || hue >= hueScoreHistogram.length) {
454                    // Defensively avoid array bounds violations.
455                    continue;
456                }
457                float score = hsv[1] * hsv[2];
458                hueScoreHistogram[hue] += score;
459                if (hueScoreHistogram[hue] > highScore) {
460                    highScore = hueScoreHistogram[hue];
461                    bestHue = hue;
462                }
463            }
464        }
465
466        SparseArray<Float> rgbScores = new SparseArray<Float>();
467        int bestColor = 0xff000000;
468        highScore = -1;
469        // Go back over the RGB colors that match the winning hue,
470        // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
471        // The highest-scoring RGB color wins.
472        for (int y = 0; y < height; y += sampleStride) {
473            for (int x = 0; x < width; x += sampleStride) {
474                int rgb = bitmap.getPixel(x, y) | 0xff000000;
475                Color.colorToHSV(rgb, hsv);
476                int hue = (int) hsv[0];
477                if (hue == bestHue) {
478                    float s = hsv[1];
479                    float v = hsv[2];
480                    int bucket = (int) (s * 100) + (int) (v * 10000);
481                    // Score by cumulative saturation * value.
482                    float score = s * v;
483                    Float oldTotal = rgbScores.get(bucket);
484                    float newTotal = oldTotal == null ? score : oldTotal + score;
485                    rgbScores.put(bucket, newTotal);
486                    if (newTotal > highScore) {
487                        highScore = newTotal;
488                        // All the colors in the winning bucket are very similar. Last in wins.
489                        bestColor = rgb;
490                    }
491                }
492            }
493        }
494        return bestColor;
495    }
496
497    /*
498     * Finds a system apk which had a broadcast receiver listening to a particular action.
499     * @param action intent action used to find the apk
500     * @return a pair of apk package name and the resources.
501     */
502    static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
503        final Intent intent = new Intent(action);
504        for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
505            if (info.activityInfo != null &&
506                    (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
507                final String packageName = info.activityInfo.packageName;
508                try {
509                    final Resources res = pm.getResourcesForApplication(packageName);
510                    return Pair.create(packageName, res);
511                } catch (NameNotFoundException e) {
512                    Log.w(TAG, "Failed to find resources for " + packageName);
513                }
514            }
515        }
516        return null;
517    }
518
519    @TargetApi(Build.VERSION_CODES.KITKAT)
520    public static boolean isViewAttachedToWindow(View v) {
521        if (ATLEAST_KITKAT) {
522            return v.isAttachedToWindow();
523        } else {
524            // A proxy call which returns null, if the view is not attached to the window.
525            return v.getKeyDispatcherState() != null;
526        }
527    }
528
529    /**
530     * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
531     * provided by the same package which is set to be global search activity.
532     * If widgetCategory is not supported, or no such widget is found, returns the first widget
533     * provided by the package.
534     */
535    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
536    public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
537        SearchManager searchManager =
538                (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
539        ComponentName searchComponent = searchManager.getGlobalSearchActivity();
540        if (searchComponent == null) return null;
541        String providerPkg = searchComponent.getPackageName();
542
543        AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
544
545        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
546        for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
547            if (info.provider.getPackageName().equals(providerPkg)) {
548                if (ATLEAST_JB_MR1) {
549                    if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
550                        return info;
551                    } else if (defaultWidgetForSearchPackage == null) {
552                        defaultWidgetForSearchPackage = info;
553                    }
554                } else {
555                    return info;
556                }
557            }
558        }
559        return defaultWidgetForSearchPackage;
560    }
561
562    /**
563     * Compresses the bitmap to a byte array for serialization.
564     */
565    public static byte[] flattenBitmap(Bitmap bitmap) {
566        // Try go guesstimate how much space the icon will take when serialized
567        // to avoid unnecessary allocations/copies during the write.
568        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
569        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
570        try {
571            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
572            out.flush();
573            out.close();
574            return out.toByteArray();
575        } catch (IOException e) {
576            Log.w(TAG, "Could not write bitmap");
577            return null;
578        }
579    }
580
581    /**
582     * Find the first vacant cell, if there is one.
583     *
584     * @param vacant Holds the x and y coordinate of the vacant cell
585     * @param spanX Horizontal cell span.
586     * @param spanY Vertical cell span.
587     *
588     * @return true if a vacant cell was found
589     */
590    public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
591            int xCount, int yCount, boolean[][] occupied) {
592
593        for (int y = 0; (y + spanY) <= yCount; y++) {
594            for (int x = 0; (x + spanX) <= xCount; x++) {
595                boolean available = !occupied[x][y];
596                out:            for (int i = x; i < x + spanX; i++) {
597                    for (int j = y; j < y + spanY; j++) {
598                        available = available && !occupied[i][j];
599                        if (!available) break out;
600                    }
601                }
602
603                if (available) {
604                    vacant[0] = x;
605                    vacant[1] = y;
606                    return true;
607                }
608            }
609        }
610
611        return false;
612    }
613
614    /**
615     * Trims the string, removing all whitespace at the beginning and end of the string.
616     * Non-breaking whitespaces are also removed.
617     */
618    public static String trim(CharSequence s) {
619        if (s == null) {
620            return null;
621        }
622
623        // Just strip any sequence of whitespace or java space characters from the beginning and end
624        Matcher m = sTrimPattern.matcher(s);
625        return m.replaceAll("$1");
626    }
627
628    /**
629     * Calculates the height of a given string at a specific text size.
630     */
631    public static float calculateTextHeight(float textSizePx) {
632        Paint p = new Paint();
633        p.setTextSize(textSizePx);
634        Paint.FontMetrics fm = p.getFontMetrics();
635        return -fm.top + fm.bottom;
636    }
637
638    /**
639     * Convenience println with multiple args.
640     */
641    public static void println(String key, Object... args) {
642        StringBuilder b = new StringBuilder();
643        b.append(key);
644        b.append(": ");
645        boolean isFirstArgument = true;
646        for (Object arg : args) {
647            if (isFirstArgument) {
648                isFirstArgument = false;
649            } else {
650                b.append(", ");
651            }
652            b.append(arg);
653        }
654        System.out.println(b.toString());
655    }
656
657    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
658    public static boolean isRtl(Resources res) {
659        return ATLEAST_JB_MR1 &&
660                (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
661    }
662
663    public static void assertWorkerThread() {
664        if (LauncherAppState.isDogfoodBuild() &&
665                (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
666            throw new IllegalStateException();
667        }
668    }
669
670    /**
671     * Returns true if the intent is a valid launch intent for a launcher activity of an app.
672     * This is used to identify shortcuts which are different from the ones exposed by the
673     * applications' manifest file.
674     *
675     * @param launchIntent The intent that will be launched when the shortcut is clicked.
676     */
677    public static boolean isLauncherAppTarget(Intent launchIntent) {
678        if (launchIntent != null
679                && Intent.ACTION_MAIN.equals(launchIntent.getAction())
680                && launchIntent.getComponent() != null
681                && launchIntent.getCategories() != null
682                && launchIntent.getCategories().size() == 1
683                && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
684                && TextUtils.isEmpty(launchIntent.getDataString())) {
685            // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
686            Bundle extras = launchIntent.getExtras();
687            if (extras == null) {
688                return true;
689            } else {
690                Set<String> keys = extras.keySet();
691                return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
692            }
693        };
694        return false;
695    }
696
697    public static float dpiFromPx(int size, DisplayMetrics metrics){
698        float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
699        return (size / densityRatio);
700    }
701    public static int pxFromDp(float size, DisplayMetrics metrics) {
702        return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
703                size, metrics));
704    }
705    public static int pxFromSp(float size, DisplayMetrics metrics) {
706        return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
707                size, metrics));
708    }
709
710    public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
711        return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
712    }
713}
714