androidx.annotation.WorkerThread Java Examples

The following examples show how to use androidx.annotation.WorkerThread. 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: PinState.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Invoked whenever a Signal PIN user disables registration lock.
 */
@WorkerThread
public static synchronized void onDisableRegistrationLockForUserWithPin() throws IOException {
  Log.i(TAG, "onDisableRegistrationLockForUserWithPin()");

  if (getState() == State.PIN_WITH_REGISTRATION_LOCK_DISABLED) {
    Log.i(TAG, "Registration lock already disabled. Skipping.");
    return;
  }

  assertState(State.PIN_WITH_REGISTRATION_LOCK_ENABLED);

  SignalStore.kbsValues().setV2RegistrationLockEnabled(true);
  ApplicationDependencies.getKeyBackupService()
                         .newPinChangeSession(SignalStore.kbsValues().getRegistrationLockTokenResponse())
                         .disableRegistrationLock();
  SignalStore.kbsValues().setV2RegistrationLockEnabled(false);

  updateState(State.PIN_WITH_REGISTRATION_LOCK_DISABLED);
}
 
Example #2
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private PushProcessMessageJob(@NonNull MessageState messageState,
                              @Nullable SignalServiceContent content,
                              @Nullable ExceptionMetadata exceptionMetadata,
                              long pushMessageId,
                              long smsMessageId,
                              long timestamp)
{
  this(createParameters(content, exceptionMetadata),
       messageState,
       content,
       exceptionMetadata,
       pushMessageId,
       smsMessageId,
       timestamp);
}
 
Example #3
Source File: BlobProvider.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private synchronized @NonNull Uri writeBlobSpecToDisk(@NonNull Context context, @NonNull BlobSpec blobSpec)
    throws IOException
{
  CountDownLatch               latch     = new CountDownLatch(1);
  AtomicReference<IOException> exception = new AtomicReference<>(null);
  Uri                          uri       = writeBlobSpecToDiskAsync(context, blobSpec, latch::countDown, exception::set);

  try {
    latch.await();
  } catch (InterruptedException e) {
    throw new IOException(e);
  }

  if (exception.get() != null) {
    throw exception.get();
  }

  return uri;
}
 
Example #4
Source File: PinState.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Called when registration lock is enabled in the settings using the old UI (i.e. no mention of
 * Signal PINs).
 */
@WorkerThread
public static synchronized void onEnableLegacyRegistrationLockPreference(@NonNull Context context, @NonNull String pin)
    throws IOException, UnauthenticatedResponseException
{
  Log.i(TAG, "onCompleteRegistrationLockV1Reminder()");
  assertState(State.NO_REGISTRATION_LOCK);

  KbsValues                         kbsValues        = SignalStore.kbsValues();
  MasterKey                         masterKey        = kbsValues.getOrCreateMasterKey();
  KeyBackupService                  keyBackupService = ApplicationDependencies.getKeyBackupService();
  KeyBackupService.PinChangeSession pinChangeSession = keyBackupService.newPinChangeSession();
  HashedPin                         hashedPin        = PinHashing.hashPin(pin, pinChangeSession);
  KbsPinData                        kbsData          = pinChangeSession.setPin(hashedPin, masterKey);

  pinChangeSession.enableRegistrationLock(masterKey);

  kbsValues.setKbsMasterKey(kbsData, pin);
  kbsValues.setV2RegistrationLockEnabled(true);
  TextSecurePreferences.clearRegistrationLockV1(context);
  TextSecurePreferences.setRegistrationLockLastReminderTime(context, System.currentTimeMillis());
  TextSecurePreferences.setRegistrationLockNextReminderInterval(context, RegistrationLockReminders.INITIAL_INTERVAL);

  updateState(buildInferredStateFromOtherFields());
}
 
Example #5
Source File: Camera1.java    From Lassi-Android with MIT License 6 votes vote down vote up
@WorkerThread
private void unbindFromSurface() {
    mIsBound = false;
    mPreviewStreamSize = null;
    mCaptureSize = null;
    try {
        if (mPreview.getOutputClass() == SurfaceHolder.class) {
            mCamera.setPreviewDisplay(null);
        } else if (mPreview.getOutputClass() == SurfaceTexture.class) {
            mCamera.setPreviewTexture(null);
        } else {
            throw new RuntimeException("Unknown CameraPreview output class.");
        }
    } catch (IOException e) {
        LOG.e("unbindFromSurface", "Could not release surface", e);
    }
}
 
Example #6
Source File: ContactRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public Cursor querySignalContacts(@NonNull String query, boolean includeSelf) {
  Cursor cursor =  TextUtils.isEmpty(query) ? recipientDatabase.getSignalContacts(includeSelf)
                                            : recipientDatabase.querySignalContacts(query, includeSelf);

  if (includeSelf && noteToSelfTitle.toLowerCase().contains(query.toLowerCase())) {
    Recipient self        = Recipient.self();
    boolean   nameMatch   = self.getDisplayName(context).toLowerCase().contains(query.toLowerCase());
    boolean   numberMatch = self.getE164().isPresent() && self.requireE164().contains(query);
    boolean   shouldAdd   = !nameMatch && !numberMatch;

    if (shouldAdd) {
      MatrixCursor selfCursor = new MatrixCursor(RecipientDatabase.SEARCH_PROJECTION_NAMES);
      selfCursor.addRow(new Object[]{ self.getId().serialize(), noteToSelfTitle, null, self.getE164().or(""), self.getEmail().orNull(), null, -1, RecipientDatabase.RegisteredState.REGISTERED.getId(), noteToSelfTitle });

      cursor = cursor == null ? selfCursor : new MergeCursor(new Cursor[]{ cursor, selfCursor });
    }
  }

  return new SearchCursorWrapper(cursor, SEARCH_CURSOR_MAPPERS);
}
 
Example #7
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private @Nullable Job getNextEligibleJobForExecution() {
  List<JobSpec> jobSpecs = jobStorage.getPendingJobsWithNoDependenciesInCreatedOrder(System.currentTimeMillis());

  for (JobSpec jobSpec : jobSpecs) {
    List<ConstraintSpec> constraintSpecs = jobStorage.getConstraintSpecs(jobSpec.getId());
    List<Constraint>     constraints     = Stream.of(constraintSpecs)
                                                 .map(ConstraintSpec::getFactoryKey)
                                                 .map(constraintInstantiator::instantiate)
                                                 .toList();

    if (Stream.of(constraints).allMatch(Constraint::isMet)) {
      return createJob(jobSpec, constraintSpecs);
    }
  }

  return null;
}
 
Example #8
Source File: AttachmentUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public static boolean isAutoDownloadPermitted(@NonNull Context context, @Nullable DatabaseAttachment attachment) {
  if (attachment == null) {
    Log.w(TAG, "attachment was null, returning vacuous true");
    return true;
  }

  if (isFromUnknownContact(context, attachment)) {
    return false;
  }

  Set<String> allowedTypes = getAllowedAutoDownloadTypes(context);
  String      contentType  = attachment.getContentType();

  if (attachment.isVoiceNote()                                                       ||
      (MediaUtil.isAudio(attachment) && TextUtils.isEmpty(attachment.getFileName())) ||
      MediaUtil.isLongTextType(attachment.getContentType())                          ||
      attachment.isSticker())
  {
    return true;
  } else if (isNonDocumentType(contentType)) {
    return allowedTypes.contains(MediaUtil.getDiscreteMimeType(contentType));
  } else {
    return allowedTypes.contains("documents");
  }
}
 
Example #9
Source File: BitmapUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public static Bitmap createScaledBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
  if (bitmap.getWidth() <= maxWidth && bitmap.getHeight() <= maxHeight) {
    return bitmap;
  }

  if (maxWidth <= 0 || maxHeight <= 0) {
    return bitmap;
  }

  int newWidth  = maxWidth;
  int newHeight = maxHeight;

  float widthRatio  = bitmap.getWidth()  / (float) maxWidth;
  float heightRatio = bitmap.getHeight() / (float) maxHeight;

  if (widthRatio > heightRatio) {
    newHeight = (int) (bitmap.getHeight() / widthRatio);
  } else {
    newWidth = (int) (bitmap.getWidth() / heightRatio);
  }

  return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
 
Example #10
Source File: CacheFileMetadataIndex.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes index data for the specified cache.
 *
 * <p>This method may be slow and shouldn't normally be called on the main thread.
 *
 * @param databaseProvider Provides the database in which the index is stored.
 * @param uid The cache UID.
 * @throws DatabaseIOException If an error occurs deleting the index data.
 */
@WorkerThread
public static void delete(DatabaseProvider databaseProvider, long uid)
    throws DatabaseIOException {
  String hexUid = Long.toHexString(uid);
  try {
    String tableName = getTableName(hexUid);
    SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
    writableDatabase.beginTransactionNonExclusive();
    try {
      VersionTable.removeVersion(
          writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
      dropTable(writableDatabase, tableName);
      writableDatabase.setTransactionSuccessful();
    } finally {
      writableDatabase.endTransaction();
    }
  } catch (SQLException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example #11
Source File: MediaRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private static LinkedHashMap<Media, Media> transformMedia(@NonNull Context context,
                                                          @NonNull List<Media> currentMedia,
                                                          @NonNull Map<Media, MediaTransform> modelsToTransform)
{
  LinkedHashMap<Media, Media> updatedMedia = new LinkedHashMap<>(currentMedia.size());

  for (Media media : currentMedia) {
    MediaTransform transformer = modelsToTransform.get(media);
    if (transformer != null) {
      updatedMedia.put(media, transformer.transform(context, media));
    } else {
      updatedMedia.put(media, media);
    }
  }
  return updatedMedia;
}
 
Example #12
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves the next job that is eligible for execution. To be 'eligible' means that the job:
 *  - Has no dependencies
 *  - Has no unmet constraints
 *
 * This method will block until a job is available.
 * When the job returned from this method has been run, you must call {@link #onJobFinished(Job)}.
 */
@WorkerThread
synchronized @NonNull Job pullNextEligibleJobForExecution() {
  try {
    Job job;

    while ((job = getNextEligibleJobForExecution()) == null) {
      if (runningJobs.isEmpty()) {
        debouncer.publish(callback::onEmpty);
      }

      wait();
    }

    jobStorage.updateJobRunningState(job.getId(), true);
    runningJobs.put(job.getId(), job);
    jobTracker.onStateChange(job, JobTracker.JobState.RUNNING);

    return job;
  } catch (InterruptedException e) {
    Log.e(TAG, "Interrupted.");
    throw new AssertionError(e);
  }
}
 
Example #13
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
synchronized void onRetry(@NonNull Job job) {
  int    nextRunAttempt     = job.getRunAttempt() + 1;
  long   nextRunAttemptTime = calculateNextRunAttemptTime(System.currentTimeMillis(), nextRunAttempt, job.getParameters().getMaxBackoff());
  String serializedData     = dataSerializer.serialize(job.serialize());

  jobStorage.updateJobAfterRetry(job.getId(), false, nextRunAttempt, nextRunAttemptTime, serializedData);
  jobTracker.onStateChange(job, JobTracker.JobState.PENDING);

  List<Constraint> constraints = Stream.of(jobStorage.getConstraintSpecs(job.getId()))
                                       .map(ConstraintSpec::getFactoryKey)
                                       .map(constraintInstantiator::instantiate)
                                       .toList();


  long delay = Math.max(0, nextRunAttemptTime - System.currentTimeMillis());

  Log.i(TAG, JobLogger.format(job, "Scheduling a retry in " + delay + " ms."));
  scheduler.schedule(delay, constraints);

  notifyAll();
}
 
Example #14
Source File: PushMediaSendJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public static void enqueue(@NonNull Context context, @NonNull JobManager jobManager, long messageId, @NonNull Recipient recipient) {
  try {
    if (!recipient.hasServiceIdentifier()) {
      throw new AssertionError();
    }

    MmsDatabase          database            = DatabaseFactory.getMmsDatabase(context);
    OutgoingMediaMessage message             = database.getOutgoingMessage(messageId);
    Set<String>          attachmentUploadIds = enqueueCompressingAndUploadAttachmentsChains(jobManager, message);

    jobManager.add(new PushMediaSendJob(messageId, recipient), attachmentUploadIds, recipient.getId().toQueueKey());

  } catch (NoSuchMessageException | MmsException e) {
    Log.w(TAG, "Failed to enqueue message.", e);
    DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
    notifyMediaMessageDeliveryFailed(context, messageId);
  }
}
 
Example #15
Source File: FcmUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves the current FCM token. If one isn't available, it'll be generated.
 */
@WorkerThread
public static Optional<String> getToken() {
  CountDownLatch          latch = new CountDownLatch(1);
  AtomicReference<String> token = new AtomicReference<>(null);

  FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(task -> {
    if (task.isSuccessful() && task.getResult() != null && !TextUtils.isEmpty(task.getResult().getToken())) {
      token.set(task.getResult().getToken());
    } else {
      Log.w(TAG, "Failed to get the token.", task.getException());
    }

    latch.countDown();
  });

  try {
    latch.await();
  } catch (InterruptedException e) {
    Log.w(TAG, "Was interrupted while waiting for the token.");
  }

  return Optional.fromNullable(token.get());
}
 
Example #16
Source File: Camera1.java    From Lassi-Android with MIT License 6 votes vote down vote up
@WorkerThread
@Override
void onStart() {
    if (isCameraAvailable()) {
        LOG.w("onStart:", "Camera not available. Should not happen.");
        onStop(); // Should not happen.
    }
    if (collectCameraId()) {
        createCamera();
        if (shouldBindToSurface()) bindToSurface();
        if (shouldStartPreview()) startPreview("onStart");
        LOG.i("onStart:", "Ended");
    } else {
        LOG.e("onStart:", "No camera available for facing", mFacing);
        throw new CameraException(CameraException.REASON_NO_CAMERA);
    }
}
 
Example #17
Source File: PinState.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Should only be called by {@link org.thoughtcrime.securesms.migrations.RegistrationPinV2MigrationJob}.
 */
@WorkerThread
public static synchronized void onMigrateToRegistrationLockV2(@NonNull Context context, @NonNull String pin)
    throws IOException, UnauthenticatedResponseException
{
  KbsValues                         kbsValues        = SignalStore.kbsValues();
  MasterKey                         masterKey        = kbsValues.getOrCreateMasterKey();
  KeyBackupService                  keyBackupService = ApplicationDependencies.getKeyBackupService();
  KeyBackupService.PinChangeSession pinChangeSession = keyBackupService.newPinChangeSession();
  HashedPin                         hashedPin        = PinHashing.hashPin(pin, pinChangeSession);
  KbsPinData                        kbsData          = pinChangeSession.setPin(hashedPin, masterKey);

  pinChangeSession.enableRegistrationLock(masterKey);

  kbsValues.setKbsMasterKey(kbsData, pin);
  TextSecurePreferences.clearRegistrationLockV1(context);

  updateState(buildInferredStateFromOtherFields());
}
 
Example #18
Source File: GroupManagerV2.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
@NonNull GroupManager.GroupActionResult updateGroupTitleAndAvatar(@Nullable String title, @Nullable byte[] avatarBytes, boolean avatarChanged)
  throws GroupChangeFailedException, GroupInsufficientRightsException, IOException, GroupNotAMemberException
{
  try {
    GroupChange.Actions.Builder change = groupOperations.createModifyGroupTitleAndMembershipChange(Optional.fromNullable(title), Collections.emptySet(), Collections.emptySet());

    if (avatarChanged) {
      String cdnKey = avatarBytes != null ? groupsV2Api.uploadAvatar(avatarBytes, groupSecretParams, authorization.getAuthorizationForToday(selfUuid, groupSecretParams))
                                          : "";
      change.setModifyAvatar(GroupChange.Actions.ModifyAvatarAction.newBuilder()
                                                .setAvatar(cdnKey));
    }

    GroupManager.GroupActionResult groupActionResult = commitChangeWithConflictResolution(change);

    if (avatarChanged) {
      AvatarHelper.setAvatar(context, Recipient.externalGroup(context, groupId).getId(), avatarBytes != null ? new ByteArrayInputStream(avatarBytes) : null);
      groupDatabase.onAvatarUpdated(groupId, avatarBytes != null);
    }

    return groupActionResult;
  } catch (VerificationFailedException e) {
    throw new GroupChangeFailedException(e);
  }
}
 
Example #19
Source File: PushChallengeRequest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private Optional<String> requestAndReceiveChallengeBlocking() {
  EventBus eventBus = EventBus.getDefault();

  eventBus.register(this);
  try {
    accountManager.requestPushChallenge(fcmToken, e164number);

    latch.await(timeoutMs, TimeUnit.MILLISECONDS);

    return Optional.fromNullable(challenge.get());
  } catch (InterruptedException | IOException e) {
    Log.w(TAG, "Error getting push challenge", e);
    return Optional.absent();
  } finally {
    eventBus.unregister(this);
  }
}
 
Example #20
Source File: AttachmentUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes the specified attachment. If its the only attachment for its linked message, the entire
 * message is deleted.
 */
@WorkerThread
public static void deleteAttachment(@NonNull Context context,
                                    @NonNull DatabaseAttachment attachment)
{
  AttachmentId attachmentId    = attachment.getAttachmentId();
  long         mmsId           = attachment.getMmsId();
  int          attachmentCount = DatabaseFactory.getAttachmentDatabase(context)
      .getAttachmentsForMessage(mmsId)
      .size();

  if (attachmentCount <= 1) {
    DatabaseFactory.getMmsDatabase(context).delete(mmsId);
  } else {
    DatabaseFactory.getAttachmentDatabase(context).deleteAttachment(attachmentId);
  }
}
 
Example #21
Source File: RemoteDeleteSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static @NonNull RemoteDeleteSendJob create(@NonNull Context context,
                                                  long messageId,
                                                  boolean isMms)
    throws NoSuchMessageException
{
  MessageRecord message = isMms ? DatabaseFactory.getMmsDatabase(context).getMessageRecord(messageId)
                                : DatabaseFactory.getSmsDatabase(context).getMessage(messageId);

  Recipient conversationRecipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(message.getThreadId());

  if (conversationRecipient == null) {
    throw new AssertionError("We have a message, but couldn't find the thread!");
  }

  List<RecipientId> recipients = conversationRecipient.isGroup() ? Stream.of(conversationRecipient.getParticipants()).map(Recipient::getId).toList()
                                                                 : Stream.of(conversationRecipient.getId()).toList();

  recipients.remove(Recipient.self().getId());

  return new RemoteDeleteSendJob(messageId,
                             isMms,
                             recipients,
                             recipients.size(),
                             new Parameters.Builder()
                                           .setQueue(conversationRecipient.getId().toQueueKey())
                                           .setLifespan(TimeUnit.DAYS.toMillis(1))
                                           .setMaxAttempts(Parameters.UNLIMITED)
                                           .build());
}
 
Example #22
Source File: BitmapUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static <T> Bitmap createScaledBitmap(Context context, T model, int maxWidth, int maxHeight)
    throws BitmapDecodingException
{
  try {
    return GlideApp.with(context.getApplicationContext())
                   .asBitmap()
                   .load(model)
                   .centerInside()
                   .submit(maxWidth, maxHeight)
                   .get();
  } catch (InterruptedException | ExecutionException e) {
    throw new BitmapDecodingException(e);
  }
}
 
Example #23
Source File: GroupManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static void acceptInvite(@NonNull Context context, @NonNull GroupId.V2 groupId)
    throws GroupChangeBusyException, GroupChangeFailedException, GroupNotAMemberException, GroupInsufficientRightsException, IOException
{
  try (GroupManagerV2.GroupEditor editor = new GroupManagerV2(context).edit(groupId.requireV2())) {
    editor.acceptInvite();
    DatabaseFactory.getGroupDatabase(context)
                   .setActive(groupId, true);
  }
}
 
Example #24
Source File: GroupManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static void updateGroupFromServer(@NonNull Context context,
                                         @NonNull GroupMasterKey groupMasterKey,
                                         int revision,
                                         long timestamp,
                                         @Nullable byte[] signedGroupChange)
    throws GroupChangeBusyException, IOException, GroupNotAMemberException
{
  try (GroupManagerV2.GroupUpdater updater = new GroupManagerV2(context).updater(groupMasterKey)) {
    updater.updateLocalToServerRevision(revision, timestamp, signedGroupChange);
  }
}
 
Example #25
Source File: GroupManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static void ejectFromGroup(@NonNull Context context, @NonNull GroupId.V2 groupId, @NonNull Recipient recipient)
    throws GroupChangeBusyException, GroupChangeFailedException, GroupInsufficientRightsException, GroupNotAMemberException, IOException
{
  try (GroupManagerV2.GroupEditor edit = new GroupManagerV2(context).edit(groupId.requireV2())) {
    edit.ejectMember(recipient.getId());
    Log.i(TAG, "Member removed from group " + groupId);
  }
}
 
Example #26
Source File: FitbitGatt.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Convenience method that attempts to start all the components
 *
 * @param context
 */
@WorkerThread
public synchronized void start(Context context) {
    startGattClient(context);
    startGattServer(context);
    initializeScanner(context);
}
 
Example #27
Source File: Camera1.java    From Lassi-Android with MIT License 5 votes vote down vote up
@NonNull
@WorkerThread
private static List<Camera.Area> computeMeteringAreas(double viewClickX, double viewClickY,
                                                      int viewWidth, int viewHeight,
                                                      int sensorToDisplay) {
    // Event came in view coordinates. We must rotate to sensor coordinates.
    // First, rescale to the -1000 ... 1000 range.
    int displayToSensor = -sensorToDisplay;
    viewClickX = -1000d + (viewClickX / (double) viewWidth) * 2000d;
    viewClickY = -1000d + (viewClickY / (double) viewHeight) * 2000d;

    // Apply rotation to this point.
    // https://academo.org/demos/rotation-about-point/
    double theta = ((double) displayToSensor) * Math.PI / 180;
    double sensorClickX = viewClickX * Math.cos(theta) - viewClickY * Math.sin(theta);
    double sensorClickY = viewClickX * Math.sin(theta) + viewClickY * Math.cos(theta);
    LOG.i("focus:", "viewClickX:", viewClickX, "viewClickY:", viewClickY);
    LOG.i("focus:", "sensorClickX:", sensorClickX, "sensorClickY:", sensorClickY);

    // Compute the rect bounds.
    Rect rect1 = computeMeteringArea(sensorClickX, sensorClickY, 150d);
    int weight1 = 1000; // 150 * 150 * 1000 = more than 10.000.000
    Rect rect2 = computeMeteringArea(sensorClickX, sensorClickY, 300d);
    int weight2 = 100; // 300 * 300 * 100 = 9.000.000

    List<Camera.Area> list = new ArrayList<>(2);
    list.add(new Camera.Area(rect1, weight1));
    list.add(new Camera.Area(rect2, weight2));
    return list;
}
 
Example #28
Source File: ComputableLiveData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@Override
public void run() {
    boolean computed;
    do {
        computed = false;
        // compute can happen only in 1 thread but no reason to lock others.
        if (mComputing.compareAndSet(false, true)) {
            // as long as it is invalid, keep computing.
            try {
                T value = null;
                while (mInvalid.compareAndSet(true, false)) {
                    computed = true;
                    value = compute();
                }
                if (computed) {
                    mLiveData.postValue(value);
                }
            } finally {
                // release compute lock
                mComputing.set(false);
            }
        }
        // check invalid after releasing compute lock to avoid the following scenario.
        // Thread A runs compute()
        // Thread A checks invalid, it is false
        // Main thread sets invalid to true
        // Thread B runs, fails to acquire compute lock and skips
        // Thread A releases compute lock
        // We've left invalid in set state. The check below recovers.
    } while (computed && mInvalid.get());
}
 
Example #29
Source File: CameraUtils.java    From Lassi-Android with MIT License 5 votes vote down vote up
/**
 * Simply writes the given data to the given file. It is done synchronously. If you are
 * running on the UI thread, please use {@link #writeToFile(byte[], File, FileCallback)}
 * and pass a file callback.
 * <p>
 * If any error is encountered, this returns null.
 *
 * @param data the data to be written
 * @param file the file to write into
 * @return the source file, or null if error
 */
@SuppressWarnings("WeakerAccess")
@Nullable
@WorkerThread
public static File writeToFile(@NonNull final byte[] data, @NonNull File file) {
    if (file.exists() && !file.delete()) return null;
    try (OutputStream stream = new BufferedOutputStream(new FileOutputStream(file))) {
        stream.write(data);
        stream.flush();
        return file;
    } catch (IOException e) {
        return null;
    }
}
 
Example #30
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves a string representing the state of the job queue. Intended for debugging.
 */
@WorkerThread
synchronized @NonNull String getDebugInfo() {
  List<JobSpec>        jobs         = jobStorage.getAllJobSpecs();
  List<ConstraintSpec> constraints  = jobStorage.getAllConstraintSpecs();
  List<DependencySpec> dependencies = jobStorage.getAllDependencySpecs();

  StringBuilder info = new StringBuilder();

  info.append("-- Jobs\n");
  if (!jobs.isEmpty()) {
    Stream.of(jobs).forEach(j -> info.append(j.toString()).append('\n'));
  } else {
    info.append("None\n");
  }

  info.append("\n-- Constraints\n");
  if (!constraints.isEmpty()) {
    Stream.of(constraints).forEach(c -> info.append(c.toString()).append('\n'));
  } else {
    info.append("None\n");
  }

  info.append("\n-- Dependencies\n");
  if (!dependencies.isEmpty()) {
    Stream.of(dependencies).forEach(d -> info.append(d.toString()).append('\n'));
  } else {
    info.append("None\n");
  }

  return info.toString();
}