Request newRequest(IVoiceInteractorCallback callback) {
   synchronized (this) {
     Request req = new Request(callback, this);
     mActiveRequests.put(req.mInterface.asBinder(), req);
     return req;
   }
 }
    private void registerClientLocked(IMediaRouterClient client,
            int pid, String packageName, int userId, boolean trusted) {
        final IBinder binder = client.asBinder();
        ClientRecord clientRecord = mAllClientRecords.get(binder);
        if (clientRecord == null) {
            boolean newUser = false;
            UserRecord userRecord = mUserRecords.get(userId);
            if (userRecord == null) {
                userRecord = new UserRecord(userId);
                newUser = true;
            }
            clientRecord = new ClientRecord(userRecord, client, pid, packageName, trusted);
            try {
                binder.linkToDeath(clientRecord, 0);
            } catch (RemoteException ex) {
                throw new RuntimeException("Media router client died prematurely.", ex);
            }

            if (newUser) {
                mUserRecords.put(userId, userRecord);
                initializeUserLocked(userRecord);
            }

            userRecord.mClientRecords.add(clientRecord);
            mAllClientRecords.put(binder, clientRecord);
            initializeClientLocked(clientRecord);
        }
    }
 private final void remove_all_objects(ArrayMap<String, F[]> map, String name, Object object) {
   F[] array = map.get(name);
   if (array != null) {
     int LAST = array.length - 1;
     while (LAST >= 0 && array[LAST] == null) {
       LAST--;
     }
     for (int idx = LAST; idx >= 0; idx--) {
       if (array[idx] == object) {
         final int remain = LAST - idx;
         if (remain > 0) {
           System.arraycopy(array, idx + 1, array, idx, remain);
         }
         array[LAST] = null;
         LAST--;
       }
     }
     if (LAST < 0) {
       map.remove(name);
     } else if (LAST < (array.length / 2)) {
       F[] newa = newArray(LAST + 2);
       System.arraycopy(array, 0, newa, 0, LAST + 1);
       map.put(name, newa);
     }
   }
 }
Ejemplo n.º 4
0
 /**
  * Perform a {@link #put(Object, Object)} of all key/value pairs in <var>map</var>
  *
  * @param map The map whose contents are to be retrieved.
  */
 @Override
 public void putAll(Map<? extends K, ? extends V> map) {
   ensureCapacity(mSize + map.size());
   for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
     put(entry.getKey(), entry.getValue());
   }
 }
Ejemplo n.º 5
0
 /**
  * Special fast path for appending items to the end of the array without validation. The array
  * must already be large enough to contain the item.
  *
  * @hide
  */
 public void append(K key, V value) {
   int index = mSize;
   final int hash = key == null ? 0 : key.hashCode();
   if (index >= mHashes.length) {
     throw new IllegalStateException("Array is full");
   }
   if (index > 0 && mHashes[index - 1] > hash) {
     RuntimeException e = new RuntimeException("here");
     e.fillInStackTrace();
     Log.w(
         TAG,
         "New hash "
             + hash
             + " is before end of array hash "
             + mHashes[index - 1]
             + " at index "
             + index
             + " key "
             + key,
         e);
     put(key, value);
     return;
   }
   mSize = index + 1;
   mHashes[index] = hash;
   index <<= 1;
   mArray[index] = key;
   mArray[index + 1] = value;
 }
 /**
  * Sets a specific transition to occur when the given pair of scenes is exited/entered.
  *
  * @param fromScene The scene being exited when the given transition will be run
  * @param toScene The scene being entered when the given transition will be run
  * @param transition The transition that will play when the given scene is entered. A value of
  *     null will result in the default behavior of using the default transition instead.
  */
 public void setTransition(Scene fromScene, Scene toScene, Transition transition) {
   ArrayMap<Scene, Transition> sceneTransitionMap = mScenePairTransitions.get(toScene);
   if (sceneTransitionMap == null) {
     sceneTransitionMap = new ArrayMap<Scene, Transition>();
     mScenePairTransitions.put(toScene, sceneTransitionMap);
   }
   sceneTransitionMap.put(fromScene, transition);
 }
 private void snooze() {
   if (mMostRecentPackageName != null) {
     mSnoozedPackages.put(
         snoozeKey(mMostRecentPackageName, mUser),
         SystemClock.elapsedRealtime() + mSnoozeLengthMs);
   }
   releaseAndClose();
 }
 static {
   METADATA_KEYS_TYPE = new ArrayMap<String, Integer>();
   METADATA_KEYS_TYPE.put(METADATA_KEY_RDS_PI, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_RDS_PS, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_RDS_PTY, METADATA_TYPE_INT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_RBDS_PTY, METADATA_TYPE_INT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_RDS_RT, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_TITLE, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_ARTIST, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_ALBUM, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_GENRE, METADATA_TYPE_TEXT);
   METADATA_KEYS_TYPE.put(METADATA_KEY_ICON, METADATA_TYPE_BITMAP);
   METADATA_KEYS_TYPE.put(METADATA_KEY_ART, METADATA_TYPE_BITMAP);
 }
  private void startObserving(File file, Uri notifyUri) {
    synchronized (mObservers) {
      DirectoryObserver observer = mObservers.get(file);
      if (observer == null) {
        observer = new DirectoryObserver(file, getContext().getContentResolver(), notifyUri);
        observer.startWatching();
        mObservers.put(file, observer);
      }
      observer.mRefCount++;

      if (LOG_INOTIFY) Log.d(TAG, "after start: " + observer);
    }
  }
 private final void addFilter(ArrayMap<String, F[]> map, String name, F filter) {
   F[] array = map.get(name);
   if (array == null) {
     array = newArray(2);
     map.put(name, array);
     array[0] = filter;
   } else {
     final int N = array.length;
     int i = N;
     while (i > 0 && array[i - 1] == null) {
       i--;
     }
     if (i < N) {
       array[i] = filter;
     } else {
       F[] newa = newArray((N * 3) / 2);
       System.arraycopy(array, 0, newa, 0, N);
       newa[N] = filter;
       map.put(name, newa);
     }
   }
 }
 public boolean getAppsWithPermissionsCount(Context context, int[] counts) {
   ArraySet<String> launcherPkgs = Utils.getLauncherPackages(context);
   // Indexed by uid.
   ArrayMap<String, Boolean> grantedApps = new ArrayMap<>();
   ArrayMap<String, Boolean> allApps = new ArrayMap<>();
   for (String group : Utils.MODERN_PERMISSION_GROUPS) {
     PermissionApps permissionApps = new PermissionApps(context, group, null);
     permissionApps.loadNowWithoutUi();
     for (PermissionApp app : permissionApps.getApps()) {
       String key = app.getKey();
       if (Utils.isSystem(app, launcherPkgs)) {
         // We default to not showing system apps, so hide them from count.
         continue;
       }
       if (app.areRuntimePermissionsGranted()) {
         grantedApps.put(key, true);
       }
       allApps.put(key, true);
     }
   }
   counts[0] = grantedApps.size();
   counts[1] = allApps.size();
   return true;
 }
Ejemplo n.º 12
0
 /**
  * Perform a {@link #put(Object, Object)} of all key/value pairs in <var>array</var>
  *
  * @param array The array whose contents are to be retrieved.
  */
 public void putAll(ArrayMap<? extends K, ? extends V> array) {
   final int N = array.mSize;
   ensureCapacity(mSize + N);
   if (mSize == 0) {
     if (N > 0) {
       System.arraycopy(array.mHashes, 0, mHashes, 0, N);
       System.arraycopy(array.mArray, 0, mArray, 0, N << 1);
       mSize = N;
     }
   } else {
     for (int i = 0; i < N; i++) {
       put(array.keyAt(i), array.valueAt(i));
     }
   }
 }
  public void addSimulatedPort(String portId, int supportedModes, IndentingPrintWriter pw) {
    synchronized (mLock) {
      if (mSimulatedPorts.containsKey(portId)) {
        pw.println("Port with same name already exists.  Please remove it first.");
        return;
      }

      pw.println(
          "Adding simulated port: portId="
              + portId
              + ", supportedModes="
              + UsbPort.modeToString(supportedModes));
      mSimulatedPorts.put(portId, new SimulatedPortInfo(portId, supportedModes));
      updatePortsLocked(pw);
    }
  }
 private void createPkgMap(
     ArrayList<ProcStatsEntry> procEntries,
     ProcessDataCollection bgTotals,
     ProcessDataCollection runTotals) {
   // Combine processes into packages.
   ArrayMap<String, ProcStatsPackageEntry> pkgMap = new ArrayMap<>();
   for (int i = procEntries.size() - 1; i >= 0; i--) {
     ProcStatsEntry proc = procEntries.get(i);
     proc.evaluateTargetPackage(mPm, mStats, bgTotals, runTotals, sEntryCompare, mUseUss);
     ProcStatsPackageEntry pkg = pkgMap.get(proc.mBestTargetPackage);
     if (pkg == null) {
       pkg = new ProcStatsPackageEntry(proc.mBestTargetPackage, memTotalTime);
       pkgMap.put(proc.mBestTargetPackage, pkg);
       pkgEntries.add(pkg);
     }
     pkg.addEntry(proc);
   }
 }
Ejemplo n.º 15
0
  /**
   * Get running process information from AMS and get the same pid , uid process.
   *
   * @param pid process id
   * @param uid user id
   * @return process record
   */
  private ProcessRecord createProcessRecordLocked(int pid, int uid) {

    ProcessRecord record = mProcessRecords.get(pid);
    if (record == null) {
      try {
        List<RunningAppProcessInfo> procInfos = mActivityManager.getRunningAppProcesses();
        if (procInfos != null && procInfos.size() > 0) {
          for (RunningAppProcessInfo info : procInfos) {
            if (info.pid == pid && info.uid == uid) {
              record = new ProcessRecord(info.pid, info.uid, info.processName);
              mProcessRecords.put(pid, record);
              break;
            }
          }
        }
      } catch (RemoteException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, "IPC Exception while get process info from AMS " + e.toString());
      }
    }

    return record;
  }
Ejemplo n.º 16
0
 public <T extends RxViewDispatch> void registerRxError(final T object) {
   String tag = object.getClass().getSimpleName() + "_error";
   Subscription subscription = mRxActionMap.get(tag);
   if (subscription == null || subscription.isUnsubscribed()) {
     mRxActionMap.put(
         tag,
         mBus.get()
             .filter(
                 new Func1<Object, Boolean>() {
                   @Override
                   public Boolean call(Object obj) {
                     return obj instanceof RxError;
                   }
                 })
             .subscribe(
                 new Action1<Object>() {
                   @Override
                   public void call(Object obj) {
                     object.onRxError((RxError) obj);
                   }
                 }));
   }
 }
Ejemplo n.º 17
0
 private void putCache(String key, int userId, Object value) {
   synchronized (mCache) {
     // Create a new key, because this will be stored in the map.
     mCache.put(new CacheKey().set(key, userId), value);
   }
 }
Ejemplo n.º 18
0
  private void setPDFMap() {
    bookPDFMap = new ArrayMap<>();

    bookPDFMap.put(
        "College Physics",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/College_Physics-LR.pdf");
    bookPDFMap.put(
        "Concepts of Biology",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Concepts_of_Biology-LR.pdf");
    bookPDFMap.put(
        "Principles of Microeconomics for AP® Courses",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Principles_of_Microeconomics_for_AP_Courses-LR.pdf");
    bookPDFMap.put(
        "U.S. History",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/U.S._History-LR.pdf");
    bookPDFMap.put(
        "University Physics Volume 3",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/UniversityPhysicsVolume3-LR.pdf");
    bookPDFMap.put(
        "Biology",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Biology-LR.pdf");
    bookPDFMap.put(
        "Algebra and Trigonometry",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Algebra_and_Trigonometry-LR.pdf");
    bookPDFMap.put(
        "Prealgebra",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Prealgebra-LR.pdf");
    bookPDFMap.put(
        "Calculus Volume 2",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/CalculusVolume2-LR.pdf");
    bookPDFMap.put(
        "American Government",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/American_Government_-_LR_20161114.pdf");
    bookPDFMap.put(
        "Microeconomics",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Principles_of_Microeconomics-LR.pdf");
    bookPDFMap.put(
        "Principles of Macroeconomics for AP® Courses",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Principles_of_Macroeconomics_for_AP_Courses-LR.pdf");
    bookPDFMap.put(
        "Astronomy",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Astronomy-LR.pdf");
    bookPDFMap.put(
        "Chemistry",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Chemistry-LR.pdf");
    bookPDFMap.put(
        "College Physics For AP® Courses",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/CollegePhysicsforAPCourses-LR.pdf");
    bookPDFMap.put(
        "Introduction to Sociology 2e",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/IntroductionToSociology2e-LR.pdf");
    bookPDFMap.put(
        "Microbiology",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Microbiology-LR.pdf");
    bookPDFMap.put(
        "College Algebra",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/College_Algebra-LR.pdf");
    bookPDFMap.put(
        "Introductory Statistics",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Introductory_Statistics-LR.pdf");
    bookPDFMap.put(
        "Psychology",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Psychology-LR.pdf");
    bookPDFMap.put(
        "Chemistry: Atoms First",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Chemistry_Atoms_First-LR.pdf");
    bookPDFMap.put(
        "University Physics Volume 2",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/University_Physics_Volume_2-LR_20161006.pdf");
    bookPDFMap.put(
        "Calculus Volume 1",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/CalculusVolume1-LR.pdf");
    bookPDFMap.put(
        "Precalculus",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/OpenStax_Precalc_2015_v2-LR.pdf");
    bookPDFMap.put(
        "University Physics Volume 1",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/University_Physics_Volume_1-LR.pdf");
    bookPDFMap.put(
        "Anatomy & Physiology",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Anatomy_and_Physiology-LR.pdf");
    bookPDFMap.put(
        "Macroeconomics",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Principles_of_Macroeconomics-LR.pdf");
    bookPDFMap.put(
        "Calculus Volume 3",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/CalculusVolume3-LR.pdf");
    bookPDFMap.put(
        "Principles of Economics",
        "https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Principles_of_Economics-LR.pdf");
  }
  private void updateVolumesLocked() {
    mRoots.clear();

    final int userId = UserHandle.myUserId();
    final List<VolumeInfo> volumes = mStorageManager.getVolumes();
    for (VolumeInfo volume : volumes) {
      if (!volume.isMountedReadable()) continue;

      final String rootId;
      final String title;
      if (volume.getType() == VolumeInfo.TYPE_EMULATED) {
        // We currently only support a single emulated volume mounted at
        // a time, and it's always considered the primary
        rootId = ROOT_ID_PRIMARY_EMULATED;
        if (VolumeInfo.ID_EMULATED_INTERNAL.equals(volume.getId())) {
          title = getContext().getString(R.string.root_internal_storage);
        } else {
          final VolumeInfo privateVol = mStorageManager.findPrivateForEmulated(volume);
          title = mStorageManager.getBestVolumeDescription(privateVol);
        }
      } else if (volume.getType() == VolumeInfo.TYPE_PUBLIC) {
        rootId = volume.getFsUuid();
        title = mStorageManager.getBestVolumeDescription(volume);
      } else {
        // Unsupported volume; ignore
        continue;
      }

      if (TextUtils.isEmpty(rootId)) {
        Log.d(TAG, "Missing UUID for " + volume.getId() + "; skipping");
        continue;
      }
      if (mRoots.containsKey(rootId)) {
        Log.w(TAG, "Duplicate UUID " + rootId + " for " + volume.getId() + "; skipping");
        continue;
      }

      try {
        final RootInfo root = new RootInfo();
        mRoots.put(rootId, root);

        root.rootId = rootId;
        root.flags =
            Root.FLAG_SUPPORTS_CREATE
                | Root.FLAG_LOCAL_ONLY
                | Root.FLAG_ADVANCED
                | Root.FLAG_SUPPORTS_SEARCH
                | Root.FLAG_SUPPORTS_IS_CHILD;
        root.title = title;
        if (volume.getType() == VolumeInfo.TYPE_PUBLIC) {
          root.flags |= Root.FLAG_HAS_SETTINGS;
        }
        if (volume.isVisibleForRead(userId)) {
          root.visiblePath = volume.getPathForUser(userId);
        } else {
          root.visiblePath = null;
        }
        root.path = volume.getInternalPathForUser(userId);
        root.docId = getDocIdForFile(root.path);

      } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
      }
    }

    Log.d(TAG, "After updating volumes, found " + mRoots.size() + " active roots");

    // Note this affects content://com.android.externalstorage.documents/root/39BD-07C5
    // as well as content://com.android.externalstorage.documents/document/*/children,
    // so just notify on content://com.android.externalstorage.documents/.
    getContext().getContentResolver().notifyChange(BASE_URI, null, false);
  }
 /**
  * Sets a specific transition to occur when the given scene is entered.
  *
  * @param scene The scene which, when applied, will cause the given transition to run.
  * @param transition The transition that will play when the given scene is entered. A value of
  *     null will result in the default behavior of using the default transition instead.
  */
 public void setTransition(Scene scene, Transition transition) {
   mSceneTransitions.put(scene, transition);
 }
 boolean dumpMap(
     PrintWriter out,
     String titlePrefix,
     String title,
     String prefix,
     ArrayMap<String, F[]> map,
     String packageName,
     boolean printFilter,
     boolean collapseDuplicates) {
   final String eprefix = prefix + "  ";
   final String fprefix = prefix + "    ";
   final ArrayMap<Object, MutableInt> found = new ArrayMap<>();
   boolean printedSomething = false;
   Printer printer = null;
   for (int mapi = 0; mapi < map.size(); mapi++) {
     F[] a = map.valueAt(mapi);
     final int N = a.length;
     boolean printedHeader = false;
     F filter;
     if (collapseDuplicates && !printFilter) {
       found.clear();
       for (int i = 0; i < N && (filter = a[i]) != null; i++) {
         if (packageName != null && !isPackageForFilter(packageName, filter)) {
           continue;
         }
         Object label = filterToLabel(filter);
         int index = found.indexOfKey(label);
         if (index < 0) {
           found.put(label, new MutableInt(1));
         } else {
           found.valueAt(index).value++;
         }
       }
       for (int i = 0; i < found.size(); i++) {
         if (title != null) {
           out.print(titlePrefix);
           out.println(title);
           title = null;
         }
         if (!printedHeader) {
           out.print(eprefix);
           out.print(map.keyAt(mapi));
           out.println(":");
           printedHeader = true;
         }
         printedSomething = true;
         dumpFilterLabel(out, fprefix, found.keyAt(i), found.valueAt(i).value);
       }
     } else {
       for (int i = 0; i < N && (filter = a[i]) != null; i++) {
         if (packageName != null && !isPackageForFilter(packageName, filter)) {
           continue;
         }
         if (title != null) {
           out.print(titlePrefix);
           out.println(title);
           title = null;
         }
         if (!printedHeader) {
           out.print(eprefix);
           out.print(map.keyAt(mapi));
           out.println(":");
           printedHeader = true;
         }
         printedSomething = true;
         dumpFilter(out, fprefix, filter);
         if (printFilter) {
           if (printer == null) {
             printer = new PrintWriterPrinter(out);
           }
           filter.dump(printer, fprefix + "  ");
         }
       }
     }
   }
   return printedSomething;
 }
  // Must only be called by updatePortsLocked.
  private void addOrUpdatePortLocked(
      String portId,
      int supportedModes,
      int currentMode,
      boolean canChangeMode,
      int currentPowerRole,
      boolean canChangePowerRole,
      int currentDataRole,
      boolean canChangeDataRole,
      IndentingPrintWriter pw) {
    // Only allow mode switch capability for dual role ports.
    // Validate that the current mode matches the supported modes we expect.
    if (supportedModes != UsbPort.MODE_DUAL) {
      canChangeMode = false;
      if (currentMode != 0 && currentMode != supportedModes) {
        logAndPrint(
            Log.WARN,
            pw,
            "Ignoring inconsistent current mode from USB "
                + "port driver: supportedModes="
                + UsbPort.modeToString(supportedModes)
                + ", currentMode="
                + UsbPort.modeToString(currentMode));
        currentMode = 0;
      }
    }

    // Determine the supported role combinations.
    // Note that the policy is designed to prefer setting the power and data
    // role independently rather than changing the mode.
    int supportedRoleCombinations = UsbPort.combineRolesAsBit(currentPowerRole, currentDataRole);
    if (currentMode != 0 && currentPowerRole != 0 && currentDataRole != 0) {
      if (canChangePowerRole && canChangeDataRole) {
        // Can change both power and data role independently.
        // Assume all combinations are possible.
        supportedRoleCombinations |=
            COMBO_SOURCE_HOST | COMBO_SOURCE_DEVICE | COMBO_SINK_HOST | COMBO_SINK_DEVICE;
      } else if (canChangePowerRole) {
        // Can only change power role.
        // Assume data role must remain at its current value.
        supportedRoleCombinations |=
            UsbPort.combineRolesAsBit(UsbPort.POWER_ROLE_SOURCE, currentDataRole);
        supportedRoleCombinations |=
            UsbPort.combineRolesAsBit(UsbPort.POWER_ROLE_SINK, currentDataRole);
      } else if (canChangeDataRole) {
        // Can only change data role.
        // Assume power role must remain at its current value.
        supportedRoleCombinations |=
            UsbPort.combineRolesAsBit(currentPowerRole, UsbPort.DATA_ROLE_HOST);
        supportedRoleCombinations |=
            UsbPort.combineRolesAsBit(currentPowerRole, UsbPort.DATA_ROLE_DEVICE);
      } else if (canChangeMode) {
        // Can only change the mode.
        // Assume both standard UFP and DFP configurations will become available
        // when this happens.
        supportedRoleCombinations |= COMBO_SOURCE_HOST | COMBO_SINK_DEVICE;
      }
    }

    // Update the port data structures.
    PortInfo portInfo = mPorts.get(portId);
    if (portInfo == null) {
      portInfo = new PortInfo(portId, supportedModes);
      portInfo.setStatus(
          currentMode,
          canChangeMode,
          currentPowerRole,
          canChangePowerRole,
          currentDataRole,
          canChangeDataRole,
          supportedRoleCombinations);
      mPorts.put(portId, portInfo);
    } else {
      // Sanity check that ports aren't changing definition out from under us.
      if (supportedModes != portInfo.mUsbPort.getSupportedModes()) {
        logAndPrint(
            Log.WARN,
            pw,
            "Ignoring inconsistent list of supported modes from "
                + "USB port driver (should be immutable): "
                + "previous="
                + UsbPort.modeToString(portInfo.mUsbPort.getSupportedModes())
                + ", current="
                + UsbPort.modeToString(supportedModes));
      }

      if (portInfo.setStatus(
          currentMode,
          canChangeMode,
          currentPowerRole,
          canChangePowerRole,
          currentDataRole,
          canChangeDataRole,
          supportedRoleCombinations)) {
        portInfo.mDisposition = PortInfo.DISPOSITION_CHANGED;
      } else {
        portInfo.mDisposition = PortInfo.DISPOSITION_READY;
      }
    }
  }
Ejemplo n.º 23
0
  private void handleReadPrintJobsLocked() {
    // Make a map with the files for a print job since we may have
    // to delete some. One example of getting orphan files if the
    // spooler crashes while constructing a print job. We do not
    // persist partially populated print jobs under construction to
    // avoid special handling for various attributes missing.
    ArrayMap<PrintJobId, File> fileForJobMap = null;
    File[] files = getFilesDir().listFiles();
    if (files != null) {
      final int fileCount = files.length;
      for (int i = 0; i < fileCount; i++) {
        File file = files[i];
        if (file.isFile() && file.getName().startsWith(PRINT_JOB_FILE_PREFIX)) {
          if (fileForJobMap == null) {
            fileForJobMap = new ArrayMap<PrintJobId, File>();
          }
          String printJobIdString =
              file.getName().substring(PRINT_JOB_FILE_PREFIX.length(), file.getName().indexOf('.'));
          PrintJobId printJobId = PrintJobId.unflattenFromString(printJobIdString);
          fileForJobMap.put(printJobId, file);
        }
      }
    }

    final int printJobCount = mPrintJobs.size();
    for (int i = 0; i < printJobCount; i++) {
      PrintJobInfo printJob = mPrintJobs.get(i);

      // We want to have only the orphan files at the end.
      if (fileForJobMap != null) {
        fileForJobMap.remove(printJob.getId());
      }

      switch (printJob.getState()) {
        case PrintJobInfo.STATE_QUEUED:
        case PrintJobInfo.STATE_STARTED:
        case PrintJobInfo.STATE_BLOCKED:
          {
            // We have a print job that was queued or started or blocked in
            // the past but the device battery died or a crash occurred. In
            // this case we assume the print job failed and let the user
            // decide whether to restart the job or just cancel it.
            setPrintJobState(
                printJob.getId(),
                PrintJobInfo.STATE_FAILED,
                getString(R.string.no_connection_to_printer));
          }
          break;
      }
    }

    if (!mPrintJobs.isEmpty()) {
      // Update the notification.
      mNotificationController.onUpdateNotifications(mPrintJobs);
    }

    // Delete the orphan files.
    if (fileForJobMap != null) {
      final int orphanFileCount = fileForJobMap.size();
      for (int i = 0; i < orphanFileCount; i++) {
        File file = fileForJobMap.valueAt(i);
        file.delete();
      }
    }
  }