com.android.internal.util.ArrayUtils Java Examples

The following examples show how to use com.android.internal.util.ArrayUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Displays the package file for a package.
 * @param pckg
 */
private int displayPackageFilePath(String pckg, int userId) throws RemoteException {
    PackageInfo info = mInterface.getPackageInfo(pckg, 0, userId);
    if (info != null && info.applicationInfo != null) {
        final PrintWriter pw = getOutPrintWriter();
        pw.print("package:");
        pw.println(info.applicationInfo.sourceDir);
        if (!ArrayUtils.isEmpty(info.applicationInfo.splitSourceDirs)) {
            for (String splitSourceDir : info.applicationInfo.splitSourceDirs) {
                pw.print("package:");
                pw.println(splitSourceDir);
            }
        }
        return 0;
    }
    return 1;
}
 
Example #2
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private CredentialHash readPatternHashIfExists(int userId) {
    byte[] stored = readFile(getLockPatternFilename(userId));
    if (!ArrayUtils.isEmpty(stored)) {
        return new CredentialHash(stored, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
                CredentialHash.VERSION_GATEKEEPER);
    }

    stored = readFile(getBaseZeroLockPatternFilename(userId));
    if (!ArrayUtils.isEmpty(stored)) {
        return CredentialHash.createBaseZeroPattern(stored);
    }

    stored = readFile(getLegacyLockPatternFilename(userId));
    if (!ArrayUtils.isEmpty(stored)) {
        return new CredentialHash(stored, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
                CredentialHash.VERSION_LEGACY);
    }
    return null;
}
 
Example #3
Source File: AppOpsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public boolean hasRestriction(int restriction, String packageName, int userId) {
    if (perUserRestrictions == null) {
        return false;
    }
    boolean[] restrictions = perUserRestrictions.get(userId);
    if (restrictions == null) {
        return false;
    }
    if (!restrictions[restriction]) {
        return false;
    }
    if (perUserExcludedPackages == null) {
        return true;
    }
    String[] perUserExclusions = perUserExcludedPackages.get(userId);
    if (perUserExclusions == null) {
        return true;
    }
    return !ArrayUtils.contains(perUserExclusions, packageName);
}
 
Example #4
Source File: KeySyncTask.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if a sync is pending.
 * @param recoveryAgentUid uid of the recovery agent.
 */
private boolean shouldCreateSnapshot(int recoveryAgentUid) {
    int[] types = mRecoverableKeyStoreDb.getRecoverySecretTypes(mUserId, recoveryAgentUid);
    if (!ArrayUtils.contains(types, KeyChainProtectionParams.TYPE_LOCKSCREEN)) {
        // Only lockscreen type is supported.
        // We will need to pass extra argument to KeySyncTask to support custom pass phrase.
        return false;
    }
    if (mCredentialUpdated) {
        // Sync credential if at least one snapshot was created.
        if (mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid) != null) {
            mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, true);
            return true;
        }
    }

    return mRecoverableKeyStoreDb.getShouldCreateSnapshot(mUserId, recoveryAgentUid);
}
 
Example #5
Source File: PermissionsState.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private int grantPermission(BasePermission permission, int userId) {
    if (hasPermission(permission.getName(), userId)) {
        return PERMISSION_OPERATION_FAILURE;
    }

    final boolean hasGids = !ArrayUtils.isEmpty(permission.computeGids(userId));
    final int[] oldGids = hasGids ? computeGids(userId) : NO_GIDS;

    PermissionData permissionData = ensurePermissionData(permission);

    if (!permissionData.grant(userId)) {
        return PERMISSION_OPERATION_FAILURE;
    }

    if (hasGids) {
        final int[] newGids = computeGids(userId);
        if (oldGids.length != newGids.length) {
            return PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
        }
    }

    return PERMISSION_OPERATION_SUCCESS;
}
 
Example #6
Source File: PackageUserState.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public PackageUserState(PackageUserState o) {
    ceDataInode = o.ceDataInode;
    installed = o.installed;
    stopped = o.stopped;
    notLaunched = o.notLaunched;
    hidden = o.hidden;
    suspended = o.suspended;
    suspendingPackage = o.suspendingPackage;
    dialogMessage = o.dialogMessage;
    suspendedAppExtras = o.suspendedAppExtras;
    suspendedLauncherExtras = o.suspendedLauncherExtras;
    instantApp = o.instantApp;
    virtualPreload = o.virtualPreload;
    enabled = o.enabled;
    lastDisableAppCaller = o.lastDisableAppCaller;
    domainVerificationStatus = o.domainVerificationStatus;
    appLinkGeneration = o.appLinkGeneration;
    categoryHint = o.categoryHint;
    installReason = o.installReason;
    disabledComponents = ArrayUtils.cloneOrNull(o.disabledComponents);
    enabledComponents = ArrayUtils.cloneOrNull(o.enabledComponents);
    overlayPaths =
        o.overlayPaths == null ? null : Arrays.copyOf(o.overlayPaths, o.overlayPaths.length);
    harmfulAppWarning = o.harmfulAppWarning;
}
 
Example #7
Source File: PackageUserState.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public PackageUserState(PackageUserState o) {
    ceDataInode = o.ceDataInode;
    installed = o.installed;
    stopped = o.stopped;
    notLaunched = o.notLaunched;
    hidden = o.hidden;
    suspended = o.suspended;
    instantApp = o.instantApp;
    virtualPreload = o.virtualPreload;
    enabled = o.enabled;
    lastDisableAppCaller = o.lastDisableAppCaller;
    domainVerificationStatus = o.domainVerificationStatus;
    appLinkGeneration = o.appLinkGeneration;
    categoryHint = o.categoryHint;
    installReason = o.installReason;
    disabledComponents = ArrayUtils.cloneOrNull(o.disabledComponents);
    enabledComponents = ArrayUtils.cloneOrNull(o.enabledComponents);
    overlayPaths =
        o.overlayPaths == null ? null : Arrays.copyOf(o.overlayPaths, o.overlayPaths.length);
}
 
Example #8
Source File: SpannableStringBuilder.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void resizeFor(int size) {
    final int oldLength = mText.length;
    if (size + 1 <= oldLength) {
        return;
    }

    char[] newText = ArrayUtils.newUnpaddedCharArray(GrowingArrayUtils.growSize(size));
    System.arraycopy(mText, 0, newText, 0, mGapStart);
    final int newLength = newText.length;
    final int delta = newLength - oldLength;
    final int after = oldLength - (mGapStart + mGapLength);
    System.arraycopy(mText, oldLength - after, newText, newLength - after, after);
    mText = newText;

    mGapLength += delta;
    if (mGapLength < 1)
        new Exception("mGapLength < 1").printStackTrace();

    if (mSpanCount != 0) {
        for (int i = 0; i < mSpanCount; i++) {
            if (mSpanStarts[i] > mGapStart) mSpanStarts[i] += delta;
            if (mSpanEnds[i] > mGapStart) mSpanEnds[i] += delta;
        }
        calcMax(treeRoot());
    }
}
 
Example #9
Source File: SparseBooleanArray.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Puts a key/value pair into the array, optimizing for the case where
 * the key is greater than all existing keys in the array.
 */
public void append(int key, boolean value) {
    if (mSize != 0 && key <= mKeys[mSize - 1]) {
        put(key, value);
        return;
    }

    int pos = mSize;
    if (pos >= mKeys.length) {
        int n = ArrayUtils.idealIntArraySize(pos + 1);

        int[] nkeys = new int[n];
        boolean[] nvalues = new boolean[n];

        // Log.e("SparseBooleanArray", "grow " + mKeys.length + " to " + n);
        System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
        System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

        mKeys = nkeys;
        mValues = nvalues;
    }

    mKeys[pos] = key;
    mValues[pos] = value;
    mSize = pos + 1;
}
 
Example #10
Source File: AccessibilityInteractionClient.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Finalize an {@link AccessibilityNodeInfo} before passing it to the client.
 *
 * @param info The info.
 * @param connectionId The id of the connection to the system.
 * @param bypassCache Whether or not to bypass the cache. The node is added to the cache if
 *                    this value is {@code false}
 * @param packageNames The valid package names a node can come from.
 */
private void finalizeAndCacheAccessibilityNodeInfo(AccessibilityNodeInfo info,
        int connectionId, boolean bypassCache, String[] packageNames) {
    if (info != null) {
        info.setConnectionId(connectionId);
        // Empty array means any package name is Okay
        if (!ArrayUtils.isEmpty(packageNames)) {
            CharSequence packageName = info.getPackageName();
            if (packageName == null
                    || !ArrayUtils.contains(packageNames, packageName.toString())) {
                // If the node package not one of the valid ones, pick the top one - this
                // is one of the packages running in the introspected UID.
                info.setPackageName(packageNames[0]);
            }
        }
        info.setSealed(true);
        if (!bypassCache) {
            sAccessibilityCache.add(info);
        }
    }
}
 
Example #11
Source File: DateTimeKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public DateTimeKeyListener(@Nullable Locale locale) {
    final LinkedHashSet<Character> chars = new LinkedHashSet<>();
    // First add the digits. Then, add all the character in AM and PM markers. Finally, add all
    // the non-pattern characters seen in the patterns for "yMdhms" and "yMdHms".
    final boolean success = NumberKeyListener.addDigits(chars, locale)
                      && NumberKeyListener.addAmPmChars(chars, locale)
                      && NumberKeyListener.addFormatCharsFromSkeleton(
                          chars, locale, SKELETON_12HOUR, SYMBOLS_TO_IGNORE)
                      && NumberKeyListener.addFormatCharsFromSkeleton(
                          chars, locale, SKELETON_24HOUR, SYMBOLS_TO_IGNORE);
    if (success) {
        mCharacters = NumberKeyListener.collectionToArray(chars);
        if (locale != null && "en".equals(locale.getLanguage())) {
            // For backward compatibility reasons, assume we don't need advanced input for
            // English locales, although English locales literally also need a comma and perhaps
            // uppercase letters for AM and PM.
            mNeedsAdvancedInput = false;
        } else {
            mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
        }
    } else {
        mCharacters = CHARACTERS;
        mNeedsAdvancedInput = false;
    }
}
 
Example #12
Source File: SparseIntArray.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Puts a key/value pair into the array, optimizing for the case where
 * the key is greater than all existing keys in the array.
 */
public void append(int key, int value) {
    if (mSize != 0 && key <= mKeys[mSize - 1]) {
        put(key, value);
        return;
    }

    int pos = mSize;
    if (pos >= mKeys.length) {
        int n = ArrayUtils.idealIntArraySize(pos + 1);

        int[] nkeys = new int[n];
        int[] nvalues = new int[n];

        // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
        System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
        System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

        mKeys = nkeys;
        mValues = nvalues;
    }

    mKeys[pos] = key;
    mValues[pos] = value;
    mSize = pos + 1;
}
 
Example #13
Source File: StorageManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
    enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);

    if (StorageManager.isFileEncryptedNativeOrEmulated()) {
        // When a user has secure lock screen, require secret to actually unlock.
        // This check is mostly in place for emulation mode.
        if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(secret)) {
            throw new IllegalStateException("Secret required to unlock secure user " + userId);
        }

        try {
            mVold.unlockUserKey(userId, serialNumber, encodeBytes(token),
                    encodeBytes(secret));
        } catch (Exception e) {
            Slog.wtf(TAG, e);
            return;
        }
    }

    synchronized (mLock) {
        mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
    }
}
 
Example #14
Source File: NetworkStats.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Only keep entries that match all specified filters.
 *
 * <p>This mutates the original structure in place. After this method is called,
 * size is the number of matching entries, and capacity is the previous capacity.
 * @param limitUid UID to filter for, or {@link #UID_ALL}.
 * @param limitIfaces Interfaces to filter for, or {@link #INTERFACES_ALL}.
 * @param limitTag Tag to filter for, or {@link #TAG_ALL}.
 */
public void filter(int limitUid, String[] limitIfaces, int limitTag) {
    if (limitUid == UID_ALL && limitTag == TAG_ALL && limitIfaces == INTERFACES_ALL) {
        return;
    }

    Entry entry = new Entry();
    int nextOutputEntry = 0;
    for (int i = 0; i < size; i++) {
        entry = getValues(i, entry);
        final boolean matches =
                (limitUid == UID_ALL || limitUid == entry.uid)
                && (limitTag == TAG_ALL || limitTag == entry.tag)
                && (limitIfaces == INTERFACES_ALL
                        || ArrayUtils.contains(limitIfaces, entry.iface));

        if (matches) {
            setValues(nextOutputEntry, entry);
            nextOutputEntry++;
        }
    }

    size = nextOutputEntry;
}
 
Example #15
Source File: NetworkStatsCollection.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Remove any {@link NetworkStatsHistory} attributed to the requested UID,
 * moving any {@link NetworkStats#TAG_NONE} series to
 * {@link TrafficStats#UID_REMOVED}.
 */
public void removeUids(int[] uids) {
    final ArrayList<Key> knownKeys = Lists.newArrayList();
    knownKeys.addAll(mStats.keySet());

    // migrate all UID stats into special "removed" bucket
    for (Key key : knownKeys) {
        if (ArrayUtils.contains(uids, key.uid)) {
            // only migrate combined TAG_NONE history
            if (key.tag == TAG_NONE) {
                final NetworkStatsHistory uidHistory = mStats.get(key);
                final NetworkStatsHistory removedHistory = findOrCreateHistory(
                        key.ident, UID_REMOVED, SET_DEFAULT, TAG_NONE);
                removedHistory.recordEntireHistory(uidHistory);
            }
            mStats.remove(key);
            mDirty = true;
        }
    }
}
 
Example #16
Source File: TimeKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public TimeKeyListener(@Nullable Locale locale) {
    final LinkedHashSet<Character> chars = new LinkedHashSet<>();
    // First add the digits. Then, add all the character in AM and PM markers. Finally, add all
    // the non-pattern characters seen in the patterns for "hms" and "Hms".
    final boolean success = NumberKeyListener.addDigits(chars, locale)
                      && NumberKeyListener.addAmPmChars(chars, locale)
                      && NumberKeyListener.addFormatCharsFromSkeleton(
                          chars, locale, SKELETON_12HOUR, SYMBOLS_TO_IGNORE)
                      && NumberKeyListener.addFormatCharsFromSkeleton(
                          chars, locale, SKELETON_24HOUR, SYMBOLS_TO_IGNORE);
    if (success) {
        mCharacters = NumberKeyListener.collectionToArray(chars);
        if (locale != null && "en".equals(locale.getLanguage())) {
            // For backward compatibility reasons, assume we don't need advanced input for
            // English locales, although English locales may need uppercase letters for
            // AM and PM.
            mNeedsAdvancedInput = false;
        } else {
            mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
        }
    } else {
        mCharacters = CHARACTERS;
        mNeedsAdvancedInput = false;
    }
}
 
Example #17
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Clean up {@link #mUidRecorder} after user is removed.
 */
@GuardedBy("mStatsLock")
private void removeUserLocked(int userId) {
    if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);

    // Build list of UIDs that we should clean up
    int[] uids = new int[0];
    final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
            PackageManager.MATCH_ANY_USER
            | PackageManager.MATCH_DISABLED_COMPONENTS);
    for (ApplicationInfo app : apps) {
        final int uid = UserHandle.getUid(userId, app.uid);
        uids = ArrayUtils.appendInt(uids, uid);
    }

    removeUidsLocked(uids);
}
 
Example #18
Source File: WatchlistLoggingHandler.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Get app digest from app uid.
 * Return null if system cannot get digest from uid.
 */
@Nullable
private byte[] getDigestFromUid(int uid) {
    return mCachedUidDigestMap.computeIfAbsent(uid, key -> {
        final String[] packageNames = mPm.getPackagesForUid(key);
        final int userId = UserHandle.getUserId(uid);
        if (!ArrayUtils.isEmpty(packageNames)) {
            for (String packageName : packageNames) {
                try {
                    final String apkPath = mPm.getPackageInfoAsUser(packageName,
                            PackageManager.MATCH_DIRECT_BOOT_AWARE
                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId)
                            .applicationInfo.publicSourceDir;
                    if (TextUtils.isEmpty(apkPath)) {
                        Slog.w(TAG, "Cannot find apkPath for " + packageName);
                        continue;
                    }
                    return DigestUtils.getSha256Hash(new File(apkPath));
                } catch (NameNotFoundException | NoSuchAlgorithmException | IOException e) {
                    Slog.e(TAG, "Should not happen", e);
                    return null;
                }
            }
        }
        // Not able to find a package name for this uid, possibly the package is installed on
        // another user.
        return null;
    });
}
 
Example #19
Source File: WebViewDelegate.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the WebView asset path to {@link android.content.res.AssetManager}.
 */
public void addWebViewAssetPath(Context context) {
    final String newAssetPath = WebViewFactory.getLoadedPackageInfo().applicationInfo.sourceDir;

    final ApplicationInfo appInfo = context.getApplicationInfo();
    final String[] libs = appInfo.sharedLibraryFiles;
    if (!ArrayUtils.contains(libs, newAssetPath)) {
        // Build the new library asset path list.
        final int newLibAssetsCount = 1 + (libs != null ? libs.length : 0);
        final String[] newLibAssets = new String[newLibAssetsCount];
        if (libs != null) {
            System.arraycopy(libs, 0, newLibAssets, 0, libs.length);
        }
        newLibAssets[newLibAssetsCount - 1] = newAssetPath;

        // Update the ApplicationInfo object with the new list.
        // We know this will persist and future Resources created via ResourcesManager
        // will include the shared library because this ApplicationInfo comes from the
        // underlying LoadedApk in ContextImpl, which does not change during the life of the
        // application.
        appInfo.sharedLibraryFiles = newLibAssets;

        // Update existing Resources with the WebView library.
        ResourcesManager.getInstance().appendLibAssetForMainAssetPath(
                appInfo.getBaseResourcePath(), newAssetPath);
    }
}
 
Example #20
Source File: TextUtils.java    From j2objc with Apache License 2.0 5 votes vote down vote up
static char[] obtain(int len) {
    char[] buf;

    synchronized (sLock) {
        buf = sTemp;
        sTemp = null;
    }

    if (buf == null || buf.length < len)
        buf = new char[ArrayUtils.idealCharArraySize(len)];

    return buf;
}
 
Example #21
Source File: Nat464Xlat.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether a network requires clat.
 * @param network the NetworkAgentInfo corresponding to the network.
 * @return true if the network requires clat, false otherwise.
 */
public static boolean requiresClat(NetworkAgentInfo nai) {
    // TODO: migrate to NetworkCapabilities.TRANSPORT_*.
    final boolean supported = ArrayUtils.contains(NETWORK_TYPES, nai.networkInfo.getType());
    final boolean connected = ArrayUtils.contains(NETWORK_STATES, nai.networkInfo.getState());
    // We only run clat on networks that don't have a native IPv4 address.
    final boolean hasIPv4Address =
            (nai.linkProperties != null) && nai.linkProperties.hasIPv4Address();
    return supported && connected && !hasIPv4Address;
}
 
Example #22
Source File: PackageKeySetData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
protected void addUpgradeKeySet(String alias) {
    if (alias == null) {
        return;
    }

    /* must have previously been defined */
    Long ks = mKeySetAliases.get(alias);
    if (ks != null) {
        mUpgradeKeySets = ArrayUtils.appendLong(mUpgradeKeySets, ks);
    } else {
        throw new IllegalArgumentException("Upgrade keyset alias " + alias
                + "does not refer to a defined keyset alias!");
    }
}
 
Example #23
Source File: NetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private CaptivePortalProbeSpec nextFallbackSpec() {
    if (ArrayUtils.isEmpty(mCaptivePortalFallbackSpecs)) {
        return null;
    }
    // Randomly change spec without memory. Also randomize the first attempt.
    final int idx = Math.abs(new Random().nextInt()) % mCaptivePortalFallbackSpecs.length;
    return mCaptivePortalFallbackSpecs[idx];
}
 
Example #24
Source File: AppStateTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @return whether force-app-standby is effective for a UID package-name.
 */
private boolean isRestricted(int uid, @NonNull String packageName,
        boolean useTempWhitelistToo, boolean exemptOnBatterySaver) {
    if (isUidActive(uid)) {
        return false;
    }
    synchronized (mLock) {
        // Whitelisted?
        final int appId = UserHandle.getAppId(uid);
        if (ArrayUtils.contains(mPowerWhitelistedAllAppIds, appId)) {
            return false;
        }
        if (useTempWhitelistToo &&
                ArrayUtils.contains(mTempWhitelistedAppIds, appId)) {
            return false;
        }
        if (mForcedAppStandbyEnabled && isRunAnyRestrictedLocked(uid, packageName)) {
            return true;
        }
        if (exemptOnBatterySaver) {
            return false;
        }
        final int userId = UserHandle.getUserId(uid);
        if (mExemptedPackages.contains(userId, packageName)) {
            return false;
        }
        return mForceAllAppsStandby;
    }
}
 
Example #25
Source File: DateKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public DateKeyListener(@Nullable Locale locale) {
    final LinkedHashSet<Character> chars = new LinkedHashSet<>();
    // First add the digits, then add all the non-pattern characters seen in the pattern for
    // "yMd", which is supposed to only have numerical fields.
    final boolean success = NumberKeyListener.addDigits(chars, locale)
                            && NumberKeyListener.addFormatCharsFromSkeletons(
                                    chars, locale, SKELETONS, SYMBOLS_TO_IGNORE);
    if (success) {
        mCharacters = NumberKeyListener.collectionToArray(chars);
        mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
    } else {
        mCharacters = CHARACTERS;
        mNeedsAdvancedInput = false;
    }
}
 
Example #26
Source File: ResourcesManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Appends the library asset path to any ResourcesImpl object that contains the main
 * assetPath.
 * @param assetPath The main asset path for which to add the library asset path.
 * @param libAsset The library asset path to add.
 */
public void appendLibAssetForMainAssetPath(String assetPath, String libAsset) {
    synchronized (this) {
        // Record which ResourcesImpl need updating
        // (and what ResourcesKey they should update to).
        final ArrayMap<ResourcesImpl, ResourcesKey> updatedResourceKeys = new ArrayMap<>();

        final int implCount = mResourceImpls.size();
        for (int i = 0; i < implCount; i++) {
            final ResourcesKey key = mResourceImpls.keyAt(i);
            final WeakReference<ResourcesImpl> weakImplRef = mResourceImpls.valueAt(i);
            final ResourcesImpl impl = weakImplRef != null ? weakImplRef.get() : null;
            if (impl != null && Objects.equals(key.mResDir, assetPath)) {
                if (!ArrayUtils.contains(key.mLibDirs, libAsset)) {
                    final int newLibAssetCount = 1 +
                            (key.mLibDirs != null ? key.mLibDirs.length : 0);
                    final String[] newLibAssets = new String[newLibAssetCount];
                    if (key.mLibDirs != null) {
                        System.arraycopy(key.mLibDirs, 0, newLibAssets, 0, key.mLibDirs.length);
                    }
                    newLibAssets[newLibAssetCount - 1] = libAsset;

                    updatedResourceKeys.put(impl, new ResourcesKey(
                            key.mResDir,
                            key.mSplitResDirs,
                            key.mOverlayDirs,
                            newLibAssets,
                            key.mDisplayId,
                            key.mOverrideConfiguration,
                            key.mCompatInfo));
                }
            }
        }

        redirectResourcesToNewImplLocked(updatedResourceKeys);
    }
}
 
Example #27
Source File: SparseBooleanArray.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a mapping from the specified key to the specified value,
 * replacing the previous mapping from the specified key if there
 * was one.
 */
public void put(int key, boolean value) {
    int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

    if (i >= 0) {
        mValues[i] = value;
    } else {
        i = ~i;

        if (mSize >= mKeys.length) {
            int n = ArrayUtils.idealIntArraySize(mSize + 1);

            int[] nkeys = new int[n];
            boolean[] nvalues = new boolean[n];

            // Log.e("SparseBooleanArray", "grow " + mKeys.length + " to " + n);
            System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
            System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

            mKeys = nkeys;
            mValues = nvalues;
        }

        if (mSize - i != 0) {
            // Log.e("SparseBooleanArray", "move " + (mSize - i));
            System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
            System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
        }

        mKeys[i] = key;
        mValues[i] = value;
        mSize++;
    }
}
 
Example #28
Source File: PackedIntVector.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Grows the value and gap arrays to be large enough to store at least
 * one more than the current number of rows.
 */
private final void growBuffer() {
    final int columns = mColumns;
    int[] newvalues = ArrayUtils.newUnpaddedIntArray(
            GrowingArrayUtils.growSize(size()) * columns);
    int newsize = newvalues.length / columns;

    final int[] valuegap = mValueGap;
    final int rowgapstart = mRowGapStart;

    int after = mRows - (rowgapstart + mRowGapLength);

    if (mValues != null) {
        System.arraycopy(mValues, 0, newvalues, 0, columns * rowgapstart);
        System.arraycopy(mValues, (mRows - after) * columns,
                         newvalues, (newsize - after) * columns,
                         after * columns);
    }

    for (int i = 0; i < columns; i++) {
        if (valuegap[i] >= rowgapstart) {
            valuegap[i] += newsize - mRows;

            if (valuegap[i] < rowgapstart) {
                valuegap[i] = rowgapstart;
            }
        }
    }

    mRowGapLength += newsize - mRows;
    mRows = newsize;
    mValues = newvalues;
}
 
Example #29
Source File: SparseBooleanArray.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new SparseBooleanArray containing no mappings that will not
 * require any additional memory allocation to store the specified
 * number of mappings.  If you supply an initial capacity of 0, the
 * sparse array will be initialized with a light-weight representation
 * not requiring any additional array allocations.
 */
public SparseBooleanArray(int initialCapacity) {
    if (initialCapacity == 0) {
        mKeys = ContainerHelpers.EMPTY_INTS;
        mValues = ContainerHelpers.EMPTY_BOOLEANS;
    } else {
        initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
        mKeys = new int[initialCapacity];
        mValues = new boolean[initialCapacity];
    }
    mSize = 0;
}
 
Example #30
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public String[] getKeyboardLayouts(String inputDeviceDescriptor) {
    InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, false);
    if (state == null) {
        return (String[])ArrayUtils.emptyArray(String.class);
    }
    return state.getKeyboardLayouts();
}