index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ControllerHelper.java | package com.airbnb.epoxy;
import java.util.List;
/**
* A helper class for {@link EpoxyController} to handle {@link
* com.airbnb.epoxy.AutoModel} models. This is only implemented by the generated classes created the
* annotation processor.
*/
public abstract class ControllerHelper<T extends EpoxyController> {
public abstract void resetAutoModels();
protected void validateModelHashCodesHaveNotChanged(T controller) {
List<EpoxyModel<?>> currentModels = controller.getAdapter().getCopyOfModels();
for (int i = 0; i < currentModels.size(); i++) {
EpoxyModel model = currentModels.get(i);
model.validateStateHasNotChangedSinceAdded(
"Model has changed since it was added to the controller.", i);
}
}
protected void setControllerToStageTo(EpoxyModel<?> model, T controller) {
model.controllerToStageTo = controller;
}
}
| 8,900 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelVisibilityStateChangedListener.java | package com.airbnb.epoxy;
import com.airbnb.epoxy.VisibilityState.Visibility;
/** Used to register an onVisibilityChanged callback with a generated model. */
public interface OnModelVisibilityStateChangedListener<T extends EpoxyModel<V>, V> {
/**
* This will be called once the visibility changed.
* <p>
* @param model The model being bound
* @param view The view that is being bound to the model
* @param visibilityState The new visibility
* <p>
* @see VisibilityState
*/
void onVisibilityStateChanged(T model, V view, @Visibility int visibilityState);
}
| 8,901 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ControllerHelperLookup.java | package com.airbnb.epoxy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;
import androidx.annotation.Nullable;
/**
* Looks up a generated {@link ControllerHelper} implementation for a given adapter.
* If the adapter has no {@link com.airbnb.epoxy.AutoModel} models then a No-Op implementation will
* be returned.
*/
class ControllerHelperLookup {
private static final String GENERATED_HELPER_CLASS_SUFFIX = "_EpoxyHelper";
private static final Map<Class<?>, Constructor<?>> BINDINGS = new LinkedHashMap<>();
private static final NoOpControllerHelper NO_OP_CONTROLLER_HELPER = new NoOpControllerHelper();
static ControllerHelper getHelperForController(EpoxyController controller) {
Constructor<?> constructor = findConstructorForClass(controller.getClass());
if (constructor == null) {
return NO_OP_CONTROLLER_HELPER;
}
try {
return (ControllerHelper) constructor.newInstance(controller);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InstantiationException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException("Unable to get Epoxy helper class.", cause);
}
}
@Nullable
private static Constructor<?> findConstructorForClass(Class<?> controllerClass) {
Constructor<?> helperCtor = BINDINGS.get(controllerClass);
if (helperCtor != null || BINDINGS.containsKey(controllerClass)) {
return helperCtor;
}
String clsName = controllerClass.getName();
if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
return null;
}
try {
Class<?> bindingClass = Class.forName(clsName + GENERATED_HELPER_CLASS_SUFFIX);
//noinspection unchecked
helperCtor = bindingClass.getConstructor(controllerClass);
} catch (ClassNotFoundException e) {
helperCtor = findConstructorForClass(controllerClass.getSuperclass());
} catch (NoSuchMethodException e) {
throw new RuntimeException("Unable to find Epoxy Helper constructor for " + clsName, e);
}
BINDINGS.put(controllerClass, helperCtor);
return helperCtor;
}
}
| 8,902 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/MainThreadExecutor.java | package com.airbnb.epoxy;
import static com.airbnb.epoxy.EpoxyAsyncUtil.AYSNC_MAIN_THREAD_HANDLER;
import static com.airbnb.epoxy.EpoxyAsyncUtil.MAIN_THREAD_HANDLER;
class MainThreadExecutor extends HandlerExecutor {
static final MainThreadExecutor INSTANCE = new MainThreadExecutor(false);
static final MainThreadExecutor ASYNC_INSTANCE = new MainThreadExecutor(true);
MainThreadExecutor(boolean async) {
super(async ? AYSNC_MAIN_THREAD_HANDLER : MAIN_THREAD_HANDLER);
}
}
| 8,903 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelBoundListener.java | package com.airbnb.epoxy;
/** Used to register an onBind callback with a generated model. */
public interface OnModelBoundListener<T extends EpoxyModel<?>, V> {
/**
* This will be called immediately after a model was bound, with the model and view that were
* bound together.
*
* @param model The model being bound
* @param view The view that is being bound to the model
* @param position The adapter position of the model
*/
void onModelBound(T model, V view, int position);
}
| 8,904 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyTouchHelper.java | package com.airbnb.epoxy;
import android.graphics.Canvas;
import android.view.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import static androidx.recyclerview.widget.ItemTouchHelper.Callback.makeMovementFlags;
/**
* A simple way to set up drag or swipe interactions with Epoxy.
* <p>
* Drag events work with the EpoxyController and automatically update the controller and
* RecyclerView when an item is moved. You just need to implement a callback to update your data to
* reflect the change.
* <p>
* Both swipe and drag events implement a small lifecycle to help you style the views as they are
* moved. You can register callbacks for the lifecycle events you care about.
* <p>
* If you want to set up multiple drag and swipe rules for the same RecyclerView, you can use this
* class multiple times to specify different targets or swipe and drag directions and callbacks.
* <p>
* If you want more control over configuration and handling, you can opt to not use this class and
* instead you can implement {@link EpoxyModelTouchCallback} directly with your own {@link
* ItemTouchHelper}. That class provides an interface that makes it easier to work with Epoxy models
* and simplifies touch callbacks.
* <p>
* If you want even more control you can implement {@link EpoxyTouchHelperCallback}. This is just a
* light layer over the normal RecyclerView touch callbacks, but it converts all view holders to
* Epoxy view holders to remove some boilerplate for you.
*/
public abstract class EpoxyTouchHelper {
/**
* The entry point for setting up drag support.
*
* @param controller The EpoxyController with the models that will be dragged. The controller will
* be updated for you when a model is dragged and moved by a user's touch
* interaction.
*/
public static DragBuilder initDragging(EpoxyController controller) {
return new DragBuilder(controller);
}
public static class DragBuilder {
private final EpoxyController controller;
private DragBuilder(EpoxyController controller) {
this.controller = controller;
}
/**
* The recyclerview that the EpoxyController has its adapter added to. An {@link
* androidx.recyclerview.widget.ItemTouchHelper} will be created and configured for you, and
* attached to this RecyclerView.
*/
public DragBuilder2 withRecyclerView(RecyclerView recyclerView) {
return new DragBuilder2(controller, recyclerView);
}
}
public static class DragBuilder2 {
private final EpoxyController controller;
private final RecyclerView recyclerView;
private DragBuilder2(EpoxyController controller, RecyclerView recyclerView) {
this.controller = controller;
this.recyclerView = recyclerView;
}
/** Enable dragging vertically, up and down. */
public DragBuilder3 forVerticalList() {
return withDirections(ItemTouchHelper.UP | ItemTouchHelper.DOWN);
}
/** Enable dragging horizontally, left and right. */
public DragBuilder3 forHorizontalList() {
return withDirections(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
}
/** Enable dragging in all directions. */
public DragBuilder3 forGrid() {
return withDirections(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT
| ItemTouchHelper.RIGHT);
}
/**
* Set custom movement flags to dictate which drag directions should be allowed.
* <p>
* Can be any of {@link ItemTouchHelper#LEFT}, {@link ItemTouchHelper#RIGHT}, {@link
* ItemTouchHelper#UP}, {@link ItemTouchHelper#DOWN}, {@link ItemTouchHelper#START}, {@link
* ItemTouchHelper#END}
* <p>
* Flags can be OR'd together to allow multiple directions.
*/
public DragBuilder3 withDirections(int directionFlags) {
return new DragBuilder3(controller, recyclerView, makeMovementFlags(directionFlags, 0));
}
}
public static class DragBuilder3 {
private final EpoxyController controller;
private final RecyclerView recyclerView;
private final int movementFlags;
private DragBuilder3(EpoxyController controller, RecyclerView recyclerView, int movementFlags) {
this.controller = controller;
this.recyclerView = recyclerView;
this.movementFlags = movementFlags;
}
/**
* Set the type of Epoxy model that is draggable. This approach works well if you only have one
* draggable type.
*/
public <U extends EpoxyModel> DragBuilder4<U> withTarget(Class<U> targetModelClass) {
List<Class<? extends EpoxyModel>> targetClasses = new ArrayList<>(1);
targetClasses.add(targetModelClass);
return new DragBuilder4<>(controller, recyclerView, movementFlags, targetModelClass,
targetClasses);
}
/**
* Specify which Epoxy model types are draggable. Use this if you have more than one type that
* is draggable.
* <p>
* If you only have one draggable type you should use {@link #withTarget(Class)}
*/
public DragBuilder4<EpoxyModel> withTargets(Class<? extends EpoxyModel>... targetModelClasses) {
return new DragBuilder4<>(controller, recyclerView, movementFlags, EpoxyModel.class,
Arrays.asList(targetModelClasses));
}
/**
* Use this if all models in the controller should be draggable, and if there are multiple types
* of models in the controller.
* <p>
* If you only have one model type you should use {@link #withTarget(Class)}
*/
public DragBuilder4<EpoxyModel> forAllModels() {
return withTarget(EpoxyModel.class);
}
}
public static class DragBuilder4<U extends EpoxyModel> {
private final EpoxyController controller;
private final RecyclerView recyclerView;
private final int movementFlags;
private final Class<U> targetModelClass;
private final List<Class<? extends EpoxyModel>> targetModelClasses;
private DragBuilder4(EpoxyController controller,
RecyclerView recyclerView, int movementFlags,
Class<U> targetModelClass, List<Class<? extends EpoxyModel>> targetModelClasses) {
this.controller = controller;
this.recyclerView = recyclerView;
this.movementFlags = movementFlags;
this.targetModelClass = targetModelClass;
this.targetModelClasses = targetModelClasses;
}
/**
* Set callbacks to handle drag actions and lifecycle events.
* <p>
* You MUST implement {@link DragCallbacks#onModelMoved(int, int, EpoxyModel,
* View)} to update your data to reflect an item move.
* <p>
* You can optionally implement the other callbacks to modify the view being dragged. This is
* useful if you want to change things like the view background, size, color, etc
*
* @return An {@link ItemTouchHelper} instance that has been initialized and attached to a
* recyclerview. The touch helper has already been fully set up and can be ignored, but you may
* want to hold a reference to it if you need to later detach the recyclerview to disable touch
* events via setting null on {@link ItemTouchHelper#attachToRecyclerView(RecyclerView)}
*/
public ItemTouchHelper andCallbacks(final DragCallbacks<U> callbacks) {
ItemTouchHelper itemTouchHelper =
new ItemTouchHelper(new EpoxyModelTouchCallback<U>(controller, targetModelClass) {
@Override
public int getMovementFlagsForModel(U model, int adapterPosition) {
return movementFlags;
}
@Override
protected boolean isTouchableModel(EpoxyModel<?> model) {
boolean isTargetType = targetModelClasses.size() == 1
? super.isTouchableModel(model)
: targetModelClasses.contains(model.getClass());
//noinspection unchecked
return isTargetType && callbacks.isDragEnabledForModel((U) model);
}
@Override
public void onDragStarted(U model, View itemView, int adapterPosition) {
callbacks.onDragStarted(model, itemView, adapterPosition);
}
@Override
public void onDragReleased(U model, View itemView) {
callbacks.onDragReleased(model, itemView);
}
@Override
public void onModelMoved(int fromPosition, int toPosition, U modelBeingMoved,
View itemView) {
callbacks.onModelMoved(fromPosition, toPosition, modelBeingMoved, itemView);
}
@Override
public void clearView(U model, View itemView) {
callbacks.clearView(model, itemView);
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
return itemTouchHelper;
}
}
public abstract static class DragCallbacks<T extends EpoxyModel>
implements EpoxyDragCallback<T> {
@Override
public void onDragStarted(T model, View itemView, int adapterPosition) {
}
@Override
public void onDragReleased(T model, View itemView) {
}
@Override
public abstract void onModelMoved(int fromPosition, int toPosition, T modelBeingMoved,
View itemView);
@Override
public void clearView(T model, View itemView) {
}
/**
* Whether the given model should be draggable.
* <p>
* True by default. You may override this to toggle draggability for a model.
*/
public boolean isDragEnabledForModel(T model) {
return true;
}
@Override
public final int getMovementFlagsForModel(T model, int adapterPosition) {
// No-Op this is not used
return 0;
}
}
/**
* The entry point for setting up swipe support for a RecyclerView. The RecyclerView must be set
* with an Epoxy adapter or controller.
*/
public static SwipeBuilder initSwiping(RecyclerView recyclerView) {
return new SwipeBuilder(recyclerView);
}
public static class SwipeBuilder {
private final RecyclerView recyclerView;
private SwipeBuilder(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
/** Enable swiping right. */
public SwipeBuilder2 right() {
return withDirections(ItemTouchHelper.RIGHT);
}
/** Enable swiping left. */
public SwipeBuilder2 left() {
return withDirections(ItemTouchHelper.LEFT);
}
/** Enable swiping horizontally, left and right. */
public SwipeBuilder2 leftAndRight() {
return withDirections(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
}
/**
* Set custom movement flags to dictate which swipe directions should be allowed.
* <p>
* Can be any of {@link ItemTouchHelper#LEFT}, {@link ItemTouchHelper#RIGHT}, {@link
* ItemTouchHelper#UP}, {@link ItemTouchHelper#DOWN}, {@link ItemTouchHelper#START}, {@link
* ItemTouchHelper#END}
* <p>
* Flags can be OR'd together to allow multiple directions.
*/
public SwipeBuilder2 withDirections(int directionFlags) {
return new SwipeBuilder2(recyclerView, makeMovementFlags(0, directionFlags));
}
}
public static class SwipeBuilder2 {
private final RecyclerView recyclerView;
private final int movementFlags;
private SwipeBuilder2(RecyclerView recyclerView,
int movementFlags) {
this.recyclerView = recyclerView;
this.movementFlags = movementFlags;
}
/**
* Set the type of Epoxy model that is swipable. Use this if you only have one
* swipable type.
*/
public <U extends EpoxyModel> SwipeBuilder3<U> withTarget(Class<U> targetModelClass) {
List<Class<? extends EpoxyModel>> targetClasses = new ArrayList<>(1);
targetClasses.add(targetModelClass);
return new SwipeBuilder3<>(recyclerView, movementFlags, targetModelClass,
targetClasses);
}
/**
* Specify which Epoxy model types are swipable. Use this if you have more than one type that
* is swipable.
* <p>
* If you only have one swipable type you should use {@link #withTarget(Class)}
*/
public SwipeBuilder3<EpoxyModel> withTargets(
Class<? extends EpoxyModel>... targetModelClasses) {
return new SwipeBuilder3<>(recyclerView, movementFlags, EpoxyModel.class,
Arrays.asList(targetModelClasses));
}
/**
* Use this if all models in the controller should be swipable, and if there are multiple types
* of models in the controller.
* <p>
* If you only have one model type you should use {@link #withTarget(Class)}
*/
public SwipeBuilder3<EpoxyModel> forAllModels() {
return withTarget(EpoxyModel.class);
}
}
public static class SwipeBuilder3<U extends EpoxyModel> {
private final RecyclerView recyclerView;
private final int movementFlags;
private final Class<U> targetModelClass;
private final List<Class<? extends EpoxyModel>> targetModelClasses;
private SwipeBuilder3(
RecyclerView recyclerView, int movementFlags,
Class<U> targetModelClass, List<Class<? extends EpoxyModel>> targetModelClasses) {
this.recyclerView = recyclerView;
this.movementFlags = movementFlags;
this.targetModelClass = targetModelClass;
this.targetModelClasses = targetModelClasses;
}
/**
* Set callbacks to handle swipe actions and lifecycle events.
* <p>
* You MUST implement {@link SwipeCallbacks#onSwipeCompleted(EpoxyModel, View, int, int)} to
* remove the swiped item from your data and request a model build.
* <p>
* You can optionally implement the other callbacks to modify the view as it is being swiped.
*
* @return An {@link ItemTouchHelper} instance that has been initialized and attached to a
* recyclerview. The touch helper has already been fully set up and can be ignored, but you may
* want to hold a reference to it if you need to later detach the recyclerview to disable touch
* events via setting null on {@link ItemTouchHelper#attachToRecyclerView(RecyclerView)}
*/
public ItemTouchHelper andCallbacks(final SwipeCallbacks<U> callbacks) {
ItemTouchHelper itemTouchHelper =
new ItemTouchHelper(new EpoxyModelTouchCallback<U>(null, targetModelClass) {
@Override
public int getMovementFlagsForModel(U model, int adapterPosition) {
return movementFlags;
}
@Override
protected boolean isTouchableModel(EpoxyModel<?> model) {
boolean isTargetType = targetModelClasses.size() == 1
? super.isTouchableModel(model)
: targetModelClasses.contains(model.getClass());
//noinspection unchecked
return isTargetType && callbacks.isSwipeEnabledForModel((U) model);
}
@Override
public void onSwipeStarted(U model, View itemView, int adapterPosition) {
callbacks.onSwipeStarted(model, itemView, adapterPosition);
}
@Override
public void onSwipeProgressChanged(U model, View itemView, float swipeProgress,
Canvas canvas) {
callbacks.onSwipeProgressChanged(model, itemView, swipeProgress, canvas);
}
@Override
public void onSwipeCompleted(U model, View itemView, int position, int direction) {
callbacks.onSwipeCompleted(model, itemView, position, direction);
}
@Override
public void onSwipeReleased(U model, View itemView) {
callbacks.onSwipeReleased(model, itemView);
}
@Override
public void clearView(U model, View itemView) {
callbacks.clearView(model, itemView);
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
return itemTouchHelper;
}
}
public abstract static class SwipeCallbacks<T extends EpoxyModel>
implements EpoxySwipeCallback<T> {
@Override
public void onSwipeStarted(T model, View itemView, int adapterPosition) {
}
@Override
public void onSwipeProgressChanged(T model, View itemView, float swipeProgress,
Canvas canvas) {
}
@Override
public abstract void onSwipeCompleted(T model, View itemView, int position, int direction);
@Override
public void onSwipeReleased(T model, View itemView) {
}
@Override
public void clearView(T model, View itemView) {
}
/**
* Whether the given model should be swipable.
* <p>
* True by default. You may override this to toggle swipabaility for a model.
*/
public boolean isSwipeEnabledForModel(T model) {
return true;
}
@Override
public final int getMovementFlagsForModel(T model, int adapterPosition) {
// Not used
return 0;
}
}
}
| 8,905 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/NoOpControllerHelper.java | package com.airbnb.epoxy;
/**
* A {@link ControllerHelper} implementation for adapters with no {@link
* com.airbnb.epoxy.AutoModel} usage.
*/
class NoOpControllerHelper extends ControllerHelper<EpoxyController> {
@Override
public void resetAutoModels() {
// No - Op
}
}
| 8,906 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ViewHolderState.java |
package com.airbnb.epoxy;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseArray;
import android.view.View;
import com.airbnb.epoxy.ViewHolderState.ViewState;
import com.airbnb.viewmodeladapter.R;
import java.util.Collection;
import androidx.collection.LongSparseArray;
/**
* Helper for {@link EpoxyAdapter} to store the state of Views in the adapter. This is useful for
* saving changes due to user input, such as text input or selection, when a view is scrolled off
* screen or if the adapter needs to be recreated.
* <p/>
* This saved state is separate from the state represented by a {@link EpoxyModel}, which should
* represent the more permanent state of the data shown in the view. This class stores transient
* state that is added to the View after it is bound to a {@link EpoxyModel}. For example, a {@link
* EpoxyModel} may inflate and bind an EditText and then be responsible for styling it and attaching
* listeners. If the user then inputs text, scrolls the view offscreen and then scrolls back, this
* class will preserve the inputted text without the {@link EpoxyModel} needing to be aware of its
* existence.
* <p/>
* This class relies on the adapter having stable ids, as the state of a view is mapped to the id of
* the {@link EpoxyModel}.
*/
@SuppressWarnings("WeakerAccess")
class ViewHolderState extends LongSparseArray<ViewState> implements Parcelable {
ViewHolderState() {
}
private ViewHolderState(int size) {
super(size);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
final int size = size();
dest.writeInt(size);
for (int i = 0; i < size; i++) {
dest.writeLong(keyAt(i));
dest.writeParcelable(valueAt(i), 0);
}
}
public static final Creator<ViewHolderState> CREATOR = new Creator<ViewHolderState>() {
public ViewHolderState[] newArray(int size) {
return new ViewHolderState[size];
}
public ViewHolderState createFromParcel(Parcel source) {
int size = source.readInt();
ViewHolderState state = new ViewHolderState(size);
for (int i = 0; i < size; i++) {
long key = source.readLong();
ViewState value = source.readParcelable(ViewState.class.getClassLoader());
state.put(key, value);
}
return state;
}
};
public boolean hasStateForHolder(EpoxyViewHolder holder) {
return get(holder.getItemId()) != null;
}
public void save(Collection<EpoxyViewHolder> holders) {
for (EpoxyViewHolder holder : holders) {
save(holder);
}
}
/** Save the state of the view bound to the given holder. */
public void save(EpoxyViewHolder holder) {
if (!holder.getModel().shouldSaveViewState()) {
return;
}
// Reuse the previous sparse array if available. We shouldn't need to clear it since the
// exact same view type is being saved to it, which
// should have identical ids for all its views, and will just overwrite the previous state.
ViewState state = get(holder.getItemId());
if (state == null) {
state = new ViewState();
}
state.save(holder.itemView);
put(holder.getItemId(), state);
}
/**
* If a state was previously saved for this view holder via {@link #save} it will be restored
* here.
*/
public void restore(EpoxyViewHolder holder) {
if (!holder.getModel().shouldSaveViewState()) {
return;
}
ViewState state = get(holder.getItemId());
if (state != null) {
state.restore(holder.itemView);
} else {
// The first time a model is bound it won't have previous state. We need to make sure
// the view is reset to its initial state to clear any changes from previously bound models
holder.restoreInitialViewState();
}
}
/**
* A wrapper around a sparse array as a helper to save the state of a view. This also adds
* parcelable support.
*/
public static class ViewState extends SparseArray<Parcelable> implements Parcelable {
ViewState() {
}
private ViewState(int size, int[] keys, Parcelable[] values) {
super(size);
for (int i = 0; i < size; ++i) {
put(keys[i], values[i]);
}
}
public void save(View view) {
int originalId = view.getId();
setIdIfNoneExists(view);
view.saveHierarchyState(this);
view.setId(originalId);
}
public void restore(View view) {
int originalId = view.getId();
setIdIfNoneExists(view);
view.restoreHierarchyState(this);
view.setId(originalId);
}
/**
* If a view hasn't had an id set we need to set a temporary one in order to save state, since a
* view won't save its state unless it has an id. The view's id is also the key into the sparse
* array for its saved state, so the temporary one we choose just needs to be consistent between
* saving and restoring state.
*/
private void setIdIfNoneExists(View view) {
if (view.getId() == View.NO_ID) {
view.setId(R.id.view_model_state_saving_id);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
int size = size();
int[] keys = new int[size];
Parcelable[] values = new Parcelable[size];
for (int i = 0; i < size; ++i) {
keys[i] = keyAt(i);
values[i] = valueAt(i);
}
parcel.writeInt(size);
parcel.writeIntArray(keys);
parcel.writeParcelableArray(values, flags);
}
public static final Creator<ViewState> CREATOR =
new Parcelable.ClassLoaderCreator<ViewState>() {
@Override
public ViewState createFromParcel(Parcel source, ClassLoader loader) {
int size = source.readInt();
int[] keys = new int[size];
source.readIntArray(keys);
Parcelable[] values = source.readParcelableArray(loader);
return new ViewState(size, keys, values);
}
@Override
public ViewState createFromParcel(Parcel source) {
return createFromParcel(source, null);
}
@Override
public ViewState[] newArray(int size) {
return new ViewState[size];
}
};
}
}
| 8,907 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelLongClickListener.java | package com.airbnb.epoxy;
import android.view.View;
public interface OnModelLongClickListener<T extends EpoxyModel<?>, V> {
/**
* Called when the view bound to the model is clicked.
*
* @param model The model that the view is bound to.
* @param parentView The view bound to the model which received the click.
* @param clickedView The view that received the click. This is either a child of the parentView
* or the parentView itself
* @param position The position of the model in the adapter.
*/
boolean onLongClick(T model, V parentView, View clickedView, int position);
}
| 8,908 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/QuantityStringResAttribute.java | package com.airbnb.epoxy;
import android.content.Context;
import java.util.Arrays;
import androidx.annotation.Nullable;
import androidx.annotation.PluralsRes;
public class QuantityStringResAttribute {
@PluralsRes private final int id;
private final int quantity;
@Nullable private final Object[] formatArgs;
public QuantityStringResAttribute(@PluralsRes int id, int quantity,
@Nullable Object[] formatArgs) {
this.quantity = quantity;
this.id = id;
this.formatArgs = formatArgs;
}
public QuantityStringResAttribute(int id, int quantity) {
this(id, quantity, null);
}
@PluralsRes
public int getId() {
return id;
}
public int getQuantity() {
return quantity;
}
@Nullable
public Object[] getFormatArgs() {
return formatArgs;
}
public CharSequence toString(Context context) {
if (formatArgs == null || formatArgs.length == 0) {
return context.getResources().getQuantityString(id, quantity);
} else {
return context.getResources().getQuantityString(id, quantity, formatArgs);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof QuantityStringResAttribute)) {
return false;
}
QuantityStringResAttribute that = (QuantityStringResAttribute) o;
if (id != that.id) {
return false;
}
if (quantity != that.quantity) {
return false;
}
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(formatArgs, that.formatArgs);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + quantity;
result = 31 * result + Arrays.hashCode(formatArgs);
return result;
}
}
| 8,909 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/IllegalEpoxyUsage.java | package com.airbnb.epoxy;
public class IllegalEpoxyUsage extends RuntimeException {
public IllegalEpoxyUsage(String message) {
super(message);
}
}
| 8,910 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/IdUtils.java | package com.airbnb.epoxy;
import androidx.annotation.Nullable;
/**
* Utilities for generating 64-bit long IDs from types such as {@link CharSequence}.
*/
public final class IdUtils {
private IdUtils() {
}
/**
* Hash a long into 64 bits instead of the normal 32. This uses a xor shift implementation to
* attempt psuedo randomness so object ids have an even spread for less chance of collisions.
* <p>
* From http://stackoverflow.com/a/11554034
* <p>
* http://www.javamex.com/tutorials/random_numbers/xorshift.shtml
*/
public static long hashLong64Bit(long value) {
value ^= (value << 21);
value ^= (value >>> 35);
value ^= (value << 4);
return value;
}
/**
* Hash a string into 64 bits instead of the normal 32. This allows us to better use strings as a
* model id with less chance of collisions. This uses the FNV-1a algorithm for a good mix of speed
* and distribution.
* <p>
* Performance comparisons found at http://stackoverflow.com/a/1660613
* <p>
* Hash implementation from http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-1a
*/
public static long hashString64Bit(@Nullable CharSequence str) {
if (str == null) {
return 0;
}
long result = 0xcbf29ce484222325L;
final int len = str.length();
for (int i = 0; i < len; i++) {
result ^= str.charAt(i);
result *= 0x100000001b3L;
}
return result;
}
}
| 8,911 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ModelState.java | package com.airbnb.epoxy;
/** Helper to store relevant information about a model that we need to determine if it changed. */
class ModelState {
long id;
int hashCode;
int position;
EpoxyModel<?> model;
/**
* A link to the item with the same id in the other list when diffing two lists. This will be null
* if the item doesn't exist, in the case of insertions or removals. This is an optimization to
* prevent having to look up the matching pair in a hash map every time.
*/
ModelState pair;
/**
* How many movement operations have been applied to this item in order to update its position. As
* we find more item movements we need to update the position of affected items in the list in
* order to correctly calculate the next movement. Instead of iterating through all items in the
* list every time a movement operation happens we keep track of how many of these operations have
* been applied to an item, and apply all new operations in order when we need to get this item's
* up to date position.
*/
int lastMoveOp;
static ModelState build(EpoxyModel<?> model, int position, boolean immutableModel) {
ModelState state = new ModelState();
state.lastMoveOp = 0;
state.pair = null;
state.id = model.id();
state.position = position;
if (immutableModel) {
state.model = model;
} else {
state.hashCode = model.hashCode();
}
return state;
}
/**
* Used for an item inserted into the new list when we need to track moves that effect the
* inserted item in the old list.
*/
void pairWithSelf() {
if (pair != null) {
throw new IllegalStateException("Already paired.");
}
pair = new ModelState();
pair.lastMoveOp = 0;
pair.id = id;
pair.position = position;
pair.hashCode = hashCode;
pair.pair = this;
pair.model = model;
}
@Override
public String toString() {
return "ModelState{"
+ "id=" + id
+ ", model=" + model
+ ", hashCode=" + hashCode
+ ", position=" + position
+ ", pair=" + pair
+ ", lastMoveOp=" + lastMoveOp
+ '}';
}
}
| 8,912 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/GeneratedModel.java | package com.airbnb.epoxy;
/** Interface applied to generated models to allow the base adapter to interact with them. */
public interface GeneratedModel<T> {
/**
* Called on the generated model immediately before the main model onBind method has been called.
* This let's the generated model handle binding setup of its own
* <p>
* The ViewHolder is needed to get the model's adapter position when clicked.
*/
void handlePreBind(EpoxyViewHolder holder, T objectToBind, int position);
/**
* Called on the generated model immediately after the main model onBind method has been called.
* This let's the generated model handle binding of its own and dispatch calls to its onBind
* listener.
* <p>
* We don't want to rely on the main onBind method to dispatch the onBind listener call because
* there are two onBind methods (one for payloads and one for no payloads), and one can call into
* the other. We don't want to dispatch two onBind listener calls in that case.
*/
void handlePostBind(T objectToBind, int position);
}
| 8,913 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/Typed2EpoxyController.java | package com.airbnb.epoxy;
import android.os.Handler;
/**
* This is a wrapper around {@link com.airbnb.epoxy.EpoxyController} to simplify how data is
* accessed. Use this if the data required to build your models is represented by two objects.
* <p>
* To use this, create a subclass typed with your data object. Then, call {@link #setData}
* whenever that data changes. This class will handle calling {@link #buildModels} with the
* latest data.
* <p>
* You should NOT call {@link #requestModelBuild()} directly.
*
* @see TypedEpoxyController
* @see Typed3EpoxyController
* @see Typed4EpoxyController
*/
public abstract class Typed2EpoxyController<T, U> extends EpoxyController {
private T data1;
private U data2;
private boolean allowModelBuildRequests;
public Typed2EpoxyController() {
}
public Typed2EpoxyController(Handler modelBuildingHandler, Handler diffingHandler) {
super(modelBuildingHandler, diffingHandler);
}
/**
* Call this with the latest data when you want models to be rebuilt. The data will be passed on
* to {@link #buildModels(Object, Object)}
*/
public void setData(T data1, U data2) {
this.data1 = data1;
this.data2 = data2;
allowModelBuildRequests = true;
requestModelBuild();
allowModelBuildRequests = false;
}
@Override
public final void requestModelBuild() {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestModelBuild();
}
@Override
public void moveModel(int fromPosition, int toPosition) {
allowModelBuildRequests = true;
super.moveModel(fromPosition, toPosition);
allowModelBuildRequests = false;
}
@Override
public void requestDelayedModelBuild(int delayMs) {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestDelayedModelBuild(delayMs);
}
@Override
protected final void buildModels() {
if (!isBuildingModels()) {
throw new IllegalStateException(
"You cannot call `buildModels` directly. Call `setData` instead to trigger a model "
+ "refresh with new data.");
}
buildModels(data1, data2);
}
protected abstract void buildModels(T data1, U data2);
}
| 8,914 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/WrappedEpoxyModelCheckedChangeListener.java | package com.airbnb.epoxy;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import androidx.recyclerview.widget.RecyclerView;
/**
* Used in the generated models to transform normal checked change listener to model
* checked change.
*/
public class WrappedEpoxyModelCheckedChangeListener<T extends EpoxyModel<?>, V>
implements OnCheckedChangeListener {
private final OnModelCheckedChangeListener<T, V> originalCheckedChangeListener;
public WrappedEpoxyModelCheckedChangeListener(
OnModelCheckedChangeListener<T, V> checkedListener
) {
if (checkedListener == null) {
throw new IllegalArgumentException("Checked change listener cannot be null");
}
this.originalCheckedChangeListener = checkedListener;
}
@Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
EpoxyViewHolder epoxyHolder = ListenersUtils.getEpoxyHolderForChildView(button);
if (epoxyHolder == null) {
// Initial binding can trigger the checked changed listener when the checked value is set.
// The view is not attached at this point so the holder can't be looked up, and in any case
// it is generally better to not trigger a callback for the binding anyway, since it isn't
// a user action.
//
// https://github.com/airbnb/epoxy/issues/797
return;
}
final int adapterPosition = epoxyHolder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
originalCheckedChangeListener
.onChecked((T) epoxyHolder.getModel(), (V) epoxyHolder.objectToBind(), button,
isChecked, adapterPosition);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof WrappedEpoxyModelCheckedChangeListener)) {
return false;
}
WrappedEpoxyModelCheckedChangeListener<?, ?>
that = (WrappedEpoxyModelCheckedChangeListener<?, ?>) o;
return originalCheckedChangeListener.equals(that.originalCheckedChangeListener);
}
@Override
public int hashCode() {
return originalCheckedChangeListener.hashCode();
}
}
| 8,915 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/UpdateOp.java |
package com.airbnb.epoxy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
/** Defines an operation that makes a change to the epoxy model list. */
class UpdateOp {
@IntDef({ADD, REMOVE, UPDATE, MOVE})
@Retention(RetentionPolicy.SOURCE)
@interface Type {
}
static final int ADD = 0;
static final int REMOVE = 1;
static final int UPDATE = 2;
static final int MOVE = 3;
@Type int type;
int positionStart;
/** Holds the target position if this is a MOVE */
int itemCount;
ArrayList<EpoxyModel<?>> payloads;
private UpdateOp() {
}
static UpdateOp instance(@Type int type, int positionStart, int itemCount,
@Nullable EpoxyModel<?> payload) {
UpdateOp op = new UpdateOp();
op.type = type;
op.positionStart = positionStart;
op.itemCount = itemCount;
op.addPayload(payload);
return op;
}
/** Returns the index one past the last item in the affected range. */
int positionEnd() {
return positionStart + itemCount;
}
boolean isAfter(int position) {
return position < positionStart;
}
boolean isBefore(int position) {
return position >= positionEnd();
}
boolean contains(int position) {
return position >= positionStart && position < positionEnd();
}
void addPayload(@Nullable EpoxyModel<?> payload) {
if (payload == null) {
return;
}
if (payloads == null) {
// In most cases this won't be a batch update so we can expect just one payload
payloads = new ArrayList<>(1);
} else if (payloads.size() == 1) {
// There are multiple payloads, but we don't know how big the batch will end up being.
// To prevent resizing the list many times we bump it to a medium size
payloads.ensureCapacity(10);
}
payloads.add(payload);
}
@Override
public String toString() {
return "UpdateOp{"
+ "type=" + type
+ ", positionStart=" + positionStart
+ ", itemCount=" + itemCount
+ '}';
}
}
| 8,916 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/Typed3EpoxyController.java | package com.airbnb.epoxy;
import android.os.Handler;
/**
* This is a wrapper around {@link com.airbnb.epoxy.EpoxyController} to simplify how data is
* accessed. Use this if the data required to build your models is represented by three objects.
* <p>
* To use this, create a subclass typed with your data object. Then, call {@link #setData}
* whenever that data changes. This class will handle calling {@link #buildModels} with the
* latest data.
* <p>
* You should NOT call {@link #requestModelBuild()} directly.
*
* @see TypedEpoxyController
* @see Typed2EpoxyController
* @see Typed4EpoxyController
*/
public abstract class Typed3EpoxyController<T, U, V> extends EpoxyController {
private T data1;
private U data2;
private V data3;
private boolean allowModelBuildRequests;
public Typed3EpoxyController() {
}
public Typed3EpoxyController(Handler modelBuildingHandler, Handler diffingHandler) {
super(modelBuildingHandler, diffingHandler);
}
/**
* Call this with the latest data when you want models to be rebuilt. The data will be passed on
* to {@link #buildModels(Object, Object, Object)}
*/
public void setData(T data1, U data2, V data3) {
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
allowModelBuildRequests = true;
requestModelBuild();
allowModelBuildRequests = false;
}
@Override
public final void requestModelBuild() {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestModelBuild();
}
@Override
public void moveModel(int fromPosition, int toPosition) {
allowModelBuildRequests = true;
super.moveModel(fromPosition, toPosition);
allowModelBuildRequests = false;
}
@Override
public void requestDelayedModelBuild(int delayMs) {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestDelayedModelBuild(delayMs);
}
@Override
protected final void buildModels() {
if (!isBuildingModels()) {
throw new IllegalStateException(
"You cannot call `buildModels` directly. Call `setData` instead to trigger a model "
+ "refresh with new data.");
}
buildModels(data1, data2, data3);
}
protected abstract void buildModels(T data1, U data2, V data3);
}
| 8,917 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelBuildFinishedListener.java | package com.airbnb.epoxy;
import androidx.annotation.NonNull;
/**
* Used with {@link EpoxyController#addModelBuildListener(OnModelBuildFinishedListener)} to be
* alerted to new model changes.
*/
public interface OnModelBuildFinishedListener {
/**
* Called after {@link EpoxyController#buildModels()} has run and changes have been notified to
* the adapter. This will be called even if no changes existed.
*/
void onModelBuildFinished(@NonNull DiffResult result);
}
| 8,918 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/HandlerExecutor.java | package com.airbnb.epoxy;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import androidx.annotation.NonNull;
/**
* An executor that does it's work via posting to a Handler.
* <p>
* A key feature of this is the runnable is executed synchronously if the current thread is the
* same as the handler's thread.
*/
class HandlerExecutor implements Executor {
final Handler handler;
HandlerExecutor(Handler handler) {
this.handler = handler;
}
@Override
public void execute(@NonNull Runnable command) {
// If we're already on the same thread then we can execute this synchronously
if (Looper.myLooper() == handler.getLooper()) {
command.run();
} else {
handler.post(command);
}
}
}
| 8,919 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/AsyncEpoxyController.java | package com.airbnb.epoxy;
import android.os.Handler;
import static com.airbnb.epoxy.EpoxyAsyncUtil.MAIN_THREAD_HANDLER;
import static com.airbnb.epoxy.EpoxyAsyncUtil.getAsyncBackgroundHandler;
/**
* A subclass of {@link EpoxyController} that makes it easy to do model building and diffing in
* the background.
* <p>
* See https://github.com/airbnb/epoxy/wiki/Epoxy-Controller#asynchronous-support
*/
public abstract class AsyncEpoxyController extends EpoxyController {
/**
* A new instance that does model building and diffing asynchronously.
*/
public AsyncEpoxyController() {
this(true);
}
/**
* @param enableAsync True to do model building and diffing asynchronously, false to do them
* both on the main thread.
*/
public AsyncEpoxyController(boolean enableAsync) {
this(enableAsync, enableAsync);
}
/**
* Individually control whether model building and diffing are done async or on the main thread.
*/
public AsyncEpoxyController(boolean enableAsyncModelBuilding, boolean enableAsyncDiffing) {
super(getHandler(enableAsyncModelBuilding), getHandler(enableAsyncDiffing));
}
private static Handler getHandler(boolean enableAsync) {
return enableAsync ? getAsyncBackgroundHandler() : MAIN_THREAD_HANDLER;
}
}
| 8,920 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyAsyncUtil.java | package com.airbnb.epoxy;
import android.os.Build;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.MainThread;
/**
* Various helpers for running Epoxy operations off the main thread.
*/
public final class EpoxyAsyncUtil {
private EpoxyAsyncUtil() {
}
/**
* A Handler class that uses the main thread's Looper.
*/
public static final Handler MAIN_THREAD_HANDLER =
createHandler(Looper.getMainLooper(), false);
/**
* A Handler class that uses the main thread's Looper. Additionally, this handler calls
* {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it
*/
public static final Handler AYSNC_MAIN_THREAD_HANDLER =
createHandler(Looper.getMainLooper(), true);
private static Handler asyncBackgroundHandler;
/**
* A Handler class that uses a separate background thread dedicated to Epoxy. Additionally,
* this handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it
*/
@MainThread
public static Handler getAsyncBackgroundHandler() {
// This is initialized lazily so we don't create the thread unless it will be used.
// It isn't synchronized so it should only be accessed on the main thread.
if (asyncBackgroundHandler == null) {
asyncBackgroundHandler = createHandler(buildBackgroundLooper("epoxy"), true);
}
return asyncBackgroundHandler;
}
/**
* Create a Handler with the given Looper
*
* @param async If true the Handler will calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*/
public static Handler createHandler(Looper looper, boolean async) {
if (!async) {
return new Handler(looper);
}
// Standard way of exposing async handler on older api's from the support library
// https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/core
// /src/main/java/androidx/core/os/HandlerCompat.java#51
if (Build.VERSION.SDK_INT >= 28) {
return Handler.createAsync(looper);
}
if (Build.VERSION.SDK_INT >= 16) {
try {
//noinspection JavaReflectionMemberAccess
return Handler.class.getDeclaredConstructor(Looper.class, Callback.class, boolean.class)
.newInstance(looper, null, true);
} catch (Throwable ignored) {
}
}
return new Handler(looper);
}
/**
* Create a new looper that runs on a new background thread.
*/
public static Looper buildBackgroundLooper(String threadName) {
HandlerThread handlerThread = new HandlerThread(threadName);
handlerThread.start();
return handlerThread.getLooper();
}
}
| 8,921 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ViewTypeManager.java | package com.airbnb.epoxy;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
class ViewTypeManager {
private static final Map<Class, Integer> VIEW_TYPE_MAP = new HashMap<>();
/**
* The last model that had its view type looked up. This is stored so in most cases we can quickly
* look up what view type belongs to which model.
*/
@Nullable
EpoxyModel<?> lastModelForViewTypeLookup;
/**
* The type map is static so that models of the same class share the same views across different
* adapters. This is useful for view recycling when the adapter instance changes, or when there
* are multiple adapters. For testing purposes though it is good to be able to clear the map so we
* don't carry over values across tests.
*/
@VisibleForTesting
void resetMapForTesting() {
VIEW_TYPE_MAP.clear();
}
int getViewTypeAndRememberModel(EpoxyModel<?> model) {
lastModelForViewTypeLookup = model;
return getViewType(model);
}
static int getViewType(EpoxyModel<?> model) {
int defaultViewType = model.getViewType();
if (defaultViewType != 0) {
return defaultViewType;
}
// If a model does not specify a view type then we generate a value to use for models of that
// class.
Class modelClass = model.getClass();
Integer viewType = VIEW_TYPE_MAP.get(modelClass);
if (viewType == null) {
viewType = -VIEW_TYPE_MAP.size() - 1;
VIEW_TYPE_MAP.put(modelClass, viewType);
}
return viewType;
}
/**
* Find the model that has the given view type so we can create a view for that model. In most
* cases this value is a layout resource and we could simply inflate it, but to support {@link
* EpoxyModelWithView} we can't assume the view type is a layout. In that case we need to lookup
* the model so we can ask it to create a new view for itself.
* <p>
* To make this efficient, we rely on the RecyclerView implementation detail that {@link
* BaseEpoxyAdapter#getItemViewType(int)} is called immediately before {@link
* BaseEpoxyAdapter#onCreateViewHolder(android.view.ViewGroup, int)} . We cache the last model
* that had its view type looked up, and unless that implementation changes we expect to have a
* very fast lookup for the correct model.
* <p>
* To be safe, we fallback to searching through all models for a view type match. This is slow and
* shouldn't be needed, but is a guard against recyclerview behavior changing.
*/
EpoxyModel<?> getModelForViewType(BaseEpoxyAdapter adapter, int viewType) {
if (lastModelForViewTypeLookup != null
&& getViewType(lastModelForViewTypeLookup) == viewType) {
// We expect this to be a hit 100% of the time
return lastModelForViewTypeLookup;
}
adapter.onExceptionSwallowed(
new IllegalStateException("Last model did not match expected view type"));
// To be extra safe in case RecyclerView implementation details change...
for (EpoxyModel<?> model : adapter.getCurrentModels()) {
if (getViewType(model) == viewType) {
return model;
}
}
// Check for the hidden model.
HiddenEpoxyModel hiddenEpoxyModel = new HiddenEpoxyModel();
if (viewType == hiddenEpoxyModel.getViewType()) {
return hiddenEpoxyModel;
}
throw new IllegalStateException("Could not find model for view type: " + viewType);
}
}
| 8,922 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/VisibilityState.java | package com.airbnb.epoxy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import androidx.annotation.IntDef;
public final class VisibilityState {
@Retention(RetentionPolicy.SOURCE)
@IntDef({VISIBLE,
INVISIBLE,
FOCUSED_VISIBLE,
UNFOCUSED_VISIBLE,
FULL_IMPRESSION_VISIBLE,
PARTIAL_IMPRESSION_VISIBLE,
PARTIAL_IMPRESSION_INVISIBLE})
public @interface Visibility {
}
/**
* Event triggered when a Component enters the Visible Range. This happens when at least a pixel
* of the Component is visible.
*/
public static final int VISIBLE = 0;
/**
* Event triggered when a Component becomes invisible. This is the same with exiting the Visible
* Range, the Focused Range and the Full Impression Range. All the code that needs to be executed
* when a component leaves any of these ranges should be written in the handler for this event.
*/
public static final int INVISIBLE = 1;
/**
* Event triggered when a Component enters the Focused Range. This happens when either the
* Component occupies at least half of the viewport or, if the Component is smaller than half of
* the viewport, when the it is fully visible.
*/
public static final int FOCUSED_VISIBLE = 2;
/**
* Event triggered when a Component exits the Focused Range. The Focused Range is defined as at
* least half of the viewport or, if the Component is smaller than half of the viewport, when the
* it is fully visible.
*/
public static final int UNFOCUSED_VISIBLE = 3;
/**
* Event triggered when a Component enters the Full Impression Range. This happens, for instance
* in the case of a vertical RecyclerView, when both the top and bottom edges of the component
* become visible.
*/
public static final int FULL_IMPRESSION_VISIBLE = 4;
/**
* Event triggered when a Component enters the Partial Impression Range. This happens, for
* instance in the case of a vertical RecyclerView, when the percentage of the visible area is
* at least the specified threshold. The threshold can be set in
* {@link EpoxyVisibilityTracker#setPartialImpressionThresholdPercentage(int)}.
*/
public static final int PARTIAL_IMPRESSION_VISIBLE = 5;
/**
* Event triggered when a Component exits the Partial Impression Range. This happens, for
* instance in the case of a vertical RecyclerView, when the percentage of the visible area is
* less than a specified threshold. The threshold can be set in
* {@link EpoxyVisibilityTracker#setPartialImpressionThresholdPercentage(int)}.
*/
public static final int PARTIAL_IMPRESSION_INVISIBLE = 6;
}
| 8,923 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/SimpleEpoxyModel.java | package com.airbnb.epoxy;
import android.view.View;
import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
/**
* Helper class for cases where you don't need to do anything special when binding the view. This
* allows you to just provide the layout instead of needing to create a separate {@link EpoxyModel}
* subclass. This is useful for static layouts. You can also specify an onClick listener and the
* span size.
*/
public class SimpleEpoxyModel extends EpoxyModel<View> {
@LayoutRes private final int layoutRes;
private View.OnClickListener onClickListener;
private int spanCount = 1;
public SimpleEpoxyModel(@LayoutRes int layoutRes) {
this.layoutRes = layoutRes;
}
public SimpleEpoxyModel onClick(View.OnClickListener listener) {
this.onClickListener = listener;
return this;
}
public SimpleEpoxyModel span(int span) {
spanCount = span;
return this;
}
@CallSuper
@Override
public void bind(@NonNull View view) {
super.bind(view);
view.setOnClickListener(onClickListener);
view.setClickable(onClickListener != null);
}
@CallSuper
@Override
public void unbind(@NonNull View view) {
super.unbind(view);
view.setOnClickListener(null);
}
@Override
protected int getDefaultLayout() {
return layoutRes;
}
@Override
public int getSpanSize(int totalSpanCount, int position, int itemCount) {
return spanCount;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SimpleEpoxyModel)) {
return false;
}
if (!super.equals(o)) {
return false;
}
SimpleEpoxyModel that = (SimpleEpoxyModel) o;
if (layoutRes != that.layoutRes) {
return false;
}
if (spanCount != that.spanCount) {
return false;
}
return onClickListener != null ? onClickListener.equals(that.onClickListener)
: that.onClickListener == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + layoutRes;
result = 31 * result + (onClickListener != null ? onClickListener.hashCode() : 0);
result = 31 * result + spanCount;
return result;
}
}
| 8,924 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/Carousel.java | package com.airbnb.epoxy;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import com.airbnb.epoxy.ModelView.Size;
import com.airbnb.viewmodeladapter.R;
import java.util.List;
import androidx.annotation.DimenRes;
import androidx.annotation.Dimension;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.SnapHelper;
/**
* <i>This feature is in Beta - please report bugs, feature requests, or other feedback at
* https://github.com/airbnb/epoxy by creating a new issue. Thanks!</i>
*
* <p>This is intended as a plug and play "Carousel" view - a Recyclerview with horizontal
* scrolling. It comes with common defaults and performance optimizations and can be either used as
* a top level RecyclerView, or nested within a vertical recyclerview.
*
* <p>This class provides:
*
* <p>1. Automatic integration with Epoxy. A {@link CarouselModel_} is generated from this class,
* which you can use in your EpoxyController. Just call {@link #setModels(List)} to provide the list
* of models to show in the carousel.
*
* <p>2. Default padding for carousel peeking, and an easy way to change this padding - {@link
* #setPaddingDp(int)}
*
* <p>3. Easily control how many items are shown on screen in the carousel at a time - {@link
* #setNumViewsToShowOnScreen(float)}
*
* <p>4. Easy snap support. By default a {@link LinearSnapHelper} is used, but you can set a global
* default for all Carousels with {@link #setDefaultGlobalSnapHelperFactory(SnapHelperFactory)}
*
* <p>5. All of the benefits of {@link EpoxyRecyclerView}
*
* <p>If you need further flexibility you can subclass this view to change its width, height,
* scrolling direction, etc. You can annotate a subclass with {@link ModelView} to generate a new
* EpoxyModel.
*/
@ModelView(saveViewState = true, autoLayout = Size.MATCH_WIDTH_WRAP_HEIGHT)
public class Carousel extends EpoxyRecyclerView {
public static final int NO_VALUE_SET = -1;
private static SnapHelperFactory defaultGlobalSnapHelperFactory =
new SnapHelperFactory() {
@Override
@NonNull
public SnapHelper buildSnapHelper(Context context) {
return new LinearSnapHelper();
}
};
@Dimension(unit = Dimension.DP)
private static int defaultSpacingBetweenItemsDp = 8;
private float numViewsToShowOnScreen;
public Carousel(Context context) {
super(context);
}
public Carousel(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public Carousel(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
// When used as a model the padding can't be set via xml so we set it programmatically
int defaultSpacingDp = getDefaultSpacingBetweenItemsDp();
if (defaultSpacingDp >= 0) {
setItemSpacingDp(defaultSpacingDp);
if (getPaddingLeft() == 0
&& getPaddingRight() == 0
&& getPaddingTop() == 0
&& getPaddingBottom() == 0) {
// Use the item spacing as the default padding if no other padding has been set
setPaddingDp(defaultSpacingDp);
}
}
SnapHelperFactory snapHelperFactory = getSnapHelperFactory();
if (snapHelperFactory != null) {
snapHelperFactory.buildSnapHelper(getContext()).attachToRecyclerView(this);
}
// Carousels will be detached when their parent recyclerview is
setRemoveAdapterWhenDetachedFromWindow(false);
}
/**
* Return a {@link SnapHelperFactory} instance to use with this Carousel. The {@link SnapHelper}
* created by the factory will be attached to this Carousel on view creation. Return null for no
* snap helper to be attached automatically.
*/
@Nullable
protected SnapHelperFactory getSnapHelperFactory() {
return defaultGlobalSnapHelperFactory;
}
/**
* Set a {@link SnapHelperFactory} instance to use with all Carousels by default. The {@link
* SnapHelper} created by the factory will be attached to each Carousel on view creation. Set null
* for no snap helper to be attached automatically.
*
* <p>A Carousel subclass can implement {@link #getSnapHelperFactory()} to override the global
* default.
*/
public static void setDefaultGlobalSnapHelperFactory(@Nullable SnapHelperFactory factory) {
defaultGlobalSnapHelperFactory = factory;
}
@ModelProp
@Override
public void setHasFixedSize(boolean hasFixedSize) {
super.setHasFixedSize(hasFixedSize);
}
/**
* Set the number of views to show on screen in this carousel at a time, partial numbers are
* allowed.
*
* <p>This is useful where you want to easily control for the number of items on screen,
* regardless of screen size. For example, you could set this to 1.2f so that one view is shown in
* full and 20% of the next view "peeks" from the edge to indicate that there is more content to
* scroll to.
*
* <p>Another pattern is setting a different view count depending on whether the device is phone
* or tablet.
*
* <p>Additionally, if a LinearLayoutManager is used this value will be forwarded to {@link
* LinearLayoutManager#setInitialPrefetchItemCount(int)} as a performance optimization.
*
* <p>If you want to only change the prefetch count without changing the view size you can simply
* use {@link #setInitialPrefetchItemCount(int)}
*/
@ModelProp(group = "prefetch")
public void setNumViewsToShowOnScreen(float viewCount) {
numViewsToShowOnScreen = viewCount;
setInitialPrefetchItemCount((int) Math.ceil(viewCount));
}
/**
* @return The number of views to show on screen in this carousel at a time.
*/
public float getNumViewsToShowOnScreen() {
return numViewsToShowOnScreen;
}
/**
* If you are using a Linear or Grid layout manager you can use this to set the item prefetch
* count. Only use this if you are not using {@link #setNumViewsToShowOnScreen(float)}
*
* @see #setNumViewsToShowOnScreen(float)
* @see LinearLayoutManager#setInitialPrefetchItemCount(int)
*/
@ModelProp(group = "prefetch")
public void setInitialPrefetchItemCount(int numItemsToPrefetch) {
if (numItemsToPrefetch < 0) {
throw new IllegalStateException("numItemsToPrefetch must be greater than 0");
}
// Use the linearlayoutmanager default of 2 if the user did not specify one
int prefetchCount = numItemsToPrefetch == 0 ? 2 : numItemsToPrefetch;
LayoutManager layoutManager = getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
((LinearLayoutManager) layoutManager).setInitialPrefetchItemCount(prefetchCount);
}
}
@Override
public void onChildAttachedToWindow(View child) {
if (numViewsToShowOnScreen > 0) {
ViewGroup.LayoutParams childLayoutParams = child.getLayoutParams();
child.setTag(R.id.epoxy_recycler_view_child_initial_size_id, childLayoutParams.width);
int itemSpacingPx = getSpacingDecorator().getPxBetweenItems();
int spaceBetweenItems = 0;
if (itemSpacingPx > 0) {
// The item decoration space is not counted in the width of the view
spaceBetweenItems = (int) (itemSpacingPx * numViewsToShowOnScreen);
}
boolean isScrollingHorizontally = getLayoutManager().canScrollHorizontally();
int itemSizeInScrollingDirection =
(int)
((getSpaceForChildren(isScrollingHorizontally) - spaceBetweenItems)
/ numViewsToShowOnScreen);
if (isScrollingHorizontally) {
childLayoutParams.width = itemSizeInScrollingDirection;
} else {
childLayoutParams.height = itemSizeInScrollingDirection;
}
// We don't need to request layout because the layout manager will do that for us next
}
}
private int getSpaceForChildren(boolean horizontal) {
if (horizontal) {
return getTotalWidthPx(this)
- getPaddingLeft()
- (getClipToPadding() ? getPaddingRight() : 0);
// If child views will be showing through padding than we include just one side of padding
// since when the list is at position 0 only the child towards the end of the list will show
// through the padding.
} else {
return getTotalHeightPx(this)
- getPaddingTop()
- (getClipToPadding() ? getPaddingBottom() : 0);
}
}
@Px
private static int getTotalWidthPx(View view) {
if (view.getWidth() > 0) {
// Can only get a width if we are laid out
return view.getWidth();
}
if (view.getMeasuredWidth() > 0) {
return view.getMeasuredWidth();
}
// Fall back to assuming we want the full screen width
DisplayMetrics metrics = view.getContext().getResources().getDisplayMetrics();
return metrics.widthPixels;
}
@Px
private static int getTotalHeightPx(View view) {
if (view.getHeight() > 0) {
return view.getHeight();
}
if (view.getMeasuredHeight() > 0) {
return view.getMeasuredHeight();
}
// Fall back to assuming we want the full screen width
DisplayMetrics metrics = view.getContext().getResources().getDisplayMetrics();
return metrics.heightPixels;
}
@Override
public void onChildDetachedFromWindow(View child) {
// Restore the view width that existed before we modified it
Object initialWidth = child.getTag(R.id.epoxy_recycler_view_child_initial_size_id);
if (initialWidth instanceof Integer) {
ViewGroup.LayoutParams params = child.getLayoutParams();
params.width = (int) initialWidth;
child.setTag(R.id.epoxy_recycler_view_child_initial_size_id, null);
// No need to request layout since the view is unbound and not attached to window
}
}
/**
* Set a global default to use as the item spacing for all Carousels. Set to 0 for no item
* spacing.
*/
public static void setDefaultItemSpacingDp(@Dimension(unit = Dimension.DP) int dp) {
defaultSpacingBetweenItemsDp = dp;
}
/**
* Return the item spacing to use in this carousel, or 0 for no spacing.
*
* <p>By default this uses the global default set in {@link #setDefaultItemSpacingDp(int)}, but
* subclasses can override this to specify their own value.
*/
@Dimension(unit = Dimension.DP)
protected int getDefaultSpacingBetweenItemsDp() {
return defaultSpacingBetweenItemsDp;
}
/**
* Set a dimension resource to specify the padding value to use on each side of the carousel and
* in between carousel items.
*/
@ModelProp(group = "padding")
public void setPaddingRes(@DimenRes int paddingRes) {
int px = resToPx(paddingRes);
setPadding(px, px, px, px);
setItemSpacingPx(px);
}
/**
* Set a DP value to use as the padding on each side of the carousel and in between carousel
* items.
*
* <p>The default as the value returned by {@link #getDefaultSpacingBetweenItemsDp()}
*/
@ModelProp(defaultValue = "NO_VALUE_SET", group = "padding")
public void setPaddingDp(@Dimension(unit = Dimension.DP) int paddingDp) {
int px = dpToPx(paddingDp != NO_VALUE_SET ? paddingDp : getDefaultSpacingBetweenItemsDp());
setPadding(px, px, px, px);
setItemSpacingPx(px);
}
/**
* Use the {@link Padding} class to specify individual padding values for each side of the
* carousel, as well as item spacing.
*
* <p>A value of null will set all padding and item spacing to 0.
*/
@ModelProp(group = "padding")
public void setPadding(@Nullable Padding padding) {
if (padding == null) {
setPaddingDp(0);
} else if (padding.paddingType == Padding.PaddingType.PX) {
setPadding(padding.left, padding.top, padding.right, padding.bottom);
setItemSpacingPx(padding.itemSpacing);
} else if (padding.paddingType == Padding.PaddingType.DP) {
setPadding(
dpToPx(padding.left), dpToPx(padding.top), dpToPx(padding.right), dpToPx(padding.bottom));
setItemSpacingPx(dpToPx(padding.itemSpacing));
} else if (padding.paddingType == Padding.PaddingType.RESOURCE) {
setPadding(
resToPx(padding.left),
resToPx(padding.top),
resToPx(padding.right),
resToPx(padding.bottom));
setItemSpacingPx(resToPx(padding.itemSpacing));
}
}
/**
* Used to specify individual padding values programmatically.
*
* @see #setPadding(Padding)
*/
public static class Padding {
public final int left;
public final int top;
public final int right;
public final int bottom;
public final int itemSpacing;
public final PaddingType paddingType;
enum PaddingType {
PX,
DP,
RESOURCE
}
/**
* @param paddingRes Padding as dimension resource.
* @param itemSpacingRes Space as dimension resource to add between each carousel item. Will be
* implemented via an item decoration.
*/
public static Padding resource(@DimenRes int paddingRes, @DimenRes int itemSpacingRes) {
return new Padding(
paddingRes, paddingRes, paddingRes, paddingRes, itemSpacingRes, PaddingType.RESOURCE);
}
/**
* @param leftRes Left padding as dimension resource.
* @param topRes Top padding as dimension resource.
* @param rightRes Right padding as dimension resource.
* @param bottomRes Bottom padding as dimension resource.
* @param itemSpacingRes Space as dimension resource to add between each carousel item. Will be
* implemented via an item decoration.
*/
public static Padding resource(
@DimenRes int leftRes,
@DimenRes int topRes,
@DimenRes int rightRes,
@DimenRes int bottomRes,
@DimenRes int itemSpacingRes) {
return new Padding(
leftRes, topRes, rightRes, bottomRes, itemSpacingRes, PaddingType.RESOURCE);
}
/**
* @param paddingDp Padding in dp.
* @param itemSpacingDp Space in dp to add between each carousel item. Will be implemented via
* an item decoration.
*/
public static Padding dp(
@Dimension(unit = Dimension.DP) int paddingDp,
@Dimension(unit = Dimension.DP) int itemSpacingDp) {
return new Padding(paddingDp, paddingDp, paddingDp, paddingDp, itemSpacingDp, PaddingType.DP);
}
/**
* @param leftDp Left padding in dp.
* @param topDp Top padding in dp.
* @param rightDp Right padding in dp.
* @param bottomDp Bottom padding in dp.
* @param itemSpacingDp Space in dp to add between each carousel item. Will be implemented via
* an item decoration.
*/
public static Padding dp(
@Dimension(unit = Dimension.DP) int leftDp,
@Dimension(unit = Dimension.DP) int topDp,
@Dimension(unit = Dimension.DP) int rightDp,
@Dimension(unit = Dimension.DP) int bottomDp,
@Dimension(unit = Dimension.DP) int itemSpacingDp) {
return new Padding(leftDp, topDp, rightDp, bottomDp, itemSpacingDp, PaddingType.DP);
}
/**
* @param paddingPx Padding in pixels to add on all sides of the carousel
* @param itemSpacingPx Space in pixels to add between each carousel item. Will be implemented
* via an item decoration.
*/
public Padding(@Px int paddingPx, @Px int itemSpacingPx) {
this(paddingPx, paddingPx, paddingPx, paddingPx, itemSpacingPx, PaddingType.PX);
}
/**
* @param leftPx Left padding in pixels.
* @param topPx Top padding in pixels.
* @param rightPx Right padding in pixels.
* @param bottomPx Bottom padding in pixels.
* @param itemSpacingPx Space in pixels to add between each carousel item. Will be implemented
* via an item decoration.
*/
public Padding(
@Px int leftPx, @Px int topPx, @Px int rightPx, @Px int bottomPx, @Px int itemSpacingPx) {
this(leftPx, topPx, rightPx, bottomPx, itemSpacingPx, PaddingType.PX);
}
/**
* @param left Left padding.
* @param top Top padding.
* @param right Right padding.
* @param bottom Bottom padding.
* @param itemSpacing Space to add between each carousel item. Will be implemented via an item
* decoration.
* @param paddingType Unit / Type of the given paddings/ itemspacing.
*/
private Padding(
int left, int top, int right, int bottom, int itemSpacing, PaddingType paddingType) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.itemSpacing = itemSpacing;
this.paddingType = paddingType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Padding padding = (Padding) o;
if (left != padding.left) {
return false;
}
if (top != padding.top) {
return false;
}
if (right != padding.right) {
return false;
}
if (bottom != padding.bottom) {
return false;
}
return itemSpacing == padding.itemSpacing;
}
@Override
public int hashCode() {
int result = left;
result = 31 * result + top;
result = 31 * result + right;
result = 31 * result + bottom;
result = 31 * result + itemSpacing;
return result;
}
}
@ModelProp
public void setModels(@NonNull List<? extends EpoxyModel<?>> models) {
super.setModels(models);
}
@OnViewRecycled
public void clear() {
super.clear();
}
/** Provide a SnapHelper implementation you want to use with a Carousel. */
public abstract static class SnapHelperFactory {
/**
* Create and return a new instance of a {@link androidx.recyclerview.widget.SnapHelper} for use
* with a Carousel.
*/
@NonNull
public abstract SnapHelper buildSnapHelper(Context context);
}
}
| 8,925 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/BaseEpoxyTouchCallback.java | package com.airbnb.epoxy;
import android.view.View;
interface BaseEpoxyTouchCallback<T extends EpoxyModel> {
/**
* Should return a composite flag which defines the enabled move directions in each state
* (idle, swiping, dragging) for the given model.
* <p>
* Return 0 to disable movement for the model.
*
* @param model The model being targeted for movement.
* @param adapterPosition The current adapter position of the targeted model
* @see androidx.recyclerview.widget.ItemTouchHelper.Callback#getMovementFlags
*/
int getMovementFlagsForModel(T model, int adapterPosition);
/**
* Called when the user interaction with a view is over and the view has
* completed its animation. This is a good place to clear all changes on the view that were done
* in other previous touch callbacks (such as on touch start, change, release, etc).
* <p>
* This is the last callback in the lifecycle of a touch event.
*
* @param model The model whose view is being cleared.
* @param itemView The view being cleared.
*/
void clearView(T model, View itemView);
}
| 8,926 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyModelWithView.java | package com.airbnb.epoxy;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
/**
* A model that allows its view to be built programmatically instead of by inflating a layout
* resource. Just implement {@link #buildView} so the adapter can create a new view for this model
* when needed.
* <p>
* {@link #getViewType()} is used by the adapter to know how to reuse views for this model. This
* means that all models that return the same type should be able to share the same view, and the
* view won't be shared with models of any other type.
* <p>
* If it is left unimplemented then at runtime a unique view type will be created to use for all
* models of that class. The generated view type will be negative so that it cannot collide with
* values from resource files, which are used in normal Epoxy models. If you would like to share
* the same view between models of different classes you can have those classes return the same view
* type. A good way to manually create a view type value is by creating an R.id. value in an ids
* resource file.
*/
public abstract class EpoxyModelWithView<T extends View> extends EpoxyModel<T> {
/**
* Get the view type associated with this model's view. Any models with the same view type will
* have views recycled between them.
*
* @see androidx.recyclerview.widget.RecyclerView.Adapter#getItemViewType(int)
*/
@Override
protected int getViewType() {
return 0;
}
/**
* Create and return a new instance of a view for this model. If no layout params are set on the
* returned view then default layout params will be used.
*
* @param parent The parent ViewGroup that the returned view will be added to.
*/
@Override
public abstract T buildView(@NonNull ViewGroup parent);
@Override
protected final int getDefaultLayout() {
throw new UnsupportedOperationException(
"Layout resources are unsupported. Views must be created with `buildView`");
}
@Override
public EpoxyModel<T> layout(@LayoutRes int layoutRes) {
throw new UnsupportedOperationException(
"Layout resources are unsupported. Views must be created with `buildView`");
}
}
| 8,927 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/DiffHelper.java |
package com.airbnb.epoxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
/**
* Helper to track changes in the models list.
*/
class DiffHelper {
private ArrayList<ModelState> oldStateList = new ArrayList<>();
// Using a HashMap instead of a LongSparseArray to
// have faster look up times at the expense of memory
private Map<Long, ModelState> oldStateMap = new HashMap<>();
private ArrayList<ModelState> currentStateList = new ArrayList<>();
private Map<Long, ModelState> currentStateMap = new HashMap<>();
private final BaseEpoxyAdapter adapter;
private final boolean immutableModels;
DiffHelper(BaseEpoxyAdapter adapter, boolean immutableModels) {
this.adapter = adapter;
this.immutableModels = immutableModels;
adapter.registerAdapterDataObserver(observer);
}
private final RecyclerView.AdapterDataObserver observer = new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
throw new UnsupportedOperationException(
"Diffing is enabled. You should use notifyModelsChanged instead of notifyDataSetChanged");
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
for (int i = positionStart; i < positionStart + itemCount; i++) {
currentStateList.get(i).hashCode = adapter.getCurrentModels().get(i).hashCode();
}
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if (itemCount == 0) {
// no-op
return;
}
if (itemCount == 1 || positionStart == currentStateList.size()) {
for (int i = positionStart; i < positionStart + itemCount; i++) {
currentStateList.add(i, createStateForPosition(i));
}
} else {
// Add in a batch since multiple insertions to the middle of the list are slow
List<ModelState> newModels = new ArrayList<>(itemCount);
for (int i = positionStart; i < positionStart + itemCount; i++) {
newModels.add(createStateForPosition(i));
}
currentStateList.addAll(positionStart, newModels);
}
// Update positions of affected items
int size = currentStateList.size();
for (int i = positionStart + itemCount; i < size; i++) {
currentStateList.get(i).position += itemCount;
}
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
if (itemCount == 0) {
// no-op
return;
}
List<ModelState> modelsToRemove =
currentStateList.subList(positionStart, positionStart + itemCount);
for (ModelState model : modelsToRemove) {
currentStateMap.remove(model.id);
}
modelsToRemove.clear();
// Update positions of affected items
int size = currentStateList.size();
for (int i = positionStart; i < size; i++) {
currentStateList.get(i).position -= itemCount;
}
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
if (fromPosition == toPosition) {
// no-op
return;
}
if (itemCount != 1) {
throw new IllegalArgumentException("Moving more than 1 item at a time is not "
+ "supported. Number of items moved: " + itemCount);
}
ModelState model = currentStateList.remove(fromPosition);
model.position = toPosition;
currentStateList.add(toPosition, model);
if (fromPosition < toPosition) {
// shift the affected items left
for (int i = fromPosition; i < toPosition; i++) {
currentStateList.get(i).position--;
}
} else {
// shift the affected items right
for (int i = toPosition + 1; i <= fromPosition; i++) {
currentStateList.get(i).position++;
}
}
}
};
/**
* Set the current list of models. The diff callbacks will be notified of the changes between the
* current list and the last list that was set.
*/
void notifyModelChanges() {
UpdateOpHelper updateOpHelper = new UpdateOpHelper();
buildDiff(updateOpHelper);
// Send out the proper notify calls for the diff. We remove our
// observer first so that we don't react to our own notify calls
adapter.unregisterAdapterDataObserver(observer);
notifyChanges(updateOpHelper);
adapter.registerAdapterDataObserver(observer);
}
private void notifyChanges(UpdateOpHelper opHelper) {
for (UpdateOp op : opHelper.opList) {
switch (op.type) {
case UpdateOp.ADD:
adapter.notifyItemRangeInserted(op.positionStart, op.itemCount);
break;
case UpdateOp.MOVE:
adapter.notifyItemMoved(op.positionStart, op.itemCount);
break;
case UpdateOp.REMOVE:
adapter.notifyItemRangeRemoved(op.positionStart, op.itemCount);
break;
case UpdateOp.UPDATE:
if (immutableModels && op.payloads != null) {
adapter.notifyItemRangeChanged(op.positionStart, op.itemCount,
new DiffPayload(op.payloads));
} else {
adapter.notifyItemRangeChanged(op.positionStart, op.itemCount);
}
break;
default:
throw new IllegalArgumentException("Unknown type: " + op.type);
}
}
}
/**
* Create a list of operations that define the difference between {@link #oldStateList} and {@link
* #currentStateList}.
*/
private UpdateOpHelper buildDiff(UpdateOpHelper updateOpHelper) {
prepareStateForDiff();
// The general approach is to first search for removals, then additions, and lastly changes.
// Focusing on one type of operation at a time makes it easy to coalesce batch changes.
// When we identify an operation and add it to the
// result list we update the positions of items in the oldStateList to reflect
// the change, this way subsequent operations will use the correct, updated positions.
collectRemovals(updateOpHelper);
// Only need to check for insertions if new list is bigger
boolean hasInsertions =
oldStateList.size() - updateOpHelper.getNumRemovals() != currentStateList.size();
if (hasInsertions) {
collectInsertions(updateOpHelper);
}
collectMoves(updateOpHelper);
collectChanges(updateOpHelper);
resetOldState();
return updateOpHelper;
}
private void resetOldState() {
oldStateList.clear();
oldStateMap.clear();
}
private void prepareStateForDiff() {
// We use a list of the models as well as a map by their id,
// so we can easily find them by both position and id
oldStateList.clear();
oldStateMap.clear();
// Swap the two lists so that we have a copy of the current state to calculate the next diff
ArrayList<ModelState> tempList = oldStateList;
oldStateList = currentStateList;
currentStateList = tempList;
Map<Long, ModelState> tempMap = oldStateMap;
oldStateMap = currentStateMap;
currentStateMap = tempMap;
// Remove all pairings in the old states so we can tell which of them were removed. The items
// that still exist in the new list will be paired when we build the current list state below
for (ModelState modelState : oldStateList) {
modelState.pair = null;
}
int modelCount = adapter.getCurrentModels().size();
currentStateList.ensureCapacity(modelCount);
for (int i = 0; i < modelCount; i++) {
currentStateList.add(createStateForPosition(i));
}
}
private ModelState createStateForPosition(int position) {
EpoxyModel<?> model = adapter.getCurrentModels().get(position);
model.addedToAdapter = true;
ModelState state = ModelState.build(model, position, immutableModels);
ModelState previousValue = currentStateMap.put(state.id, state);
if (previousValue != null) {
int previousPosition = previousValue.position;
EpoxyModel<?> previousModel = adapter.getCurrentModels().get(previousPosition);
throw new IllegalStateException("Two models have the same ID. ID's must be unique!"
+ " Model at position " + position + ": " + model
+ " Model at position " + previousPosition + ": " + previousModel);
}
return state;
}
/**
* Find all removal operations and add them to the result list. The general strategy here is to
* walk through the {@link #oldStateList} and check for items that don't exist in the new list.
* Walking through it in order makes it easy to batch adjacent removals.
*/
private void collectRemovals(UpdateOpHelper helper) {
for (ModelState state : oldStateList) {
// Update the position of the item to take into account previous removals,
// so that future operations will reference the correct position
state.position -= helper.getNumRemovals();
// This is our first time going through the list, so we
// look up the item with the matching id in the new
// list and hold a reference to it so that we can access it quickly in the future
state.pair = currentStateMap.get(state.id);
if (state.pair != null) {
state.pair.pair = state;
continue;
}
helper.remove(state.position);
}
}
/**
* Find all insertion operations and add them to the result list. The general strategy here is to
* walk through the {@link #currentStateList} and check for items that don't exist in the old
* list. Walking through it in order makes it easy to batch adjacent insertions.
*/
private void collectInsertions(UpdateOpHelper helper) {
Iterator<ModelState> oldItemIterator = oldStateList.iterator();
for (ModelState itemToInsert : currentStateList) {
if (itemToInsert.pair != null) {
// Update the position of the next item in the old list to take any insertions into account
ModelState nextOldItem = getNextItemWithPair(oldItemIterator);
if (nextOldItem != null) {
nextOldItem.position += helper.getNumInsertions();
}
continue;
}
helper.add(itemToInsert.position);
}
}
/**
* Check if any items have had their values changed, batching if possible.
*/
private void collectChanges(UpdateOpHelper helper) {
for (ModelState newItem : currentStateList) {
ModelState previousItem = newItem.pair;
if (previousItem == null) {
continue;
}
// We use equals when we know the models are immutable and available, otherwise we have to
// rely on the stored hashCode
boolean modelChanged;
if (immutableModels) {
// Make sure that the old model hasn't changed, otherwise comparing it with the new one
// won't be accurate.
if (previousItem.model.isDebugValidationEnabled()) {
previousItem.model
.validateStateHasNotChangedSinceAdded("Model was changed before it could be diffed.",
previousItem.position);
}
modelChanged = !previousItem.model.equals(newItem.model);
} else {
modelChanged = previousItem.hashCode != newItem.hashCode;
}
if (modelChanged) {
helper.update(newItem.position, previousItem.model);
}
}
}
/**
* Check which items have had a position changed. Recyclerview does not support batching these.
*/
private void collectMoves(UpdateOpHelper helper) {
// This walks through both the new and old list simultaneous and checks for position changes.
Iterator<ModelState> oldItemIterator = oldStateList.iterator();
ModelState nextOldItem = null;
for (ModelState newItem : currentStateList) {
if (newItem.pair == null) {
// This item was inserted. However, insertions are done at the item's final position, and
// aren't smart about inserting at a different position to take future moves into account.
// As the old state list is updated to reflect moves, it needs to also consider insertions
// affected by those moves in order for the final change set to be correct
if (helper.moves.isEmpty()) {
// There have been no moves, so the item is still at it's correct position
continue;
} else {
// There have been moves, so the old list needs to take this inserted item
// into account. The old list doesn't have this item inserted into it
// (for optimization purposes), but we can create a pair for this item to
// track its position in the old list and move it back to its final position if necessary
newItem.pairWithSelf();
}
}
// We could iterate through only the new list and move each
// item that is out of place, however in cases such as moving the first item
// to the end, that strategy would do many moves to move all
// items up one instead of doing one move to move the first item to the end.
// To avoid this we compare the old item to the new item at
// each index and move the one that is farthest from its correct position.
// We only move on from a new item once its pair is placed in
// the correct spot. Since we move from start to end, all new items we've
// already iterated through are guaranteed to have their pair
// be already in the right spot, which won't be affected by future MOVEs.
if (nextOldItem == null) {
nextOldItem = getNextItemWithPair(oldItemIterator);
// We've already iterated through all old items and moved each
// item once. However, subsequent moves may have shifted an item out of
// its correct space once it was already moved. We finish
// iterating through all the new items to ensure everything is still correct
if (nextOldItem == null) {
nextOldItem = newItem.pair;
}
}
while (nextOldItem != null) {
// Make sure the positions are updated to the latest
// move operations before we calculate the next move
updateItemPosition(newItem.pair, helper.moves);
updateItemPosition(nextOldItem, helper.moves);
// The item is the same and its already in the correct place
if (newItem.id == nextOldItem.id && newItem.position == nextOldItem.position) {
nextOldItem = null;
break;
}
int newItemDistance = newItem.pair.position - newItem.position;
int oldItemDistance = nextOldItem.pair.position - nextOldItem.position;
// Both items are already in the correct position
if (newItemDistance == 0 && oldItemDistance == 0) {
nextOldItem = null;
break;
}
if (oldItemDistance > newItemDistance) {
helper.move(nextOldItem.position, nextOldItem.pair.position);
nextOldItem.position = nextOldItem.pair.position;
nextOldItem.lastMoveOp = helper.getNumMoves();
nextOldItem = getNextItemWithPair(oldItemIterator);
} else {
helper.move(newItem.pair.position, newItem.position);
newItem.pair.position = newItem.position;
newItem.pair.lastMoveOp = helper.getNumMoves();
break;
}
}
}
}
/**
* Apply the movement operations to the given item to update its position. Only applies the
* operations that have not been applied yet, and stores how many operations have been applied so
* we know which ones to apply next time.
*/
private void updateItemPosition(ModelState item, List<UpdateOp> moveOps) {
int size = moveOps.size();
for (int i = item.lastMoveOp; i < size; i++) {
UpdateOp moveOp = moveOps.get(i);
int fromPosition = moveOp.positionStart;
int toPosition = moveOp.itemCount;
if (item.position > fromPosition && item.position <= toPosition) {
item.position--;
} else if (item.position < fromPosition && item.position >= toPosition) {
item.position++;
}
}
item.lastMoveOp = size;
}
/**
* Gets the next item in the list that has a pair, meaning it wasn't inserted or removed.
*/
@Nullable
private ModelState getNextItemWithPair(Iterator<ModelState> iterator) {
ModelState nextItem = null;
while (nextItem == null && iterator.hasNext()) {
nextItem = iterator.next();
if (nextItem.pair == null) {
// Skip this one and go on to the next
nextItem = null;
}
}
return nextItem;
}
}
| 8,928 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/SimpleEpoxyAdapter.java | package com.airbnb.epoxy;
import java.util.Collection;
import java.util.List;
/**
* A non-abstract version of {@link com.airbnb.epoxy.EpoxyAdapter} that exposes all methods and
* models as public. Use this if you don't want to create your own adapter subclass and instead want
* to modify the adapter from elsewhere, such as from an activity.
*/
public class SimpleEpoxyAdapter extends EpoxyAdapter {
public List<EpoxyModel<?>> getModels() {
return models;
}
@Override
public void enableDiffing() {
super.enableDiffing();
}
@Override
public void notifyModelsChanged() {
super.notifyModelsChanged();
}
@Override
public BoundViewHolders getBoundViewHolders() {
return super.getBoundViewHolders();
}
@Override
public void notifyModelChanged(EpoxyModel<?> model) {
super.notifyModelChanged(model);
}
@Override
public void addModels(EpoxyModel<?>... modelsToAdd) {
super.addModels(modelsToAdd);
}
@Override
public void addModels(Collection<? extends EpoxyModel<?>> modelsToAdd) {
super.addModels(modelsToAdd);
}
@Override
public void insertModelBefore(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertBefore) {
super.insertModelBefore(modelToInsert, modelToInsertBefore);
}
@Override
public void insertModelAfter(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertAfter) {
super.insertModelAfter(modelToInsert, modelToInsertAfter);
}
@Override
public void removeModel(EpoxyModel<?> model) {
super.removeModel(model);
}
@Override
public void removeAllModels() {
super.removeAllModels();
}
@Override
public void removeAllAfterModel(EpoxyModel<?> model) {
super.removeAllAfterModel(model);
}
@Override
public void showModel(EpoxyModel<?> model, boolean show) {
super.showModel(model, show);
}
@Override
public void showModel(EpoxyModel<?> model) {
super.showModel(model);
}
@Override
public void showModels(EpoxyModel<?>... models) {
super.showModels(models);
}
@Override
public void showModels(boolean show, EpoxyModel<?>... models) {
super.showModels(show, models);
}
@Override
public void showModels(Iterable<EpoxyModel<?>> epoxyModels) {
super.showModels(epoxyModels);
}
@Override
public void showModels(Iterable<EpoxyModel<?>> epoxyModels, boolean show) {
super.showModels(epoxyModels, show);
}
@Override
public void hideModel(EpoxyModel<?> model) {
super.hideModel(model);
}
@Override
public void hideModels(Iterable<EpoxyModel<?>> epoxyModels) {
super.hideModels(epoxyModels);
}
@Override
public void hideModels(EpoxyModel<?>... models) {
super.hideModels(models);
}
@Override
public void hideAllAfterModel(EpoxyModel<?> model) {
super.hideAllAfterModel(model);
}
@Override
public List<EpoxyModel<?>> getAllModelsAfter(EpoxyModel<?> model) {
return super.getAllModelsAfter(model);
}
@Override
public int getModelPosition(EpoxyModel<?> model) {
return super.getModelPosition(model);
}
}
| 8,929 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelUnboundListener.java | package com.airbnb.epoxy;
/** Used to register an onUnbind callback with a generated model. */
public interface OnModelUnboundListener<T extends EpoxyModel<?>, V> {
/**
* This will be called immediately after a model is unbound from a view, with the view and model
* that were unbound.
*/
void onModelUnbound(T model, V view);
}
| 8,930 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelVisibilityChangedListener.java | package com.airbnb.epoxy;
import androidx.annotation.FloatRange;
import androidx.annotation.Px;
/** Used to register an onVisibilityChanged callback with a generated model. */
public interface OnModelVisibilityChangedListener<T extends EpoxyModel<V>, V> {
/**
* This will be called once the view visible part changes.
* <p>
* OnModelVisibilityChangedListener should be used with particular care since they will be
* dispatched on every frame while scrolling. No heavy work should be done inside the
* implementation. Using {@link OnModelVisibilityStateChangedListener} is recommended whenever
* possible.
* <p>
* @param model The model being bound
* @param view The view that is being bound to the model
* @param percentVisibleHeight The percentage of height visible (0-100)
* @param percentVisibleWidth The percentage of width visible (0-100)
* @param heightVisible The visible height in pixel
* @param widthVisible The visible width in pixel
*/
void onVisibilityChanged(T model, V view,
@FloatRange(from = 0, to = 100) float percentVisibleHeight,
@FloatRange(from = 0, to = 100) float percentVisibleWidth,
@Px int heightVisible, @Px int widthVisible);
}
| 8,931 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyViewHolder.java | package com.airbnb.epoxy;
import android.view.View;
import android.view.ViewParent;
import com.airbnb.epoxy.ViewHolderState.ViewState;
import com.airbnb.epoxy.VisibilityState.Visibility;
import java.util.List;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.recyclerview.widget.RecyclerView;
@SuppressWarnings("WeakerAccess")
public class EpoxyViewHolder extends RecyclerView.ViewHolder {
@SuppressWarnings("rawtypes") private EpoxyModel epoxyModel;
private List<Object> payloads;
private EpoxyHolder epoxyHolder;
@Nullable ViewHolderState.ViewState initialViewState;
// Once the EpoxyHolder is created parent will be set to null.
private ViewParent parent;
public EpoxyViewHolder(ViewParent parent, View view, boolean saveInitialState) {
super(view);
this.parent = parent;
if (saveInitialState) {
// We save the initial state of the view when it is created so that we can reset this initial
// state before a model is bound for the first time. Otherwise the view may carry over
// state from a previously bound model.
initialViewState = new ViewState();
initialViewState.save(itemView);
}
}
void restoreInitialViewState() {
if (initialViewState != null) {
initialViewState.restore(itemView);
}
}
public void bind(@SuppressWarnings("rawtypes") EpoxyModel model,
@Nullable EpoxyModel<?> previouslyBoundModel, List<Object> payloads, int position) {
this.payloads = payloads;
if (epoxyHolder == null && model instanceof EpoxyModelWithHolder) {
epoxyHolder = ((EpoxyModelWithHolder) model).createNewHolder(parent);
epoxyHolder.bindView(itemView);
}
// Safe to set to null as it is only used for createNewHolder method
parent = null;
if (model instanceof GeneratedModel) {
// The generated method will enforce that only a properly typed listener can be set
//noinspection unchecked
((GeneratedModel) model).handlePreBind(this, objectToBind(), position);
}
// noinspection unchecked
model.preBind(objectToBind(), previouslyBoundModel);
if (previouslyBoundModel != null) {
// noinspection unchecked
model.bind(objectToBind(), previouslyBoundModel);
} else if (payloads.isEmpty()) {
// noinspection unchecked
model.bind(objectToBind());
} else {
// noinspection unchecked
model.bind(objectToBind(), payloads);
}
if (model instanceof GeneratedModel) {
// The generated method will enforce that only a properly typed listener can be set
//noinspection unchecked
((GeneratedModel) model).handlePostBind(objectToBind(), position);
}
epoxyModel = model;
}
@NonNull
Object objectToBind() {
return epoxyHolder != null ? epoxyHolder : itemView;
}
public void unbind() {
assertBound();
// noinspection unchecked
epoxyModel.unbind(objectToBind());
epoxyModel = null;
payloads = null;
}
public void visibilityStateChanged(@Visibility int visibilityState) {
assertBound();
// noinspection unchecked
epoxyModel.onVisibilityStateChanged(visibilityState, objectToBind());
}
public void visibilityChanged(
@FloatRange(from = 0.0f, to = 100.0f) float percentVisibleHeight,
@FloatRange(from = 0.0f, to = 100.0f) float percentVisibleWidth,
@Px int visibleHeight,
@Px int visibleWidth
) {
assertBound();
// noinspection unchecked
epoxyModel.onVisibilityChanged(percentVisibleHeight, percentVisibleWidth, visibleHeight,
visibleWidth, objectToBind());
}
public List<Object> getPayloads() {
assertBound();
return payloads;
}
public EpoxyModel<?> getModel() {
assertBound();
return epoxyModel;
}
public EpoxyHolder getHolder() {
assertBound();
return epoxyHolder;
}
private void assertBound() {
if (epoxyModel == null) {
throw new IllegalStateException("This holder is not currently bound.");
}
}
@Override
public String toString() {
return "EpoxyViewHolder{"
+ "epoxyModel=" + epoxyModel
+ ", view=" + itemView
+ ", super=" + super.toString()
+ '}';
}
}
| 8,932 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/Typed4EpoxyController.java | package com.airbnb.epoxy;
import android.os.Handler;
/**
* This is a wrapper around {@link com.airbnb.epoxy.EpoxyController} to simplify how data is
* accessed. Use this if the data required to build your models is represented by four objects.
* <p>
* To use this, create a subclass typed with your data object. Then, call {@link #setData}
* whenever that data changes. This class will handle calling {@link #buildModels} with the
* latest data.
* <p>
* You should NOT call {@link #requestModelBuild()} directly.
*
* @see TypedEpoxyController
* @see Typed2EpoxyController
* @see Typed3EpoxyController
*/
public abstract class Typed4EpoxyController<T, U, V, W> extends EpoxyController {
private T data1;
private U data2;
private V data3;
private W data4;
private boolean allowModelBuildRequests;
public Typed4EpoxyController() {
}
public Typed4EpoxyController(Handler modelBuildingHandler, Handler diffingHandler) {
super(modelBuildingHandler, diffingHandler);
}
/**
* Call this with the latest data when you want models to be rebuilt. The data will be passed on
* to {@link #buildModels(Object, Object, Object, Object)}
*/
public void setData(T data1, U data2, V data3, W data4) {
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
this.data4 = data4;
allowModelBuildRequests = true;
requestModelBuild();
allowModelBuildRequests = false;
}
@Override
public final void requestModelBuild() {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestModelBuild();
}
@Override
public void moveModel(int fromPosition, int toPosition) {
allowModelBuildRequests = true;
super.moveModel(fromPosition, toPosition);
allowModelBuildRequests = false;
}
@Override
public void requestDelayedModelBuild(int delayMs) {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestDelayedModelBuild(delayMs);
}
@Override
protected final void buildModels() {
if (!isBuildingModels()) {
throw new IllegalStateException(
"You cannot call `buildModels` directly. Call `setData` instead to trigger a model "
+ "refresh with new data.");
}
buildModels(data1, data2, data3, data4);
}
protected abstract void buildModels(T data1, U data2, V data3, W data4);
}
| 8,933 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyDragCallback.java | package com.airbnb.epoxy;
import android.view.View;
/**
* For use with {@link EpoxyModelTouchCallback}
*/
public interface EpoxyDragCallback<T extends EpoxyModel> extends BaseEpoxyTouchCallback<T> {
/**
* Called when the view switches from an idle state to a dragged state, as the user begins a drag
* interaction with it. You can use this callback to modify the view to indicate it is being
* dragged.
* <p>
* This is the first callback in the lifecycle of a drag event.
*
* @param model The model representing the view that is being dragged
* @param itemView The view that is being dragged
* @param adapterPosition The adapter position of the model
*/
void onDragStarted(T model, View itemView, int adapterPosition);
/**
* Called after {@link #onDragStarted(EpoxyModel, View, int)} when the dragged view is dropped to
* a new position. The EpoxyController will be updated automatically for you to reposition the
* models and notify the RecyclerView of the change.
* <p>
* You MUST use this callback to modify your data backing the models to reflect the change.
* <p>
* The next callback in the drag lifecycle will be {@link #onDragStarted(EpoxyModel, View, int)}
*
* @param modelBeingMoved The model representing the view that was moved
* @param itemView The view that was moved
* @param fromPosition The adapter position that the model came from
* @param toPosition The new adapter position of the model
*/
void onModelMoved(int fromPosition, int toPosition, T modelBeingMoved, View itemView);
/**
* Called after {@link #onDragStarted(EpoxyModel, View, int)} when the view being dragged is
* released. If the view was dragged to a new, valid location then {@link #onModelMoved(int, int,
* EpoxyModel, View)} will be called before this and the view will settle to the new location.
* Otherwise the view will animate back to its original position.
* <p>
* You can use this callback to modify the view as it animates back into position.
* <p>
* {@link BaseEpoxyTouchCallback#clearView(EpoxyModel, View)} will be called after this, when the
* view has finished animating. Final cleanup of the view should be done there.
*
* @param model The model representing the view that is being released
* @param itemView The view that was being dragged
*/
void onDragReleased(T model, View itemView);
}
| 8,934 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/NoOpTimer.java | package com.airbnb.epoxy;
class NoOpTimer implements Timer {
@Override
public void start(String sectionName) {
}
@Override
public void stop() {
}
}
| 8,935 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyModelTouchCallback.java | package com.airbnb.epoxy;
import android.graphics.Canvas;
import android.view.View;
import com.airbnb.viewmodeladapter.R;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
/**
* A wrapper around {@link androidx.recyclerview.widget.ItemTouchHelper.Callback} to enable
* easier touch support when working with Epoxy models.
* <p>
* For simplicity you can use {@link EpoxyTouchHelper} to set up touch handling via this class for
* you instead of using this class directly. However, you may choose to use this class directly with
* your own {@link ItemTouchHelper} if you need extra flexibility or customization.
*/
public abstract class EpoxyModelTouchCallback<T extends EpoxyModel>
extends EpoxyTouchHelperCallback implements EpoxyDragCallback<T>, EpoxySwipeCallback<T> {
private static final int TOUCH_DEBOUNCE_MILLIS = 300;
@Nullable private final EpoxyController controller;
private final Class<T> targetModelClass;
private EpoxyViewHolder holderBeingDragged;
private EpoxyViewHolder holderBeingSwiped;
public EpoxyModelTouchCallback(@Nullable EpoxyController controller, Class<T> targetModelClass) {
this.controller = controller;
this.targetModelClass = targetModelClass;
}
@Override
protected int getMovementFlags(RecyclerView recyclerView, EpoxyViewHolder viewHolder) {
EpoxyModel<?> model = viewHolder.getModel();
// If multiple touch callbacks are registered on the recyclerview (to support combinations of
// dragging and dropping) then we won't want to enable anything if another
// callback has a view actively selected.
boolean isOtherCallbackActive =
holderBeingDragged == null
&& holderBeingSwiped == null
&& recyclerViewHasSelection(recyclerView);
if (!isOtherCallbackActive && isTouchableModel(model)) {
//noinspection unchecked
return getMovementFlagsForModel((T) model, viewHolder.getAdapterPosition());
} else {
return 0;
}
}
@Override
protected boolean canDropOver(RecyclerView recyclerView, EpoxyViewHolder current,
EpoxyViewHolder target) {
// By default we don't allow dropping on a model that isn't a drag target
return isTouchableModel(target.getModel());
}
protected boolean isTouchableModel(EpoxyModel<?> model) {
return targetModelClass.isInstance(model);
}
@Override
protected boolean onMove(RecyclerView recyclerView, EpoxyViewHolder viewHolder,
EpoxyViewHolder target) {
if (controller == null) {
throw new IllegalStateException(
"A controller must be provided in the constructor if dragging is enabled");
}
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
controller.moveModel(fromPosition, toPosition);
EpoxyModel<?> model = viewHolder.getModel();
if (!isTouchableModel(model)) {
throw new IllegalStateException(
"A model was dragged that is not a valid target: " + model.getClass());
}
//noinspection unchecked
onModelMoved(fromPosition, toPosition, (T) model, viewHolder.itemView);
return true;
}
@Override
public void onModelMoved(int fromPosition, int toPosition, T modelBeingMoved, View itemView) {
}
@Override
protected void onSwiped(EpoxyViewHolder viewHolder, int direction) {
EpoxyModel<?> model = viewHolder.getModel();
View view = viewHolder.itemView;
int position = viewHolder.getAdapterPosition();
if (!isTouchableModel(model)) {
throw new IllegalStateException(
"A model was swiped that is not a valid target: " + model.getClass());
}
//noinspection unchecked
onSwipeCompleted((T) model, view, position, direction);
}
@Override
public void onSwipeCompleted(T model, View itemView, int position, int direction) {
}
@Override
protected void onSelectedChanged(@Nullable EpoxyViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
if (viewHolder != null) {
EpoxyModel<?> model = viewHolder.getModel();
if (!isTouchableModel(model)) {
throw new IllegalStateException(
"A model was selected that is not a valid target: " + model.getClass());
}
markRecyclerViewHasSelection((RecyclerView) viewHolder.itemView.getParent());
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
holderBeingSwiped = viewHolder;
//noinspection unchecked
onSwipeStarted((T) model, viewHolder.itemView, viewHolder.getAdapterPosition());
} else if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
holderBeingDragged = viewHolder;
//noinspection unchecked
onDragStarted((T) model, viewHolder.itemView, viewHolder.getAdapterPosition());
}
} else if (holderBeingDragged != null) {
//noinspection unchecked
onDragReleased((T) holderBeingDragged.getModel(), holderBeingDragged.itemView);
holderBeingDragged = null;
} else if (holderBeingSwiped != null) {
//noinspection unchecked
onSwipeReleased((T) holderBeingSwiped.getModel(), holderBeingSwiped.itemView);
holderBeingSwiped = null;
}
}
private void markRecyclerViewHasSelection(RecyclerView recyclerView) {
recyclerView.setTag(R.id.epoxy_touch_helper_selection_status, Boolean.TRUE);
}
private boolean recyclerViewHasSelection(RecyclerView recyclerView) {
return recyclerView.getTag(R.id.epoxy_touch_helper_selection_status) != null;
}
private void clearRecyclerViewSelectionMarker(RecyclerView recyclerView) {
recyclerView.setTag(R.id.epoxy_touch_helper_selection_status, null);
}
@Override
public void onSwipeStarted(T model, View itemView, int adapterPosition) {
}
@Override
public void onSwipeReleased(T model, View itemView) {
}
@Override
public void onDragStarted(T model, View itemView, int adapterPosition) {
}
@Override
public void onDragReleased(T model, View itemView) {
}
@Override
protected void clearView(final RecyclerView recyclerView, EpoxyViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
//noinspection unchecked
clearView((T) viewHolder.getModel(), viewHolder.itemView);
// If multiple touch helpers are in use, one touch helper can pick up buffered touch inputs
// immediately after another touch event finishes. This leads to things like a view being
// selected for drag when another view finishes its swipe off animation. To prevent that we
// keep the recyclerview marked as having an active selection for a brief period after a
// touch event ends.
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
clearRecyclerViewSelectionMarker(recyclerView);
}
}, TOUCH_DEBOUNCE_MILLIS);
}
@Override
public void clearView(T model, View itemView) {
}
@Override
protected void onChildDraw(Canvas c, RecyclerView recyclerView, EpoxyViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
EpoxyModel<?> model;
// It’s possible for a touch helper to still draw if the item is being removed, which means it
// has technically be unbound by that point. getModel will throw an exception in this case.
try {
model = viewHolder.getModel();
} catch (IllegalStateException ignored) {
return;
}
if (!isTouchableModel(model)) {
throw new IllegalStateException(
"A model was selected that is not a valid target: " + model.getClass());
}
View itemView = viewHolder.itemView;
float swipeProgress;
if (Math.abs(dX) > Math.abs(dY)) {
swipeProgress = dX / itemView.getWidth();
} else {
swipeProgress = dY / itemView.getHeight();
}
// Clamp to 1/-1 in the case of side padding where the view can be swiped extra
float clampedProgress = Math.max(-1f, Math.min(1f, swipeProgress));
//noinspection unchecked
onSwipeProgressChanged((T) model, itemView, clampedProgress, c);
}
@Override
public void onSwipeProgressChanged(T model, View itemView, float swipeProgress,
Canvas canvas) {
}
}
| 8,936 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/Timer.java | package com.airbnb.epoxy;
interface Timer {
void start(String sectionName);
void stop();
}
| 8,937 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyController.java | package com.airbnb.epoxy;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import com.airbnb.epoxy.stickyheader.StickyHeaderCallbacks;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup;
import static com.airbnb.epoxy.ControllerHelperLookup.getHelperForController;
/**
* A controller for easily combining {@link EpoxyModel} instances in a {@link RecyclerView.Adapter}.
* Simply implement {@link #buildModels()} to declare which models should be used, and in which
* order. Call {@link #requestModelBuild()} whenever your data changes, and the controller will call
* {@link #buildModels()}, update the adapter with the new models, and notify any changes between
* the new and old models.
* <p>
* The controller maintains a {@link androidx.recyclerview.widget.RecyclerView.Adapter} with the
* latest models, which you can get via {@link #getAdapter()} to set on your RecyclerView.
* <p>
* All data change notifications are applied automatically via Epoxy's diffing algorithm. All of
* your models must have a unique id set on them for diffing to work. You may choose to use {@link
* AutoModel} annotations to have the controller create models with unique ids for you
* automatically.
* <p>
* Once a model is created and added to the controller in {@link #buildModels()} it should be
* treated as immutable and never modified again. This is necessary for adapter updates to be
* accurate.
*/
public abstract class EpoxyController implements ModelCollector, StickyHeaderCallbacks {
/**
* We check that the adapter is not connected to multiple recyclerviews, but when a fragment has
* its view quickly destroyed and recreated it may temporarily attach the same adapter to the
* previous view and the new view (eg because of fragment transitions) if the controller is reused
* across views. We want to allow this case since it is a brief transient state. This should be
* enough time for screen transitions to happen.
*/
private static final int DELAY_TO_CHECK_ADAPTER_COUNT_MS = 3000;
private static final Timer NO_OP_TIMER = new NoOpTimer();
public static Handler defaultModelBuildingHandler = MainThreadExecutor.INSTANCE.handler;
public static Handler defaultDiffingHandler = MainThreadExecutor.INSTANCE.handler;
private static boolean filterDuplicatesDefault = false;
private static boolean globalDebugLoggingEnabled = false;
private final EpoxyControllerAdapter adapter;
private EpoxyDiffLogger debugObserver;
private int recyclerViewAttachCount = 0;
private final Handler modelBuildHandler;
/**
* This is iterated over in the build models thread, but items can be inserted or removed from
* other threads at any time.
*/
private final List<Interceptor> interceptors = new CopyOnWriteArrayList<>();
// Volatile because -> write only on main thread, read from builder thread
private volatile boolean filterDuplicates = filterDuplicatesDefault;
/**
* This is used to track whether we are currently building models. If it is non null it means
* a thread is in the building models method. We store the thread so we can know which one
* is building models.
* <p>
* Volatile because -> write only on handler, read from any thread
*/
private volatile Thread threadBuildingModels = null;
/**
* Used to know that we should build models synchronously the first time.
* <p>
* Volatile because -> written from the build models thread, read from the main thread.
*/
private volatile boolean hasBuiltModelsEver;
//////////////////////////////////////////////////////////////////////////////////////////
/*
* These fields are expected to only be used on the model building thread so they are not
* synchronized.
*/
/** Used to time operations and log their duration when in debug mode. */
private Timer timer = NO_OP_TIMER;
private final ControllerHelper helper = getHelperForController(this);
private ControllerModelList modelsBeingBuilt;
private List<ModelInterceptorCallback> modelInterceptorCallbacks;
private EpoxyModel<?> stagedModel;
//////////////////////////////////////////////////////////////////////////////////////////
public EpoxyController() {
this(defaultModelBuildingHandler, defaultDiffingHandler);
}
public EpoxyController(Handler modelBuildingHandler, Handler diffingHandler) {
adapter = new EpoxyControllerAdapter(this, diffingHandler);
modelBuildHandler = modelBuildingHandler;
setDebugLoggingEnabled(globalDebugLoggingEnabled);
}
/**
* Posting and canceling runnables is a bit expensive - it is synchronizes and iterates the
* list of runnables. We want clients to be able to request model builds as often as they want and
* have it act as a no-op if one is already requested, without being a performance hit. To do that
* we track whether we have a call to build models posted already so we can avoid canceling a
* current call and posting it again.
*/
@RequestedModelBuildType private volatile int requestedModelBuildType =
RequestedModelBuildType.NONE;
@Retention(RetentionPolicy.SOURCE)
@IntDef({RequestedModelBuildType.NONE,
RequestedModelBuildType.NEXT_FRAME,
RequestedModelBuildType.DELAYED})
private @interface RequestedModelBuildType {
int NONE = 0;
/** A request has been made to build models immediately. It is posted. */
int NEXT_FRAME = 1;
/** A request has been made to build models after a delay. It is post delayed. */
int DELAYED = 2;
}
/**
* Call this to request a model update. The controller will schedule a call to {@link
* #buildModels()} so that models can be rebuilt for the current data. Once a build is requested
* all subsequent requests are ignored until the model build runs. Therefore, the calling code
* need not worry about calling this multiple times in a row.
* <p>
* The exception is that the first time this is called on a new instance of {@link
* EpoxyController} it is run synchronously. This allows state to be restored and the initial view
* to be draw quicker.
* <p>
* If you would like to be alerted when models have finished building use
* {@link #addModelBuildListener(OnModelBuildFinishedListener)}
*/
public void requestModelBuild() {
if (isBuildingModels()) {
throw new IllegalEpoxyUsage("Cannot call `requestModelBuild` from inside `buildModels`");
}
// If it is the first time building models then we do it right away, otherwise we post the call.
// We want to do it right away the first time so that scroll position can be restored correctly,
// shared element transitions aren't delayed, and content is shown asap. We post later calls
// so that they are debounced, and so any updates to data can be completely finished before
// the models are built.
if (hasBuiltModelsEver) {
requestDelayedModelBuild(0);
} else {
buildModelsRunnable.run();
}
}
/**
* Whether an update to models is currently pending. This can either be because
* {@link #requestModelBuild()} was called, or because models are currently being built or diff
* on a background thread.
*/
public boolean hasPendingModelBuild() {
return requestedModelBuildType != RequestedModelBuildType.NONE // model build is posted
|| threadBuildingModels != null // model build is in progress
|| adapter.isDiffInProgress(); // Diff in progress
}
/**
* Add a listener that will be called every time {@link #buildModels()} has finished running
* and changes have been dispatched to the RecyclerView.
* <p>
* Since buildModels can be called once for many calls to {@link #requestModelBuild()}, this is
* called just once for each buildModels execution, not for every request.
* <p>
* Use this to react to changes in your models that need to happen after the RecyclerView has
* been notified, such as scrolling.
*/
public void addModelBuildListener(OnModelBuildFinishedListener listener) {
adapter.addModelBuildListener(listener);
}
/**
* Remove a listener added with {@link #addModelBuildListener(OnModelBuildFinishedListener)}.
* This is safe to call from inside the callback
* {@link OnModelBuildFinishedListener#onModelBuildFinished(DiffResult)}
*/
public void removeModelBuildListener(OnModelBuildFinishedListener listener) {
adapter.removeModelBuildListener(listener);
}
/**
* Call this to request a delayed model update. The controller will schedule a call to {@link
* #buildModels()} so that models can be rebuilt for the current data.
* <p>
* Using this to delay a model update may be helpful in cases where user input is causing many
* rapid changes in the models, such as typing. In that case, the view is already updated on
* screen and constantly rebuilding models is potentially slow and unnecessary. The downside to
* delaying the model build too long is that models will not be in sync with the data or view, and
* scrolling the view offscreen and back onscreen will cause the model to bind old data.
* <p>
* If a previous request is still pending it will be removed in favor of this new delay
* <p>
* Any call to {@link #requestModelBuild()} will override a delayed request.
* <p>
* In most cases you should use {@link #requestModelBuild()} instead of this.
*
* @param delayMs The time in milliseconds to delay the model build by. Should be greater than or
* equal to 0. A value of 0 is equivalent to calling {@link #requestModelBuild()}
*/
public synchronized void requestDelayedModelBuild(int delayMs) {
if (isBuildingModels()) {
throw new IllegalEpoxyUsage(
"Cannot call `requestDelayedModelBuild` from inside `buildModels`");
}
if (requestedModelBuildType == RequestedModelBuildType.DELAYED) {
cancelPendingModelBuild();
} else if (requestedModelBuildType == RequestedModelBuildType.NEXT_FRAME) {
return;
}
requestedModelBuildType =
delayMs == 0 ? RequestedModelBuildType.NEXT_FRAME : RequestedModelBuildType.DELAYED;
modelBuildHandler.postDelayed(buildModelsRunnable, delayMs);
}
/**
* Cancels a pending call to {@link #buildModels()} if one has been queued by {@link
* #requestModelBuild()}.
*/
public synchronized void cancelPendingModelBuild() {
// Access to requestedModelBuildType is synchronized because the model building thread clears
// it when model building starts, and the main thread needs to set it to indicate a build
// request.
// Additionally, it is crucial to guarantee that the state of requestedModelBuildType is in sync
// with the modelBuildHandler, otherwise we could end up in a state where we think a model build
// is queued, but it isn't, and model building never happens - stuck forever.
if (requestedModelBuildType != RequestedModelBuildType.NONE) {
requestedModelBuildType = RequestedModelBuildType.NONE;
modelBuildHandler.removeCallbacks(buildModelsRunnable);
}
}
private final Runnable buildModelsRunnable = new Runnable() {
@Override
public void run() {
// Do this first to mark the controller as being in the model building process.
threadBuildingModels = Thread.currentThread();
// This is needed to reset the requestedModelBuildType back to NONE.
// As soon as we do this another model build can be posted.
cancelPendingModelBuild();
helper.resetAutoModels();
modelsBeingBuilt = new ControllerModelList(getExpectedModelCount());
timer.start("Models built");
// The user's implementation of buildModels is wrapped in a try/catch so that if it fails
// we can reset the state of this controller. This is useful when model building is done
// on a dedicated thread, which may have its own error handler, and a failure may not
// crash the app - in which case this controller would be in an invalid state and crash later
// with confusing errors because "threadBuildingModels" and other properties are not
// correctly set. This can happen particularly with Espresso testing.
try {
buildModels();
} catch (Throwable throwable) {
timer.stop();
modelsBeingBuilt = null;
hasBuiltModelsEver = true;
threadBuildingModels = null;
stagedModel = null;
throw throwable;
}
addCurrentlyStagedModelIfExists();
timer.stop();
runInterceptors();
filterDuplicatesIfNeeded(modelsBeingBuilt);
modelsBeingBuilt.freeze();
timer.start("Models diffed");
adapter.setModels(modelsBeingBuilt);
// This timing is only right if diffing and model building are on the same thread
timer.stop();
modelsBeingBuilt = null;
hasBuiltModelsEver = true;
threadBuildingModels = null;
}
};
/** An estimate for how many models will be built in the next {@link #buildModels()} phase. */
private int getExpectedModelCount() {
int currentModelCount = adapter.getItemCount();
return currentModelCount != 0 ? currentModelCount : 25;
}
/**
* Subclasses should implement this to describe what models should be shown for the current state.
* Implementations should call either {@link #add(EpoxyModel)}, {@link
* EpoxyModel#addTo(EpoxyController)}, or {@link EpoxyModel#addIf(boolean, EpoxyController)} with
* the models that should be shown, in the order that is desired.
* <p>
* Once a model is added to the controller it should be treated as immutable and never modified
* again. This is necessary for adapter updates to be accurate. If "validateEpoxyModelUsage" is
* enabled then runtime validations will be done to make sure models are not changed.
* <p>
* You CANNOT call this method directly. Instead, call {@link #requestModelBuild()} to have the
* controller schedule an update.
*/
protected abstract void buildModels();
int getFirstIndexOfModelInBuildingList(EpoxyModel<?> model) {
assertIsBuildingModels();
int size = modelsBeingBuilt.size();
for (int i = 0; i < size; i++) {
if (modelsBeingBuilt.get(i) == model) {
return i;
}
}
return -1;
}
boolean isModelAddedMultipleTimes(EpoxyModel<?> model) {
assertIsBuildingModels();
int modelCount = 0;
int size = modelsBeingBuilt.size();
for (int i = 0; i < size; i++) {
if (modelsBeingBuilt.get(i) == model) {
modelCount++;
}
}
return modelCount > 1;
}
void addAfterInterceptorCallback(ModelInterceptorCallback callback) {
assertIsBuildingModels();
if (modelInterceptorCallbacks == null) {
modelInterceptorCallbacks = new ArrayList<>();
}
modelInterceptorCallbacks.add(callback);
}
/**
* Callbacks to each model for when interceptors are started and stopped, so the models know when
* to allow changes.
*/
interface ModelInterceptorCallback {
void onInterceptorsStarted(EpoxyController controller);
void onInterceptorsFinished(EpoxyController controller);
}
private void runInterceptors() {
if (!interceptors.isEmpty()) {
if (modelInterceptorCallbacks != null) {
for (ModelInterceptorCallback callback : modelInterceptorCallbacks) {
callback.onInterceptorsStarted(this);
}
}
timer.start("Interceptors executed");
for (Interceptor interceptor : interceptors) {
interceptor.intercept(modelsBeingBuilt);
}
timer.stop();
if (modelInterceptorCallbacks != null) {
for (ModelInterceptorCallback callback : modelInterceptorCallbacks) {
callback.onInterceptorsFinished(this);
}
}
}
// Interceptors are cleared so that future model builds don't notify past models.
// We need to make sure they are cleared even if there are no interceptors so that
// we don't leak the models.
modelInterceptorCallbacks = null;
}
/** A callback that is run after {@link #buildModels()} completes and before diffing is run. */
public interface Interceptor {
/**
* This is called immediately after {@link #buildModels()} and before diffing is run and the
* models are set on the adapter. This is a final chance to make any changes to the the models
* added in {@link #buildModels()}. This may be useful for actions that act on all models in
* aggregate, such as toggling divider settings, or for cases such as rearranging models for an
* experiment.
* <p>
* The models list must not be changed after this method returns. Doing so will throw an
* exception.
*/
void intercept(@NonNull List<EpoxyModel<?>> models);
}
/**
* Add an interceptor callback to be run after models are built, to make any last changes before
* they are set on the adapter. Interceptors are run in the order they are added.
* <p>
* Interceptors are run on the same thread that models are built on.
*
* @see Interceptor#intercept(List)
*/
public void addInterceptor(@NonNull Interceptor interceptor) {
interceptors.add(interceptor);
}
/** Remove an interceptor that was added with {@link #addInterceptor(Interceptor)}. */
public void removeInterceptor(@NonNull Interceptor interceptor) {
interceptors.remove(interceptor);
}
/**
* Get the number of models added so far during the {@link #buildModels()} phase. It is only valid
* to call this from within that method.
* <p>
* This is different from the number of models currently on the adapter, since models on the
* adapter are not updated until after models are finished being built. To access current adapter
* count call {@link #getAdapter()} and {@link EpoxyControllerAdapter#getItemCount()}
*/
protected int getModelCountBuiltSoFar() {
assertIsBuildingModels();
return modelsBeingBuilt.size();
}
private void assertIsBuildingModels() {
if (!isBuildingModels()) {
throw new IllegalEpoxyUsage("Can only call this when inside the `buildModels` method");
}
}
private void assertNotBuildingModels() {
if (isBuildingModels()) {
throw new IllegalEpoxyUsage("Cannot call this from inside `buildModels`");
}
}
/**
* Add the model to this controller. Can only be called from inside {@link
* EpoxyController#buildModels()}.
*/
public void add(@NonNull EpoxyModel<?> model) {
model.addTo(this);
}
/**
* Add the models to this controller. Can only be called from inside {@link
* EpoxyController#buildModels()}.
*/
protected void add(@NonNull EpoxyModel<?>... modelsToAdd) {
modelsBeingBuilt.ensureCapacity(modelsBeingBuilt.size() + modelsToAdd.length);
for (EpoxyModel<?> model : modelsToAdd) {
add(model);
}
}
/**
* Add the models to this controller. Can only be called from inside {@link
* EpoxyController#buildModels()}.
*/
protected void add(@NonNull List<? extends EpoxyModel<?>> modelsToAdd) {
modelsBeingBuilt.ensureCapacity(modelsBeingBuilt.size() + modelsToAdd.size());
for (EpoxyModel<?> model : modelsToAdd) {
add(model);
}
}
/**
* Method to actually add the model to the list being built. Should be called after all
* validations are done.
*/
void addInternal(EpoxyModel<?> modelToAdd) {
assertIsBuildingModels();
if (modelToAdd.hasDefaultId()) {
throw new IllegalEpoxyUsage(
"You must set an id on a model before adding it. Use the @AutoModel annotation if you "
+ "want an id to be automatically generated for you.");
}
if (!modelToAdd.isShown()) {
throw new IllegalEpoxyUsage(
"You cannot hide a model in an EpoxyController. Use `addIf` to conditionally add a "
+ "model instead.");
}
// The model being added may not have been staged if it wasn't mutated before it was added.
// In that case we may have a previously staged model that still needs to be added.
clearModelFromStaging(modelToAdd);
modelToAdd.controllerToStageTo = null;
modelsBeingBuilt.add(modelToAdd);
}
/**
* Staging models allows them to be implicitly added after the user finishes modifying them. This
* means that if a user has modified a model, and then moves on to modifying a different model,
* the first model is automatically added as soon as the second model is modified.
* <p>
* There are some edge cases for handling models that are added without modification, or models
* that are modified but then fail an `addIf` check.
* <p>
* This only works for AutoModels, and only if implicitly adding is enabled in configuration.
*/
void setStagedModel(EpoxyModel<?> model) {
if (model != stagedModel) {
addCurrentlyStagedModelIfExists();
}
stagedModel = model;
}
void addCurrentlyStagedModelIfExists() {
if (stagedModel != null) {
stagedModel.addTo(this);
}
stagedModel = null;
}
void clearModelFromStaging(EpoxyModel<?> model) {
if (stagedModel != model) {
addCurrentlyStagedModelIfExists();
}
stagedModel = null;
}
/** True if the current callstack originated from the buildModels call, on the same thread. */
protected boolean isBuildingModels() {
return threadBuildingModels == Thread.currentThread();
}
private void filterDuplicatesIfNeeded(List<EpoxyModel<?>> models) {
if (!filterDuplicates) {
return;
}
timer.start("Duplicates filtered");
Set<Long> modelIds = new HashSet<>(models.size());
ListIterator<EpoxyModel<?>> modelIterator = models.listIterator();
while (modelIterator.hasNext()) {
EpoxyModel<?> model = modelIterator.next();
if (!modelIds.add(model.id())) {
int indexOfDuplicate = modelIterator.previousIndex();
modelIterator.remove();
int indexOfOriginal = findPositionOfDuplicate(models, model);
EpoxyModel<?> originalModel = models.get(indexOfOriginal);
if (indexOfDuplicate <= indexOfOriginal) {
// Adjust for the original positions of the models before the duplicate was removed
indexOfOriginal++;
}
onExceptionSwallowed(
new IllegalEpoxyUsage("Two models have the same ID. ID's must be unique!"
+ "\nOriginal has position " + indexOfOriginal + ":\n" + originalModel
+ "\nDuplicate has position " + indexOfDuplicate + ":\n" + model)
);
}
}
timer.stop();
}
private int findPositionOfDuplicate(List<EpoxyModel<?>> models, EpoxyModel<?> duplicateModel) {
int size = models.size();
for (int i = 0; i < size; i++) {
EpoxyModel<?> model = models.get(i);
if (model.id() == duplicateModel.id()) {
return i;
}
}
throw new IllegalArgumentException("No duplicates in list");
}
/**
* If set to true, Epoxy will search for models with duplicate ids added during {@link
* #buildModels()} and remove any duplicates found. If models with the same id are found, the
* first one is left in the adapter and any subsequent models are removed. {@link
* #onExceptionSwallowed(RuntimeException)} will be called for each duplicate removed.
* <p>
* This may be useful if your models are created via server supplied data, in which case the
* server may erroneously send duplicate items. Duplicate items are otherwise left in and can
* result in undefined behavior.
*/
public void setFilterDuplicates(boolean filterDuplicates) {
this.filterDuplicates = filterDuplicates;
}
public boolean isDuplicateFilteringEnabled() {
return filterDuplicates;
}
/**
* {@link #setFilterDuplicates(boolean)} is disabled in each EpoxyController by default. It can be
* toggled individually in each controller, or alternatively you can use this to change the
* default value for all EpoxyControllers.
*/
public static void setGlobalDuplicateFilteringDefault(boolean filterDuplicatesByDefault) {
EpoxyController.filterDuplicatesDefault = filterDuplicatesByDefault;
}
/**
* If enabled, DEBUG logcat messages will be printed to show when models are rebuilt, the time
* taken to build them, the time taken to diff them, and the item change outcomes from the
* differ. The tag of the logcat message is the class name of your EpoxyController.
* <p>
* This is useful to verify that models are being diffed as expected, as well as to watch for
* slowdowns in model building or diffing to indicate when you should optimize model building or
* model hashCode/equals implementations (which can often slow down diffing).
* <p>
* This should only be used in debug builds to avoid a performance hit in prod.
*/
public void setDebugLoggingEnabled(boolean enabled) {
assertNotBuildingModels();
if (enabled) {
timer = new DebugTimer(getClass().getSimpleName());
if (debugObserver == null) {
debugObserver = new EpoxyDiffLogger(getClass().getSimpleName());
}
adapter.registerAdapterDataObserver(debugObserver);
} else {
timer = NO_OP_TIMER;
if (debugObserver != null) {
adapter.unregisterAdapterDataObserver(debugObserver);
}
}
}
public boolean isDebugLoggingEnabled() {
return timer != NO_OP_TIMER;
}
/**
* Similar to {@link #setDebugLoggingEnabled(boolean)}, but this changes the global default for
* all EpoxyControllers.
* <p>
* The default is false.
*/
public static void setGlobalDebugLoggingEnabled(boolean globalDebugLoggingEnabled) {
EpoxyController.globalDebugLoggingEnabled = globalDebugLoggingEnabled;
}
/**
* An optimized way to move a model from one position to another without rebuilding all models.
* This is intended to be used with {@link androidx.recyclerview.widget.ItemTouchHelper} to
* allow for efficient item dragging and rearranging. It cannot be
* <p>
* If you call this you MUST also update the data backing your models as necessary.
* <p>
* This will immediately change the model's position and notify the change to the RecyclerView.
* However, a delayed request to rebuild models will be scheduled for the future to guarantee that
* models are in sync with data.
*
* @param fromPosition Previous position of the item.
* @param toPosition New position of the item.
*/
public void moveModel(int fromPosition, int toPosition) {
assertNotBuildingModels();
adapter.moveModel(fromPosition, toPosition);
requestDelayedModelBuild(500);
}
/**
* An way to notify the adapter that a model has changed. This is intended to be used with
* {@link androidx.recyclerview.widget.ItemTouchHelper} to allow revert swiping a model.
* <p>
* This will immediately notify the change to the RecyclerView.
*
* @param position Position of the item.
*/
public void notifyModelChanged(int position) {
assertNotBuildingModels();
adapter.notifyModelChanged(position);
}
/**
* Get the underlying adapter built by this controller. Use this to get the adapter to set on a
* RecyclerView, or to get information about models currently in use.
*/
@NonNull
public EpoxyControllerAdapter getAdapter() {
return adapter;
}
public void onSaveInstanceState(@NonNull Bundle outState) {
adapter.onSaveInstanceState(outState);
}
public void onRestoreInstanceState(@Nullable Bundle inState) {
adapter.onRestoreInstanceState(inState);
}
/**
* For use with a grid layout manager - use this to get the {@link SpanSizeLookup} for models in
* this controller. This will delegate span look up calls to each model's {@link
* EpoxyModel#getSpanSize(int, int, int)}. Make sure to also call {@link #setSpanCount(int)} so
* the span count is correct.
*/
@NonNull
public SpanSizeLookup getSpanSizeLookup() {
return adapter.getSpanSizeLookup();
}
/**
* If you are using a grid layout manager you must call this to set the span count of the grid.
* This span count will be passed on to the models so models can choose which span count to be.
*
* @see #getSpanSizeLookup()
* @see EpoxyModel#getSpanSize(int, int, int)
*/
public void setSpanCount(int spanCount) {
adapter.setSpanCount(spanCount);
}
public int getSpanCount() {
return adapter.getSpanCount();
}
public boolean isMultiSpan() {
return adapter.isMultiSpan();
}
/**
* This is called when recoverable exceptions occur at runtime. By default they are ignored and
* Epoxy will recover, but you can override this to be aware of when they happen.
* <p>
* A common use for this is being aware of duplicates when {@link #setFilterDuplicates(boolean)}
* is enabled.
* <p>
* By default the global exception handler provided by
* {@link #setGlobalExceptionHandler(ExceptionHandler)}
* is called with the exception. Overriding this allows you to provide your own handling for a
* controller.
*/
protected void onExceptionSwallowed(@NonNull RuntimeException exception) {
globalExceptionHandler.onException(this, exception);
}
/**
* Default handler for exceptions in all EpoxyControllers. Set with {@link
* #setGlobalExceptionHandler(ExceptionHandler)}
*/
private static ExceptionHandler globalExceptionHandler =
new ExceptionHandler() {
@Override
public void onException(@NonNull EpoxyController controller,
@NonNull RuntimeException exception) {
// Ignore exceptions as the default
}
};
/**
* Set a callback to be notified when a recoverable exception occurs at runtime. By default these
* are ignored and Epoxy will recover, but you can override this to be aware of when they happen.
* <p>
* For example, you could choose to rethrow the exception in development builds, or log them in
* production.
* <p>
* A common use for this is being aware of duplicates when {@link #setFilterDuplicates(boolean)}
* is enabled.
* <p>
* This callback will be used in all EpoxyController classes. If you would like specific handling
* in a certain controller you can override {@link #onExceptionSwallowed(RuntimeException)} in
* that controller.
*/
public static void setGlobalExceptionHandler(
@NonNull ExceptionHandler globalExceptionHandler) {
EpoxyController.globalExceptionHandler = globalExceptionHandler;
}
public interface ExceptionHandler {
/**
* This is called when recoverable exceptions happen at runtime. They can be ignored and Epoxy
* will recover, but you can override this to be aware of when they happen.
* <p>
* For example, you could choose to rethrow the exception in development builds, or log them in
* production.
*
* @param controller The EpoxyController that the error occurred in.
*/
void onException(@NonNull EpoxyController controller, @NonNull RuntimeException exception);
}
void onAttachedToRecyclerViewInternal(RecyclerView recyclerView) {
recyclerViewAttachCount++;
if (recyclerViewAttachCount > 1) {
MainThreadExecutor.INSTANCE.handler.postDelayed(new Runnable() {
@Override
public void run() {
// Only warn if there are still multiple adapters attached after a delay, to allow for
// a grace period
if (recyclerViewAttachCount > 1) {
onExceptionSwallowed(new IllegalStateException(
"This EpoxyController had its adapter added to more than one ReyclerView. Epoxy "
+ "does not support attaching an adapter to multiple RecyclerViews because "
+ "saved state will not work properly. If you did not intend to attach your "
+ "adapter "
+ "to multiple RecyclerViews you may be leaking a "
+ "reference to a previous RecyclerView. Make sure to remove the adapter from "
+ "any "
+ "previous RecyclerViews (eg if the adapter is reused in a Fragment across "
+ "multiple onCreateView/onDestroyView cycles). See https://github"
+ ".com/airbnb/epoxy/wiki/Avoiding-Memory-Leaks for more information."));
}
}
}, DELAY_TO_CHECK_ADAPTER_COUNT_MS);
}
onAttachedToRecyclerView(recyclerView);
}
void onDetachedFromRecyclerViewInternal(RecyclerView recyclerView) {
recyclerViewAttachCount--;
onDetachedFromRecyclerView(recyclerView);
}
/** Called when the controller's adapter is attach to a recyclerview. */
protected void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
}
/** Called when the controller's adapter is detached from a recyclerview. */
protected void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
}
/**
* Called immediately after a model is bound to a view holder. Subclasses can override this if
* they want alerts on when a model is bound. Alternatively you may attach a listener directly to
* a generated model with model.onBind(...)
*
* @param previouslyBoundModel If non null, this is a model with the same id as the newly bound
* model, and was previously bound to a view. This means that {@link
* #buildModels()} returned a model that is different from the
* previouslyBoundModel and the view is being rebound to incorporate
* the change. You can compare this previous model with the new one to
* see exactly what changed.
* <p>
* The newly bound model and the previously bound model are guaranteed
* to have the same id, but will not necessarily be of the same type
* depending on your implementation of {@link #buildModels()}. With
* common usage patterns of Epoxy they should be the same type, and
* will only differ if you are using different model classes with the
* same id.
* <p>
* Comparing the newly bound model with the previous model allows you
* to be more intelligent when updating your view. This may help you
* optimize, or make it easier to work with animations.
* <p>
* If the new model and the previous model have the same view type
* (given by {@link EpoxyModel#getViewType()}), and if you are using
* the default ReyclerView item animator, the same view will be kept.
* If you are using a custom item animator then the view will be the
* same if the animator returns true in canReuseUpdatedViewHolder.
* <p>
* This previously bound model is taken as a payload from the diffing
* process, and follows the same general conditions for all
* recyclerview change payloads.
*/
protected void onModelBound(@NonNull EpoxyViewHolder holder, @NonNull EpoxyModel<?> boundModel,
int position,
@Nullable EpoxyModel<?> previouslyBoundModel) {
}
/**
* Called immediately after a model is unbound from a view holder. Subclasses can override this if
* they want alerts on when a model is unbound. Alternatively you may attach a listener directly
* to a generated model with model.onUnbind(...)
*/
protected void onModelUnbound(@NonNull EpoxyViewHolder holder, @NonNull EpoxyModel<?> model) {
}
/**
* Called when the given viewholder is attached to the window, along with the model it is bound
* to.
*
* @see BaseEpoxyAdapter#onViewAttachedToWindow(EpoxyViewHolder)
*/
protected void onViewAttachedToWindow(@NonNull EpoxyViewHolder holder,
@NonNull EpoxyModel<?> model) {
}
/**
* Called when the given viewholder is detechaed from the window, along with the model it is bound
* to.
*
* @see BaseEpoxyAdapter#onViewDetachedFromWindow(EpoxyViewHolder)
*/
protected void onViewDetachedFromWindow(@NonNull EpoxyViewHolder holder,
@NonNull EpoxyModel<?> model) {
}
//region Sticky header
/**
* Optional callback to setup the sticky view,
* by default it doesn't do anything.
*
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public void setupStickyHeaderView(@NotNull View stickyHeader) {
// no-op
}
/**
* Optional callback to perform tear down operation on the
* sticky view, by default it doesn't do anything.
*
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public void teardownStickyHeaderView(@NotNull View stickyHeader) {
// no-op
}
/**
* Called to check if the item at the position is a sticky item,
* by default returns false.
*
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public boolean isStickyHeader(int position) {
return false;
}
//endregion
}
| 8,938 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/DiffResult.java | package com.airbnb.epoxy;
import java.util.Collections;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.AdapterListUpdateCallback;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView.Adapter;
/**
* Wraps the result of {@link AsyncEpoxyDiffer#submitList(List)}.
*/
public class DiffResult {
@NonNull final List<? extends EpoxyModel<?>> previousModels;
@NonNull final List<? extends EpoxyModel<?>> newModels;
/**
* If this is non null it means the full differ ran and the result is contained
* in this object. If it is null, it means that either the old list or the new list was empty, so
* we can simply add all or clear all items and skipped running the full diffing.
*/
@Nullable final DiffUtil.DiffResult differResult;
/** No changes were made to the models. */
static DiffResult noOp(@Nullable List<? extends EpoxyModel<?>> models) {
if (models == null) {
models = Collections.emptyList();
}
return new DiffResult(models, models, null);
}
/** The previous list was empty and the given non empty list was inserted. */
static DiffResult inserted(@NonNull List<? extends EpoxyModel<?>> newModels) {
//noinspection unchecked
return new DiffResult(Collections.EMPTY_LIST, newModels, null);
}
/** The previous list was non empty and the new list is empty. */
static DiffResult clear(@NonNull List<? extends EpoxyModel<?>> previousModels) {
//noinspection unchecked
return new DiffResult(previousModels, Collections.EMPTY_LIST, null);
}
/**
* The previous and new models are both non empty and a full differ pass was run on them.
* There may be no changes, however.
*/
static DiffResult diff(
@NonNull List<? extends EpoxyModel<?>> previousModels,
@NonNull List<? extends EpoxyModel<?>> newModels,
@NonNull DiffUtil.DiffResult differResult
) {
return new DiffResult(previousModels, newModels, differResult);
}
private DiffResult(
@NonNull List<? extends EpoxyModel<?>> previousModels,
@NonNull List<? extends EpoxyModel<?>> newModels,
@Nullable DiffUtil.DiffResult differResult
) {
this.previousModels = previousModels;
this.newModels = newModels;
this.differResult = differResult;
}
public void dispatchTo(Adapter adapter) {
dispatchTo(new AdapterListUpdateCallback(adapter));
}
public void dispatchTo(ListUpdateCallback callback) {
if (differResult != null) {
differResult.dispatchUpdatesTo(callback);
} else if (newModels.isEmpty() && !previousModels.isEmpty()) {
callback.onRemoved(0, previousModels.size());
} else if (!newModels.isEmpty() && previousModels.isEmpty()) {
callback.onInserted(0, newModels.size());
}
// Else nothing changed!
}
}
| 8,939 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyHolder.java | package com.airbnb.epoxy;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
/**
* Used in conjunction with {@link com.airbnb.epoxy.EpoxyModelWithHolder} to provide a view holder
* pattern when binding to a model.
*/
public abstract class EpoxyHolder {
public EpoxyHolder(@NonNull ViewParent parent) {
this();
}
public EpoxyHolder() {
}
/**
* Called when this holder is created, with the view that it should hold. You can use this
* opportunity to find views by id, and do any other initialization you need. This is called only
* once for the lifetime of the class.
*
* @param itemView A view inflated from the layout provided by
* {@link EpoxyModelWithHolder#getLayout()}
*/
protected abstract void bindView(@NonNull View itemView);
}
| 8,940 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ControllerModelList.java | package com.airbnb.epoxy;
/**
* This ArrayList subclass enforces that no changes are made to the list after {@link #freeze()} is
* called. This prevents model interceptors from storing the list and trying to change it later. We
* could copy the list before diffing, but that would waste memory to make the copy for every
* buildModels cycle, plus the interceptors could still try to modify the list and be confused about
* why it doesn't do anything.
*/
class ControllerModelList extends ModelList {
private static final ModelListObserver OBSERVER = new ModelListObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
throw new IllegalStateException(
"Models cannot be changed once they are added to the controller");
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
throw new IllegalStateException(
"Models cannot be changed once they are added to the controller");
}
};
ControllerModelList(int expectedModelCount) {
super(expectedModelCount);
pauseNotifications();
}
void freeze() {
setObserver(OBSERVER);
resumeNotifications();
}
}
| 8,941 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ListenersUtils.java | package com.airbnb.epoxy;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
public class ListenersUtils {
@Nullable
static EpoxyViewHolder getEpoxyHolderForChildView(View v) {
RecyclerView recyclerView = findParentRecyclerView(v);
if (recyclerView == null) {
return null;
}
ViewHolder viewHolder = recyclerView.findContainingViewHolder(v);
if (viewHolder == null) {
return null;
}
if (!(viewHolder instanceof EpoxyViewHolder)) {
return null;
}
return (EpoxyViewHolder) viewHolder;
}
@Nullable
private static RecyclerView findParentRecyclerView(@Nullable View v) {
if (v == null) {
return null;
}
ViewParent parent = v.getParent();
if (parent instanceof RecyclerView) {
return (RecyclerView) parent;
}
if (parent instanceof View) {
return findParentRecyclerView((View) parent);
}
return null;
}
}
| 8,942 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/TypedEpoxyController.java | package com.airbnb.epoxy;
import android.os.Handler;
import androidx.annotation.Nullable;
/**
* This is a wrapper around {@link com.airbnb.epoxy.EpoxyController} to simplify how data is
* accessed. Use this if the data required to build your models is represented by a single object.
* <p>
* To use this, create a subclass typed with your data object. Then, call {@link #setData(Object)}
* whenever that data changes. This class will handle calling {@link #buildModels(Object)} with the
* latest data.
* <p>
* You should NOT call {@link #requestModelBuild()} directly.
*
* @see Typed2EpoxyController
* @see Typed3EpoxyController
* @see Typed4EpoxyController
*/
public abstract class TypedEpoxyController<T> extends EpoxyController {
private T currentData;
private boolean allowModelBuildRequests;
public TypedEpoxyController() {
}
public TypedEpoxyController(Handler modelBuildingHandler, Handler diffingHandler) {
super(modelBuildingHandler, diffingHandler);
}
public final void setData(T data) {
currentData = data;
allowModelBuildRequests = true;
requestModelBuild();
allowModelBuildRequests = false;
}
@Override
public final void requestModelBuild() {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestModelBuild();
}
@Override
public void moveModel(int fromPosition, int toPosition) {
allowModelBuildRequests = true;
super.moveModel(fromPosition, toPosition);
allowModelBuildRequests = false;
}
@Override
public void requestDelayedModelBuild(int delayMs) {
if (!allowModelBuildRequests) {
throw new IllegalStateException(
"You cannot call `requestModelBuild` directly. Call `setData` instead to trigger a "
+ "model refresh with new data.");
}
super.requestDelayedModelBuild(delayMs);
}
@Nullable
public final T getCurrentData() {
return currentData;
}
@Override
protected final void buildModels() {
if (!isBuildingModels()) {
throw new IllegalStateException(
"You cannot call `buildModels` directly. Call `setData` instead to trigger a model "
+ "refresh with new data.");
}
buildModels(currentData);
}
protected abstract void buildModels(T data);
}
| 8,943 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyModel.java | package com.airbnb.epoxy;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.airbnb.epoxy.EpoxyController.ModelInterceptorCallback;
import com.airbnb.epoxy.VisibilityState.Visibility;
import java.util.List;
import androidx.annotation.FloatRange;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import static com.airbnb.epoxy.IdUtils.hashLong64Bit;
import static com.airbnb.epoxy.IdUtils.hashString64Bit;
/**
* Helper to bind data to a view using a builder style. The parameterized type should extend
* Android's View or EpoxyHolder.
*
* @see EpoxyModelWithHolder
* @see EpoxyModelWithView
*/
public abstract class EpoxyModel<T> {
/**
* Counts how many of these objects are created, so that each new object can have a unique id .
* Uses negative values so that these autogenerated ids don't clash with database ids that may be
* set with {@link #id(long)}
*/
private static long idCounter = -1;
/**
* An id that can be used to uniquely identify this {@link EpoxyModel} for use in RecyclerView
* stable ids. It defaults to a unique id for this object instance, if you want to maintain the
* same id across instances use {@link #id(long)}
*/
private long id;
@LayoutRes private int layout;
private boolean shown = true;
/**
* Set to true once this model is diffed in an adapter. Used to ensure that this model's id
* doesn't change after being diffed.
*/
boolean addedToAdapter;
/**
* The first controller this model was added to. A reference is kept in debug mode in order to run
* validations. The model is allowed to be added to other controllers, but we only keep a
* reference to the first.
*/
private EpoxyController firstControllerAddedTo;
/**
* Models are staged when they are changed. This allows them to be automatically added when they
* are done being changed (eg the next model is changed/added or buildModels finishes). It is only
* allowed for AutoModels, and only if implicit adding is enabled.
*/
EpoxyController controllerToStageTo;
private boolean currentlyInInterceptors;
private int hashCodeWhenAdded;
private boolean hasDefaultId;
@Nullable private SpanSizeOverrideCallback spanSizeOverride;
protected EpoxyModel(long id) {
id(id);
}
public EpoxyModel() {
this(idCounter--);
hasDefaultId = true;
}
boolean hasDefaultId() {
return hasDefaultId;
}
/**
* Get the view type to associate with this model in the recyclerview. For models that use a
* layout resource, the view type is simply the layout resource value by default.
* <p>
* If this returns 0 Epoxy will assign a unique view type for this model at run time.
*
* @see androidx.recyclerview.widget.RecyclerView.Adapter#getItemViewType(int)
*/
protected int getViewType() {
return getLayout();
}
/**
* Create and return a new instance of a view for this model. By default a view is created by
* inflating the layout resource.
*/
public View buildView(@NonNull ViewGroup parent) {
return LayoutInflater.from(parent.getContext()).inflate(getLayout(), parent, false);
}
/**
* Hook that is called before {@link #bind(Object)}. This is similar to
* {@link GeneratedModel#handlePreBind(EpoxyViewHolder, Object, int)}, but is intended for
* subclasses of EpoxyModel to hook into rather than for generated code to hook into.
* Overriding preBind is useful to capture state before the view changes, e.g. for animations.
*
* @param previouslyBoundModel This is a model with the same id that was previously bound. You can
* compare this previous model with the current one to see exactly
* what changed.
* <p>
* This model and the previously bound model are guaranteed to have
* the same id, but will not necessarily be of the same type depending
* on your implementation of {@link EpoxyController#buildModels()}.
* With common usage patterns of Epoxy they should be the same type,
* and will only differ if you are using different model classes with
* the same id.
* <p>
* Comparing the newly bound model with the previous model allows you
* to be more intelligent when binding your view. This may help you
* optimize view binding, or make it easier to work with animations.
* <p>
* If the new model and the previous model have the same view type
* (given by {@link EpoxyModel#getViewType()}), and if you are using
* the default ReyclerView item animator, the same view will be
* reused. This means that you only need to update the view to reflect
* the data that changed. If you are using a custom item animator then
* the view will be the same if the animator returns true in
* canReuseUpdatedViewHolder.
* <p>
* This previously bound model is taken as a payload from the diffing
* process, and follows the same general conditions for all
* recyclerview change payloads.
*/
public void preBind(@NonNull T view, @Nullable EpoxyModel<?> previouslyBoundModel) {
}
/**
* Binds the current data to the given view. You should bind all fields including unset/empty
* fields to ensure proper recycling.
*/
public void bind(@NonNull T view) {
}
/**
* Similar to {@link #bind(Object)}, but provides a non null, non empty list of payloads
* describing what changed. This is the payloads list specified in the adapter's notifyItemChanged
* method. This is a useful optimization to allow you to only change part of a view instead of
* updating the whole thing, which may prevent unnecessary layout calls. If there are no payloads
* then {@link #bind(Object)} is called instead. This will only be used if the model is used with
* an {@link EpoxyAdapter}
*/
public void bind(@NonNull T view, @NonNull List<Object> payloads) {
bind(view);
}
/**
* Similar to {@link #bind(Object)}, but provides a non null model which was previously bound to
* this view. This will only be called if the model is used with an {@link EpoxyController}.
*
* @param previouslyBoundModel This is a model with the same id that was previously bound. You can
* compare this previous model with the current one to see exactly
* what changed.
* <p>
* This model and the previously bound model are guaranteed to have
* the same id, but will not necessarily be of the same type depending
* on your implementation of {@link EpoxyController#buildModels()}.
* With common usage patterns of Epoxy they should be the same type,
* and will only differ if you are using different model classes with
* the same id.
* <p>
* Comparing the newly bound model with the previous model allows you
* to be more intelligent when binding your view. This may help you
* optimize view binding, or make it easier to work with animations.
* <p>
* If the new model and the previous model have the same view type
* (given by {@link EpoxyModel#getViewType()}), and if you are using
* the default ReyclerView item animator, the same view will be
* reused. This means that you only need to update the view to reflect
* the data that changed. If you are using a custom item animator then
* the view will be the same if the animator returns true in
* canReuseUpdatedViewHolder.
* <p>
* This previously bound model is taken as a payload from the diffing
* process, and follows the same general conditions for all
* recyclerview change payloads.
*/
public void bind(@NonNull T view, @NonNull EpoxyModel<?> previouslyBoundModel) {
bind(view);
}
/**
* Called when the view bound to this model is recycled. Subclasses can override this if their
* view should release resources when it's recycled.
* <p>
* Note that {@link #bind(Object)} can be called multiple times without an unbind call in between
* if the view has remained on screen to be reused across item changes. This means that you should
* not rely on unbind to clear a view or model's state before bind is called again.
*
* @see EpoxyAdapter#onViewRecycled(EpoxyViewHolder)
*/
public void unbind(@NonNull T view) {
}
/**
* TODO link to the wiki
*
* @see OnVisibilityStateChanged annotation
*/
public void onVisibilityStateChanged(@Visibility int visibilityState, @NonNull T view) {
}
/**
* TODO link to the wiki
*
* @see OnVisibilityChanged annotation
*/
public void onVisibilityChanged(
@FloatRange(from = 0.0f, to = 100.0f) float percentVisibleHeight,
@FloatRange(from = 0.0f, to = 100.0f) float percentVisibleWidth,
@Px int visibleHeight,
@Px int visibleWidth,
@NonNull T view
) {
}
public long id() {
return id;
}
/**
* Override the default id in cases where the data subject naturally has an id, like an object
* from a database. This id can only be set before the model is added to the adapter, it is an
* error to change the id after that.
*/
public EpoxyModel<T> id(long id) {
if ((addedToAdapter || firstControllerAddedTo != null) && id != this.id) {
throw new IllegalEpoxyUsage(
"Cannot change a model's id after it has been added to the adapter.");
}
hasDefaultId = false;
this.id = id;
return this;
}
/**
* Use multiple numbers as the id for this model. Useful when you don't have a single long that
* represents a unique id.
* <p>
* This hashes the numbers, so there is a tiny risk of collision with other ids.
*/
public EpoxyModel<T> id(@Nullable Number... ids) {
long result = 0;
if (ids != null) {
for (@Nullable Number id : ids) {
result = 31 * result + hashLong64Bit(id == null ? 0 : id.hashCode());
}
}
return id(result);
}
/**
* Use two numbers as the id for this model. Useful when you don't have a single long that
* represents a unique id.
* <p>
* This hashes the two numbers, so there is a tiny risk of collision with other ids.
*/
public EpoxyModel<T> id(long id1, long id2) {
long result = hashLong64Bit(id1);
result = 31 * result + hashLong64Bit(id2);
return id(result);
}
/**
* Use a string as the model id. Useful for models that don't clearly map to a numerical id. This
* is preferable to using {@link String#hashCode()} because that is a 32 bit hash and this is a 64
* bit hash, giving better spread and less chance of collision with other ids.
* <p>
* Since this uses a hashcode method to convert the String to a long there is a very small chance
* that you may have a collision with another id. Assuming an even spread of hashcodes, and
* several hundred models in the adapter, there would be roughly 1 in 100 trillion chance of a
* collision. (http://preshing.com/20110504/hash-collision-probabilities/)
*
* @see IdUtils#hashString64Bit(CharSequence)
*/
public EpoxyModel<T> id(@Nullable CharSequence key) {
id(hashString64Bit(key));
return this;
}
/**
* Use several strings to define the id of the model.
* <p>
* Similar to {@link #id(CharSequence)}, but with additional strings.
*/
public EpoxyModel<T> id(@Nullable CharSequence key, @Nullable CharSequence... otherKeys) {
long result = hashString64Bit(key);
if (otherKeys != null) {
for (CharSequence otherKey : otherKeys) {
result = 31 * result + hashString64Bit(otherKey);
}
}
return id(result);
}
/**
* Set an id that is namespaced with a string. This is useful when you need to show models of
* multiple types, side by side and don't want to risk id collisions.
* <p>
* Since this uses a hashcode method to convert the String to a long there is a very small chance
* that you may have a collision with another id. Assuming an even spread of hashcodes, and
* several hundred models in the adapter, there would be roughly 1 in 100 trillion chance of a
* collision. (http://preshing.com/20110504/hash-collision-probabilities/)
*
* @see IdUtils#hashString64Bit(CharSequence)
* @see IdUtils#hashLong64Bit(long)
*/
public EpoxyModel<T> id(@Nullable CharSequence key, long id) {
long result = hashString64Bit(key);
result = 31 * result + hashLong64Bit(id);
id(result);
return this;
}
/**
* Return the default layout resource to be used when creating views for this model. The resource
* will be inflated to create a view for the model; additionally the layout int is used as the
* views type in the RecyclerView.
* <p>
* This can be left unimplemented if you use the {@link EpoxyModelClass} annotation to define a
* layout.
* <p>
* This default value can be overridden with {@link #layout(int)} at runtime to change the layout
* dynamically.
*/
@LayoutRes
protected abstract int getDefaultLayout();
@NonNull
public EpoxyModel<T> layout(@LayoutRes int layoutRes) {
onMutation();
layout = layoutRes;
return this;
}
@LayoutRes
public final int getLayout() {
if (layout == 0) {
return getDefaultLayout();
}
return layout;
}
/**
* Sets fields of the model to default ones.
*/
@NonNull
public EpoxyModel<T> reset() {
onMutation();
layout = 0;
shown = true;
return this;
}
/**
* Add this model to the given controller. Can only be called from inside {@link
* EpoxyController#buildModels()}.
*/
public void addTo(@NonNull EpoxyController controller) {
controller.addInternal(this);
}
/**
* Add this model to the given controller if the condition is true. Can only be called from inside
* {@link EpoxyController#buildModels()}.
*/
public void addIf(boolean condition, @NonNull EpoxyController controller) {
if (condition) {
addTo(controller);
} else if (controllerToStageTo != null) {
// Clear this model from staging since it failed the add condition. If this model wasn't
// staged (eg not changed before addIf was called, then we need to make sure to add the
// previously staged model.
controllerToStageTo.clearModelFromStaging(this);
controllerToStageTo = null;
}
}
/**
* Add this model to the given controller if the {@link AddPredicate} return true. Can only be
* called from inside {@link EpoxyController#buildModels()}.
*/
public void addIf(@NonNull AddPredicate predicate, @NonNull EpoxyController controller) {
addIf(predicate.addIf(), controller);
}
/**
* @see #addIf(AddPredicate, EpoxyController)
*/
public interface AddPredicate {
boolean addIf();
}
/**
* This is used internally by generated models to turn on validation checking when
* "validateEpoxyModelUsage" is enabled and the model is used with an {@link EpoxyController}.
*/
protected final void addWithDebugValidation(@NonNull EpoxyController controller) {
if (controller == null) {
throw new IllegalArgumentException("Controller cannot be null");
}
if (controller.isModelAddedMultipleTimes(this)) {
throw new IllegalEpoxyUsage(
"This model was already added to the controller at position "
+ controller.getFirstIndexOfModelInBuildingList(this));
}
if (firstControllerAddedTo == null) {
firstControllerAddedTo = controller;
// We save the current hashCode so we can compare it to the hashCode at later points in time
// in order to validate that it doesn't change and enforce mutability.
hashCodeWhenAdded = hashCode();
// The one time it is valid to change the model is during an interceptor callback. To support
// that we need to update the hashCode after interceptors have been run.
// The model can be added to multiple controllers, but we only allow an interceptor change
// the first time, since after that it will have been added to an adapter.
controller.addAfterInterceptorCallback(new ModelInterceptorCallback() {
@Override
public void onInterceptorsStarted(EpoxyController controller) {
currentlyInInterceptors = true;
}
@Override
public void onInterceptorsFinished(EpoxyController controller) {
hashCodeWhenAdded = EpoxyModel.this.hashCode();
currentlyInInterceptors = false;
}
});
}
}
boolean isDebugValidationEnabled() {
return firstControllerAddedTo != null;
}
/**
* This is used internally by generated models to do validation checking when
* "validateEpoxyModelUsage" is enabled and the model is used with an {@link EpoxyController}.
* This method validates that it is ok to change this model. It is only valid if the model hasn't
* yet been added, or the change is being done from an {@link EpoxyController.Interceptor}
* callback.
* <p>
* This is also used to stage the model for implicitly adding it, if it is an AutoModel and
* implicit adding is enabled.
*/
protected final void onMutation() {
// The model may be added to multiple controllers, in which case if it was already diffed
// and added to an adapter in one controller we don't want to even allow interceptors
// from changing the model in a different controller
if (isDebugValidationEnabled() && !currentlyInInterceptors) {
throw new ImmutableModelException(this,
getPosition(firstControllerAddedTo, this));
}
if (controllerToStageTo != null) {
controllerToStageTo.setStagedModel(this);
}
}
private static int getPosition(@NonNull EpoxyController controller,
@NonNull EpoxyModel<?> model) {
// If the model was added to multiple controllers, or was removed from the controller and then
// modified, this won't be correct. But those should be very rare cases that we don't need to
// worry about
if (controller.isBuildingModels()) {
return controller.getFirstIndexOfModelInBuildingList(model);
}
return controller.getAdapter().getModelPosition(model);
}
/**
* This is used internally by generated models to do validation checking when
* "validateEpoxyModelUsage" is enabled and the model is used with a {@link EpoxyController}. This
* method validates that the model's hashCode hasn't been changed since it was added to the
* controller. This is similar to {@link #onMutation()}, but that method is only used for
* specific model changes such as calling a setter. By checking the hashCode, this method allows
* us to catch more subtle changes, such as through setting a field directly or through changing
* an object that is set on the model.
*/
protected final void validateStateHasNotChangedSinceAdded(String descriptionOfChange,
int modelPosition) {
if (isDebugValidationEnabled()
&& !currentlyInInterceptors
&& hashCodeWhenAdded != hashCode()) {
throw new ImmutableModelException(this, descriptionOfChange, modelPosition);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EpoxyModel)) {
return false;
}
EpoxyModel<?> that = (EpoxyModel<?>) o;
if (id != that.id) {
return false;
}
if (getViewType() != that.getViewType()) {
return false;
}
return shown == that.shown;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + getViewType();
result = 31 * result + (shown ? 1 : 0);
return result;
}
/**
* Subclasses can override this if they want their view to take up more than one span in a grid
* layout.
*
* @param totalSpanCount The number of spans in the grid
* @param position The position of the model
* @param itemCount The total number of items in the adapter
*/
public int getSpanSize(int totalSpanCount, int position, int itemCount) {
return 1;
}
public EpoxyModel<T> spanSizeOverride(@Nullable SpanSizeOverrideCallback spanSizeCallback) {
this.spanSizeOverride = spanSizeCallback;
return this;
}
public interface SpanSizeOverrideCallback {
int getSpanSize(int totalSpanCount, int position, int itemCount);
}
/**
* Returns the actual span size of this model, using the {@link SpanSizeOverrideCallback} if one
* was set, otherwise using the value from {@link #getSpanSize(int, int, int)}
*/
public final int spanSize(int totalSpanCount, int position, int itemCount) {
if (spanSizeOverride != null) {
return spanSizeOverride.getSpanSize(totalSpanCount, position, itemCount);
}
return getSpanSize(totalSpanCount, position, itemCount);
}
/**
* Change the visibility of the model so that it's view is shown. This only works if the model is
* used in {@link EpoxyAdapter} or a {@link EpoxyModelGroup}, but is not supported in {@link
* EpoxyController}
*/
@NonNull
public EpoxyModel<T> show() {
return show(true);
}
/**
* Change the visibility of the model's view. This only works if the model is
* used in {@link EpoxyAdapter} or a {@link EpoxyModelGroup}, but is not supported in {@link
* EpoxyController}
*/
@NonNull
public EpoxyModel<T> show(boolean show) {
onMutation();
shown = show;
return this;
}
/**
* Change the visibility of the model so that it's view is hidden. This only works if the model is
* used in {@link EpoxyAdapter} or a {@link EpoxyModelGroup}, but is not supported in {@link
* EpoxyController}
*/
@NonNull
public EpoxyModel<T> hide() {
return show(false);
}
/**
* Whether the model's view should be shown on screen. If false it won't be inflated and drawn,
* and will be like it was never added to the recycler view.
*/
public boolean isShown() {
return shown;
}
/**
* Whether the adapter should save the state of the view bound to this model.
*/
public boolean shouldSaveViewState() {
return false;
}
/**
* Called if the RecyclerView failed to recycle this model's view. You can take this opportunity
* to clear the animation(s) that affect the View's transient state and return <code>true</code>
* so that the View can be recycled. Keep in mind that the View in question is already removed
* from the RecyclerView.
*
* @return True if the View should be recycled, false otherwise
* @see EpoxyAdapter#onFailedToRecycleView(androidx.recyclerview.widget.RecyclerView.ViewHolder)
*/
public boolean onFailedToRecycleView(@NonNull T view) {
return false;
}
/**
* Called when this model's view is attached to the window.
*
* @see EpoxyAdapter#onViewAttachedToWindow(androidx.recyclerview.widget.RecyclerView.ViewHolder)
*/
public void onViewAttachedToWindow(@NonNull T view) {
}
/**
* Called when this model's view is detached from the the window.
*
* @see EpoxyAdapter#onViewDetachedFromWindow(androidx.recyclerview.widget.RecyclerView
* .ViewHolder)
*/
public void onViewDetachedFromWindow(@NonNull T view) {
}
@Override
public String toString() {
return getClass().getSimpleName() + "{"
+ "id=" + id
+ ", viewType=" + getViewType()
+ ", shown=" + shown
+ ", addedToAdapter=" + addedToAdapter
+ '}';
}
}
| 8,944 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/BoundViewHolders.java |
package com.airbnb.epoxy;
import java.util.Iterator;
import java.util.NoSuchElementException;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
/** Helper class for keeping track of {@link EpoxyViewHolder}s that are currently bound. */
@SuppressWarnings("WeakerAccess")
public class BoundViewHolders implements Iterable<EpoxyViewHolder> {
private final LongSparseArray<EpoxyViewHolder> holders = new LongSparseArray<>();
@Nullable
public EpoxyViewHolder get(EpoxyViewHolder holder) {
return holders.get(holder.getItemId());
}
public void put(EpoxyViewHolder holder) {
holders.put(holder.getItemId(), holder);
}
public void remove(EpoxyViewHolder holder) {
holders.remove(holder.getItemId());
}
public int size() {
return holders.size();
}
@Override
public Iterator<EpoxyViewHolder> iterator() {
return new HolderIterator();
}
@Nullable
public EpoxyViewHolder getHolderForModel(EpoxyModel<?> model) {
return holders.get(model.id());
}
private class HolderIterator implements Iterator<EpoxyViewHolder> {
private int position = 0;
@Override
public boolean hasNext() {
return position < holders.size();
}
@Override
public EpoxyViewHolder next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return holders.valueAt(position++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| 8,945 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyModelWithHolder.java | package com.airbnb.epoxy;
import android.view.ViewParent;
import com.airbnb.epoxy.VisibilityState.Visibility;
import java.util.List;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Px;
/**
* A version of {@link com.airbnb.epoxy.EpoxyModel} that allows you to use a view holder pattern
* instead of a specific view when binding to your model.
*/
public abstract class EpoxyModelWithHolder<T extends EpoxyHolder> extends EpoxyModel<T> {
public EpoxyModelWithHolder() {
}
public EpoxyModelWithHolder(long id) {
super(id);
}
/** This should return a new instance of your {@link com.airbnb.epoxy.EpoxyHolder} class. */
protected abstract T createNewHolder(@NonNull ViewParent parent);
@Override
public void bind(@NonNull T holder) {
super.bind(holder);
}
@Override
public void bind(@NonNull T holder, @NonNull List<Object> payloads) {
super.bind(holder, payloads);
}
@Override
public void bind(@NonNull T holder, @NonNull EpoxyModel<?> previouslyBoundModel) {
super.bind(holder, previouslyBoundModel);
}
@Override
public void unbind(@NonNull T holder) {
super.unbind(holder);
}
@Override
public void onVisibilityStateChanged(@Visibility int visibilityState, @NonNull T holder) {
super.onVisibilityStateChanged(visibilityState, holder);
}
@Override
public void onVisibilityChanged(
@FloatRange(from = 0, to = 100) float percentVisibleHeight,
@FloatRange(from = 0, to = 100) float percentVisibleWidth,
@Px int visibleHeight, @Px int visibleWidth,
@NonNull T holder) {
super.onVisibilityChanged(
percentVisibleHeight, percentVisibleWidth,
visibleHeight, visibleWidth,
holder);
}
@Override
public boolean onFailedToRecycleView(T holder) {
return super.onFailedToRecycleView(holder);
}
@Override
public void onViewAttachedToWindow(T holder) {
super.onViewAttachedToWindow(holder);
}
@Override
public void onViewDetachedFromWindow(T holder) {
super.onViewDetachedFromWindow(holder);
}
}
| 8,946 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ImmutableModelException.java | package com.airbnb.epoxy;
import androidx.annotation.NonNull;
/**
* Thrown if a model is changed after it is added to an {@link com.airbnb.epoxy.EpoxyController}.
*/
class ImmutableModelException extends RuntimeException {
private static final String MODEL_CANNOT_BE_CHANGED_MESSAGE =
"Epoxy attribute fields on a model cannot be changed once the model is added to a "
+ "controller. Check that these fields are not updated, or that the assigned objects "
+ "are not mutated, outside of the buildModels method. The only exception is if "
+ "the change is made inside an Interceptor callback. Consider using an interceptor"
+ " if you need to change a model after it is added to the controller and before it"
+ " is set on the adapter. If the model is already set on the adapter then you must"
+ " call `requestModelBuild` instead to recreate all models.";
ImmutableModelException(EpoxyModel model, int modelPosition) {
this(model, "", modelPosition);
}
ImmutableModelException(EpoxyModel model,
String descriptionOfWhenChangeHappened, int modelPosition) {
super(buildMessage(model, descriptionOfWhenChangeHappened, modelPosition));
}
@NonNull
private static String buildMessage(EpoxyModel model,
String descriptionOfWhenChangeHappened, int modelPosition) {
return new StringBuilder(descriptionOfWhenChangeHappened)
.append(" Position: ")
.append(modelPosition)
.append(" Model: ")
.append(model.toString())
.append("\n\n")
.append(MODEL_CANNOT_BE_CHANGED_MESSAGE)
.toString();
}
}
| 8,947 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyAdapter.java |
package com.airbnb.epoxy;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import androidx.annotation.Nullable;
/**
* Allows you to easily combine different view types in the same adapter, and handles view holder
* creation, binding, and ids for you. Subclasses just need to add their desired {@link EpoxyModel}
* objects and the rest is done automatically.
* <p/>
* {@link androidx.recyclerview.widget.RecyclerView.Adapter#setHasStableIds(boolean)} is set to true
* by default, since {@link EpoxyModel} makes it easy to support unique ids. If you don't want to
* support this then disable it in your base class (not recommended).
*/
@SuppressWarnings("WeakerAccess")
public abstract class EpoxyAdapter extends BaseEpoxyAdapter {
private final HiddenEpoxyModel hiddenModel = new HiddenEpoxyModel();
/**
* Subclasses should modify this list as necessary with the models they want to show. Subclasses
* are responsible for notifying data changes whenever this list is changed.
*/
protected final List<EpoxyModel<?>> models = new ModelList();
private DiffHelper diffHelper;
@Override
List<EpoxyModel<?>> getCurrentModels() {
return models;
}
/**
* Enables support for automatically notifying model changes via {@link #notifyModelsChanged()}.
* If used, this should be called in the constructor, before any models are changed.
*
* @see #notifyModelsChanged()
*/
protected void enableDiffing() {
if (diffHelper != null) {
throw new IllegalStateException("Diffing was already enabled");
}
if (!models.isEmpty()) {
throw new IllegalStateException("You must enable diffing before modifying models");
}
if (!hasStableIds()) {
throw new IllegalStateException("You must have stable ids to use diffing");
}
diffHelper = new DiffHelper(this, false);
}
@Override
EpoxyModel<?> getModelForPosition(int position) {
EpoxyModel<?> model = models.get(position);
return model.isShown() ? model : hiddenModel;
}
/**
* Intelligently notify item changes by comparing the current {@link #models} list against the
* previous so you don't have to micromanage notification calls yourself. This may be
* prohibitively slow for large model lists (in the hundreds), in which case consider doing
* notification calls yourself. If you use this, all your view models must implement {@link
* EpoxyModel#hashCode()} and {@link EpoxyModel#equals(Object)} to completely identify their
* state, so that changes to a model's content can be detected. Before using this you must enable
* it with {@link #enableDiffing()}, since keeping track of the model state adds extra computation
* time to all other data change notifications.
*
* @see #enableDiffing()
*/
protected void notifyModelsChanged() {
if (diffHelper == null) {
throw new IllegalStateException("You must enable diffing before notifying models changed");
}
diffHelper.notifyModelChanges();
}
/**
* Notify that the given model has had its data changed. It should only be called if the model
* retained the same position.
*/
protected void notifyModelChanged(EpoxyModel<?> model) {
notifyModelChanged(model, null);
}
/**
* Notify that the given model has had its data changed. It should only be called if the model
* retained the same position.
*/
protected void notifyModelChanged(EpoxyModel<?> model, @Nullable Object payload) {
int index = getModelPosition(model);
if (index != -1) {
notifyItemChanged(index, payload);
}
}
/**
* Adds the model to the end of the {@link #models} list and notifies that the item was inserted.
*/
protected void addModel(EpoxyModel<?> modelToAdd) {
int initialSize = models.size();
pauseModelListNotifications();
models.add(modelToAdd);
resumeModelListNotifications();
notifyItemRangeInserted(initialSize, 1);
}
/**
* Adds the models to the end of the {@link #models} list and notifies that the items were
* inserted.
*/
protected void addModels(EpoxyModel<?>... modelsToAdd) {
int initialSize = models.size();
int numModelsToAdd = modelsToAdd.length;
((ModelList) models).ensureCapacity(initialSize + numModelsToAdd);
pauseModelListNotifications();
Collections.addAll(models, modelsToAdd);
resumeModelListNotifications();
notifyItemRangeInserted(initialSize, numModelsToAdd);
}
/**
* Adds the models to the end of the {@link #models} list and notifies that the items were
* inserted.
*/
protected void addModels(Collection<? extends EpoxyModel<?>> modelsToAdd) {
int initialSize = models.size();
pauseModelListNotifications();
models.addAll(modelsToAdd);
resumeModelListNotifications();
notifyItemRangeInserted(initialSize, modelsToAdd.size());
}
/**
* Inserts the given model before the other in the {@link #models} list, and notifies that the
* item was inserted.
*/
protected void insertModelBefore(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertBefore) {
int targetIndex = getModelPosition(modelToInsertBefore);
if (targetIndex == -1) {
throw new IllegalStateException("Model is not added: " + modelToInsertBefore);
}
pauseModelListNotifications();
models.add(targetIndex, modelToInsert);
resumeModelListNotifications();
notifyItemInserted(targetIndex);
}
/**
* Inserts the given model after the other in the {@link #models} list, and notifies that the item
* was inserted.
*/
protected void insertModelAfter(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertAfter) {
int modelIndex = getModelPosition(modelToInsertAfter);
if (modelIndex == -1) {
throw new IllegalStateException("Model is not added: " + modelToInsertAfter);
}
int targetIndex = modelIndex + 1;
pauseModelListNotifications();
models.add(targetIndex, modelToInsert);
resumeModelListNotifications();
notifyItemInserted(targetIndex);
}
/**
* If the given model exists it is removed and an item removal is notified. Otherwise this does
* nothing.
*/
protected void removeModel(EpoxyModel<?> model) {
int index = getModelPosition(model);
if (index != -1) {
pauseModelListNotifications();
models.remove(index);
resumeModelListNotifications();
notifyItemRemoved(index);
}
}
/**
* Removes all models
*/
protected void removeAllModels() {
int numModelsRemoved = models.size();
pauseModelListNotifications();
models.clear();
resumeModelListNotifications();
notifyItemRangeRemoved(0, numModelsRemoved);
}
/**
* Removes all models after the given model, which must have already been added. An example use
* case is you want to keep a header but clear everything else, like in the case of refreshing
* data.
*/
protected void removeAllAfterModel(EpoxyModel<?> model) {
List<EpoxyModel<?>> modelsToRemove = getAllModelsAfter(model);
int numModelsRemoved = modelsToRemove.size();
int initialModelCount = models.size();
// This is a sublist, so clearing it will clear the models in the original list
pauseModelListNotifications();
modelsToRemove.clear();
resumeModelListNotifications();
notifyItemRangeRemoved(initialModelCount - numModelsRemoved, numModelsRemoved);
}
/**
* Sets the visibility of the given model, and notifies that the item changed if the new
* visibility is different from the previous.
*
* @param model The model to show. It should already be added to the {@link #models} list.
* @param show True to show the model, false to hide it.
*/
protected void showModel(EpoxyModel<?> model, boolean show) {
if (model.isShown() == show) {
return;
}
model.show(show);
notifyModelChanged(model);
}
/**
* Shows the given model, and notifies that the item changed if the item wasn't already shown.
*
* @param model The model to show. It should already be added to the {@link #models} list.
*/
protected void showModel(EpoxyModel<?> model) {
showModel(model, true);
}
/**
* Shows the given models, and notifies that each item changed if the item wasn't already shown.
*
* @param models The models to show. They should already be added to the {@link #models} list.
*/
protected void showModels(EpoxyModel<?>... models) {
showModels(Arrays.asList(models));
}
/**
* Sets the visibility of the given models, and notifies that the items changed if the new
* visibility is different from the previous.
*
* @param models The models to show. They should already be added to the {@link #models} list.
* @param show True to show the models, false to hide them.
*/
protected void showModels(boolean show, EpoxyModel<?>... models) {
showModels(Arrays.asList(models), show);
}
/**
* Shows the given models, and notifies that each item changed if the item wasn't already shown.
*
* @param models The models to show. They should already be added to the {@link #models} list.
*/
protected void showModels(Iterable<EpoxyModel<?>> models) {
showModels(models, true);
}
/**
* Sets the visibility of the given models, and notifies that the items changed if the new
* visibility is different from the previous.
*
* @param models The models to show. They should already be added to the {@link #models} list.
* @param show True to show the models, false to hide them.
*/
protected void showModels(Iterable<EpoxyModel<?>> models, boolean show) {
for (EpoxyModel<?> model : models) {
showModel(model, show);
}
}
/**
* Hides the given model, and notifies that the item changed if the item wasn't already hidden.
*
* @param model The model to hide. This should already be added to the {@link #models} list.
*/
protected void hideModel(EpoxyModel<?> model) {
showModel(model, false);
}
/**
* Hides the given models, and notifies that each item changed if the item wasn't already hidden.
*
* @param models The models to hide. They should already be added to the {@link #models} list.
*/
protected void hideModels(Iterable<EpoxyModel<?>> models) {
showModels(models, false);
}
/**
* Hides the given models, and notifies that each item changed if the item wasn't already hidden.
*
* @param models The models to hide. They should already be added to the {@link #models} list.
*/
protected void hideModels(EpoxyModel<?>... models) {
hideModels(Arrays.asList(models));
}
/**
* Hides all models currently located after the given model in the {@link #models} list.
*
* @param model The model after which to hide. It must exist in the {@link #models} list.
*/
protected void hideAllAfterModel(EpoxyModel<?> model) {
hideModels(getAllModelsAfter(model));
}
/**
* Returns a sub list of all items in {@link #models} that occur after the given model. This list
* is backed by the original models list, any changes to the returned list will be reflected in
* the original {@link #models} list.
*
* @param model Must exist in {@link #models}.
*/
protected List<EpoxyModel<?>> getAllModelsAfter(EpoxyModel<?> model) {
int index = getModelPosition(model);
if (index == -1) {
throw new IllegalStateException("Model is not added: " + model);
}
return models.subList(index + 1, models.size());
}
/**
* We pause the list's notifications when we modify models internally, since we already do the
* proper adapter notifications for those modifications. By pausing these list notifications we
* prevent the differ having to do work to track them.
*/
private void pauseModelListNotifications() {
((ModelList) models).pauseNotifications();
}
private void resumeModelListNotifications() {
((ModelList) models).resumeNotifications();
}
}
| 8,948 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/BaseEpoxyAdapter.java | package com.airbnb.epoxy;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import com.airbnb.epoxy.stickyheader.StickyHeaderCallbacks;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup;
import androidx.recyclerview.widget.RecyclerView;
public abstract class BaseEpoxyAdapter
extends RecyclerView.Adapter<EpoxyViewHolder>
implements StickyHeaderCallbacks {
private static final String SAVED_STATE_ARG_VIEW_HOLDERS = "saved_state_view_holders";
private int spanCount = 1;
private final ViewTypeManager viewTypeManager = new ViewTypeManager();
/**
* Keeps track of view holders that are currently bound so we can save their state in {@link
* #onSaveInstanceState(Bundle)}.
*/
private final BoundViewHolders boundViewHolders = new BoundViewHolders();
private ViewHolderState viewHolderState = new ViewHolderState();
private final SpanSizeLookup spanSizeLookup = new SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
try {
return getModelForPosition(position)
.spanSize(spanCount, position, getItemCount());
} catch (IndexOutOfBoundsException e) {
// There seems to be a GridLayoutManager bug where when the user is in accessibility mode
// it incorrectly uses an outdated view position
// when calling this method. This crashes when a view is animating out, when it is
// removed from the adapter but technically still added
// to the layout. We've posted a bug report and hopefully can update when the support
// library fixes this
// TODO: (eli_hart 8/23/16) Figure out if this has been fixed in new support library
onExceptionSwallowed(e);
return 1;
}
}
};
public BaseEpoxyAdapter() {
// Defaults to stable ids since view models generate unique ids. Set this to false in the
// subclass if you don't want to support it
setHasStableIds(true);
spanSizeLookup.setSpanIndexCacheEnabled(true);
}
/**
* This is called when recoverable exceptions happen at runtime. They can be ignored and Epoxy
* will recover, but you can override this to be aware of when they happen.
*/
protected void onExceptionSwallowed(RuntimeException exception) {
}
@Override
public int getItemCount() {
return getCurrentModels().size();
}
/** Return the models currently being used by the adapter to populate the recyclerview. */
abstract List<? extends EpoxyModel<?>> getCurrentModels();
public boolean isEmpty() {
return getCurrentModels().isEmpty();
}
@Override
public long getItemId(int position) {
// This does not call getModelForPosition so that we don't use the id of the empty model when
// hidden,
// so that the id stays constant when gone vs shown
return getCurrentModels().get(position).id();
}
@Override
public int getItemViewType(int position) {
return viewTypeManager.getViewTypeAndRememberModel(getModelForPosition(position));
}
@Override
public EpoxyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
EpoxyModel<?> model = viewTypeManager.getModelForViewType(this, viewType);
View view = model.buildView(parent);
return new EpoxyViewHolder(parent, view, model.shouldSaveViewState());
}
@Override
public void onBindViewHolder(EpoxyViewHolder holder, int position) {
onBindViewHolder(holder, position, Collections.emptyList());
}
@Override
public void onBindViewHolder(EpoxyViewHolder holder, int position, List<Object> payloads) {
EpoxyModel<?> modelToShow = getModelForPosition(position);
EpoxyModel<?> previouslyBoundModel = null;
if (diffPayloadsEnabled()) {
previouslyBoundModel = DiffPayload.getModelFromPayload(payloads, getItemId(position));
}
holder.bind(modelToShow, previouslyBoundModel, payloads, position);
if (payloads.isEmpty()) {
// We only apply saved state to the view on initial bind, not on model updates.
// Since view state should be independent of model props, we should not need to apply state
// again in this case. This simplifies a rebind on update
viewHolderState.restore(holder);
}
boundViewHolders.put(holder);
if (diffPayloadsEnabled()) {
onModelBound(holder, modelToShow, position, previouslyBoundModel);
} else {
onModelBound(holder, modelToShow, position, payloads);
}
}
boolean diffPayloadsEnabled() {
return false;
}
/**
* Called immediately after a model is bound to a view holder. Subclasses can override this if
* they want alerts on when a model is bound.
*/
protected void onModelBound(EpoxyViewHolder holder, EpoxyModel<?> model, int position,
@Nullable List<Object> payloads) {
onModelBound(holder, model, position);
}
void onModelBound(EpoxyViewHolder holder, EpoxyModel<?> model, int position,
@Nullable EpoxyModel<?> previouslyBoundModel) {
onModelBound(holder, model, position);
}
/**
* Called immediately after a model is bound to a view holder. Subclasses can override this if
* they want alerts on when a model is bound.
*/
protected void onModelBound(EpoxyViewHolder holder, EpoxyModel<?> model, int position) {
}
/**
* Returns an object that manages the view holders currently bound to the RecyclerView. This
* object is mainly used by the base Epoxy adapter to save view states, but you may find it useful
* to help access views or models currently shown in the RecyclerView.
*/
protected BoundViewHolders getBoundViewHolders() {
return boundViewHolders;
}
EpoxyModel<?> getModelForPosition(int position) {
return getCurrentModels().get(position);
}
@Override
public void onViewRecycled(EpoxyViewHolder holder) {
viewHolderState.save(holder);
boundViewHolders.remove(holder);
EpoxyModel<?> model = holder.getModel();
holder.unbind();
onModelUnbound(holder, model);
}
@CallSuper
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
// The last model is saved for optimization, but holding onto it can leak anything saved inside
// the model (like a click listener that references a Fragment). This is only needed during
// the viewholder creation phase, so it is safe to clear now.
viewTypeManager.lastModelForViewTypeLookup = null;
}
/**
* Called immediately after a model is unbound from a view holder. Subclasses can override this if
* they want alerts on when a model is unbound.
*/
protected void onModelUnbound(EpoxyViewHolder holder, EpoxyModel<?> model) {
}
@CallSuper
@Override
public boolean onFailedToRecycleView(EpoxyViewHolder holder) {
//noinspection unchecked,rawtypes
return ((EpoxyModel) holder.getModel()).onFailedToRecycleView(holder.objectToBind());
}
@CallSuper
@Override
public void onViewAttachedToWindow(EpoxyViewHolder holder) {
//noinspection unchecked,rawtypes
((EpoxyModel) holder.getModel()).onViewAttachedToWindow(holder.objectToBind());
}
@CallSuper
@Override
public void onViewDetachedFromWindow(EpoxyViewHolder holder) {
//noinspection unchecked,rawtypes
((EpoxyModel) holder.getModel()).onViewDetachedFromWindow(holder.objectToBind());
}
public void onSaveInstanceState(Bundle outState) {
// Save the state of currently bound views first so they are included. Views that were
// scrolled off and unbound will already have had
// their state saved.
for (EpoxyViewHolder holder : boundViewHolders) {
viewHolderState.save(holder);
}
if (viewHolderState.size() > 0 && !hasStableIds()) {
throw new IllegalStateException("Must have stable ids when saving view holder state");
}
outState.putParcelable(SAVED_STATE_ARG_VIEW_HOLDERS, viewHolderState);
}
public void onRestoreInstanceState(@Nullable Bundle inState) {
// To simplify things we enforce that state is restored before views are bound, otherwise it
// is more difficult to update view state once they are bound
if (boundViewHolders.size() > 0) {
throw new IllegalStateException(
"State cannot be restored once views have been bound. It should be done before adding "
+ "the adapter to the recycler view.");
}
if (inState != null) {
viewHolderState = inState.getParcelable(SAVED_STATE_ARG_VIEW_HOLDERS);
if (viewHolderState == null) {
throw new IllegalStateException(
"Tried to restore instance state, but onSaveInstanceState was never called.");
}
}
}
/**
* Finds the position of the given model in the list. Doesn't use indexOf to avoid unnecessary
* equals() calls since we're looking for the same object instance.
*
* @return The position of the given model in the current models list, or -1 if the model can't be
* found.
*/
protected int getModelPosition(EpoxyModel<?> model) {
int size = getCurrentModels().size();
for (int i = 0; i < size; i++) {
if (model == getCurrentModels().get(i)) {
return i;
}
}
return -1;
}
/**
* For use with a grid layout manager - use this to get the {@link SpanSizeLookup} for models in
* this adapter. This will delegate span look up calls to each model's {@link
* EpoxyModel#getSpanSize(int, int, int)}. Make sure to also call {@link #setSpanCount(int)} so
* the span count is correct.
*/
public SpanSizeLookup getSpanSizeLookup() {
return spanSizeLookup;
}
/**
* If you are using a grid layout manager you must call this to set the span count of the grid.
* This span count will be passed on to the models so models can choose what span count to be.
*
* @see #getSpanSizeLookup()
* @see EpoxyModel#getSpanSize(int, int, int)
*/
public void setSpanCount(int spanCount) {
this.spanCount = spanCount;
}
public int getSpanCount() {
return spanCount;
}
public boolean isMultiSpan() {
return spanCount > 1;
}
//region Sticky header
/**
* Optional callback to setup the sticky view,
* by default it doesn't do anything.
* <p>
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public void setupStickyHeaderView(@NotNull View stickyHeader) {
// no-op
}
/**
* Optional callback to perform tear down operation on the
* sticky view, by default it doesn't do anything.
* <p>
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public void teardownStickyHeaderView(@NotNull View stickyHeader) {
// no-op
}
/**
* Called to check if the item at the position is a sticky item,
* by default returns false.
* <p>
* The sub-classes should override the function if they are
* using sticky header feature.
*/
@Override
public boolean isStickyHeader(int position) {
return false;
}
//endregion
}
| 8,949 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/DiffPayload.java | package com.airbnb.epoxy;
import java.util.Collections;
import java.util.List;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.LongSparseArray;
/**
* A helper class for tracking changed models found by the {@link com.airbnb.epoxy.DiffHelper} to
* be included as a payload in the
* {@link androidx.recyclerview.widget.RecyclerView.Adapter#notifyItemChanged(int, Object)}
* call.
*/
public class DiffPayload {
private final EpoxyModel<?> singleModel;
private final LongSparseArray<EpoxyModel<?>> modelsById;
DiffPayload(List<? extends EpoxyModel<?>> models) {
if (models.isEmpty()) {
throw new IllegalStateException("Models must not be empty");
}
int modelCount = models.size();
if (modelCount == 1) {
// Optimize for the common case of only one model changed.
singleModel = models.get(0);
modelsById = null;
} else {
singleModel = null;
modelsById = new LongSparseArray<>(modelCount);
for (EpoxyModel<?> model : models) {
modelsById.put(model.id(), model);
}
}
}
public DiffPayload(EpoxyModel<?> changedItem) {
this(Collections.singletonList(changedItem));
}
/**
* Looks through the payloads list and returns the first model found with the given model id. This
* assumes that the payloads list will only contain objects of type {@link DiffPayload}, and will
* throw if an unexpected type is found.
*/
@Nullable
public static EpoxyModel<?> getModelFromPayload(List<Object> payloads, long modelId) {
if (payloads.isEmpty()) {
return null;
}
for (Object payload : payloads) {
DiffPayload diffPayload = (DiffPayload) payload;
if (diffPayload.singleModel != null) {
if (diffPayload.singleModel.id() == modelId) {
return diffPayload.singleModel;
}
} else {
EpoxyModel<?> modelForId = diffPayload.modelsById.get(modelId);
if (modelForId != null) {
return modelForId;
}
}
}
return null;
}
@VisibleForTesting
boolean equalsForTesting(DiffPayload that) {
if (singleModel != null) {
return that.singleModel == singleModel;
}
int thisSize = modelsById.size();
int thatSize = that.modelsById.size();
if (thisSize != thatSize) {
return false;
}
for (int i = 0; i < thisSize; i++) {
long thisKey = modelsById.keyAt(i);
long thatKey = that.modelsById.keyAt(i);
if (thisKey != thatKey) {
return false;
}
EpoxyModel<?> thisModel = modelsById.valueAt(i);
EpoxyModel<?> thatModel = that.modelsById.valueAt(i);
if (thisModel != thatModel) {
return false;
}
}
return true;
}
}
| 8,950 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/StringAttributeData.java | package com.airbnb.epoxy;
import android.content.Context;
import java.util.Arrays;
import androidx.annotation.Nullable;
import androidx.annotation.PluralsRes;
import androidx.annotation.StringRes;
public class StringAttributeData {
private final boolean hasDefault;
@Nullable private final CharSequence defaultString;
@StringRes private final int defaultStringRes;
@Nullable private CharSequence string;
@StringRes private int stringRes;
@PluralsRes private int pluralRes;
private int quantity;
@Nullable private Object[] formatArgs;
public StringAttributeData() {
hasDefault = false;
defaultString = null;
defaultStringRes = 0;
}
public StringAttributeData(@Nullable CharSequence defaultString) {
hasDefault = true;
this.defaultString = defaultString;
string = defaultString;
defaultStringRes = 0;
}
public StringAttributeData(@StringRes int defaultStringRes) {
hasDefault = true;
this.defaultStringRes = defaultStringRes;
stringRes = defaultStringRes;
defaultString = null;
}
public void setValue(@Nullable CharSequence string) {
this.string = string;
stringRes = 0;
pluralRes = 0;
}
public void setValue(@StringRes int stringRes) {
setValue(stringRes, null);
}
public void setValue(@StringRes int stringRes, @Nullable Object[] formatArgs) {
if (stringRes != 0) {
this.stringRes = stringRes;
this.formatArgs = formatArgs;
string = null;
pluralRes = 0;
} else {
handleInvalidStringRes();
}
}
private void handleInvalidStringRes() {
if (hasDefault) {
if (defaultStringRes != 0) {
setValue(defaultStringRes);
} else {
setValue(defaultString);
}
} else {
throw new IllegalArgumentException("0 is an invalid value for required strings.");
}
}
public void setValue(@PluralsRes int pluralRes, int quantity, @Nullable Object[] formatArgs) {
if (pluralRes != 0) {
this.pluralRes = pluralRes;
this.quantity = quantity;
this.formatArgs = formatArgs;
string = null;
stringRes = 0;
} else {
handleInvalidStringRes();
}
}
public CharSequence toString(Context context) {
if (pluralRes != 0) {
if (formatArgs != null) {
return context.getResources().getQuantityString(pluralRes, quantity, formatArgs);
} else {
return context.getResources().getQuantityString(pluralRes, quantity);
}
} else if (stringRes != 0) {
if (formatArgs != null) {
return context.getResources().getString(stringRes, formatArgs);
} else {
return context.getResources().getText(stringRes);
}
} else {
return string;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof StringAttributeData)) {
return false;
}
StringAttributeData that = (StringAttributeData) o;
if (stringRes != that.stringRes) {
return false;
}
if (pluralRes != that.pluralRes) {
return false;
}
if (quantity != that.quantity) {
return false;
}
if (string != null ? !string.equals(that.string) : that.string != null) {
return false;
}
return Arrays.equals(formatArgs, that.formatArgs);
}
@Override
public int hashCode() {
int result = string != null ? string.hashCode() : 0;
result = 31 * result + stringRes;
result = 31 * result + pluralRes;
result = 31 * result + quantity;
result = 31 * result + Arrays.hashCode(formatArgs);
return result;
}
}
| 8,951 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/ModelList.java | package com.airbnb.epoxy;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import androidx.annotation.NonNull;
/**
* Used by our {@link EpoxyAdapter} to track models. It simply wraps ArrayList and notifies an
* observer when remove or insertion operations are done on the list. This allows us to optimize
* diffing since we have a knowledge of what changed in the list.
*/
class ModelList extends ArrayList<EpoxyModel<?>> {
ModelList(int expectedModelCount) {
super(expectedModelCount);
}
ModelList() {
}
interface ModelListObserver {
void onItemRangeInserted(int positionStart, int itemCount);
void onItemRangeRemoved(int positionStart, int itemCount);
}
private boolean notificationsPaused;
private ModelListObserver observer;
void pauseNotifications() {
if (notificationsPaused) {
throw new IllegalStateException("Notifications already paused");
}
notificationsPaused = true;
}
void resumeNotifications() {
if (!notificationsPaused) {
throw new IllegalStateException("Notifications already resumed");
}
notificationsPaused = false;
}
void setObserver(ModelListObserver observer) {
this.observer = observer;
}
private void notifyInsertion(int positionStart, int itemCount) {
if (!notificationsPaused && observer != null) {
observer.onItemRangeInserted(positionStart, itemCount);
}
}
private void notifyRemoval(int positionStart, int itemCount) {
if (!notificationsPaused && observer != null) {
observer.onItemRangeRemoved(positionStart, itemCount);
}
}
@Override
public EpoxyModel<?> set(int index, EpoxyModel<?> element) {
EpoxyModel<?> previousModel = super.set(index, element);
if (previousModel.id() != element.id()) {
notifyRemoval(index, 1);
notifyInsertion(index, 1);
}
return previousModel;
}
@Override
public boolean add(EpoxyModel<?> epoxyModel) {
notifyInsertion(size(), 1);
return super.add(epoxyModel);
}
@Override
public void add(int index, EpoxyModel<?> element) {
notifyInsertion(index, 1);
super.add(index, element);
}
@Override
public boolean addAll(Collection<? extends EpoxyModel<?>> c) {
notifyInsertion(size(), c.size());
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends EpoxyModel<?>> c) {
notifyInsertion(index, c.size());
return super.addAll(index, c);
}
@Override
public EpoxyModel<?> remove(int index) {
notifyRemoval(index, 1);
return super.remove(index);
}
@Override
public boolean remove(Object o) {
int index = indexOf(o);
if (index == -1) {
return false;
}
notifyRemoval(index, 1);
super.remove(index);
return true;
}
@Override
public void clear() {
if (!isEmpty()) {
notifyRemoval(0, size());
super.clear();
}
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
if (fromIndex == toIndex) {
return;
}
notifyRemoval(fromIndex, toIndex - fromIndex);
super.removeRange(fromIndex, toIndex);
}
@Override
public boolean removeAll(Collection<?> collection) {
// Using this implementation from the Android ArrayList since the Java 1.8 ArrayList
// doesn't call through to remove. Calling through to remove lets us leverage the notification
// done there
boolean result = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (collection.contains(it.next())) {
it.remove();
result = true;
}
}
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
// Using this implementation from the Android ArrayList since the Java 1.8 ArrayList
// doesn't call through to remove. Calling through to remove lets us leverage the notification
// done there
boolean result = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (!collection.contains(it.next())) {
it.remove();
result = true;
}
}
return result;
}
@NonNull
@Override
public Iterator<EpoxyModel<?>> iterator() {
return new Itr();
}
/**
* An Iterator implementation that calls through to the parent list's methods for modification.
* Some implementations, like the Android ArrayList.ArrayListIterator class, modify the list data
* directly instead of calling into the parent list's methods. We need the implementation to call
* the parent methods so that the proper notifications are done.
*/
private class Itr implements Iterator<EpoxyModel<?>> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
@SuppressWarnings("unchecked")
public EpoxyModel<?> next() {
checkForComodification();
int i = cursor;
cursor = i + 1;
lastRet = i;
return ModelList.this.get(i);
}
public void remove() {
if (lastRet < 0) {
throw new IllegalStateException();
}
checkForComodification();
try {
ModelList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
@NonNull
@Override
public ListIterator<EpoxyModel<?>> listIterator() {
return new ListItr(0);
}
@NonNull
@Override
public ListIterator<EpoxyModel<?>> listIterator(int index) {
return new ListItr(index);
}
/**
* A ListIterator implementation that calls through to the parent list's methods for modification.
* Some implementations may modify the list data directly instead of calling into the parent
* list's methods. We need the implementation to call the parent methods so that the proper
* notifications are done.
*/
private class ListItr extends Itr implements ListIterator<EpoxyModel<?>> {
ListItr(int index) {
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public EpoxyModel<?> previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0) {
throw new NoSuchElementException();
}
cursor = i;
lastRet = i;
return ModelList.this.get(i);
}
public void set(EpoxyModel<?> e) {
if (lastRet < 0) {
throw new IllegalStateException();
}
checkForComodification();
try {
ModelList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(EpoxyModel<?> e) {
checkForComodification();
try {
int i = cursor;
ModelList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
@NonNull
@Override
public List<EpoxyModel<?>> subList(int start, int end) {
if (start >= 0 && end <= size()) {
if (start <= end) {
return new SubList(this, start, end);
}
throw new IllegalArgumentException();
}
throw new IndexOutOfBoundsException();
}
/**
* A SubList implementation from Android's AbstractList class. It's copied here to make sure the
* implementation doesn't change, since some implementations, like the Java 1.8 ArrayList.SubList
* class, modify the list data directly instead of calling into the parent list's methods. We need
* the implementation to call the parent methods so that the proper notifications are done.
*/
private static class SubList extends AbstractList<EpoxyModel<?>> {
private final ModelList fullList;
private int offset;
private int size;
private static final class SubListIterator implements ListIterator<EpoxyModel<?>> {
private final SubList subList;
private final ListIterator<EpoxyModel<?>> iterator;
private int start;
private int end;
SubListIterator(ListIterator<EpoxyModel<?>> it, SubList list, int offset, int length) {
iterator = it;
subList = list;
start = offset;
end = start + length;
}
public void add(EpoxyModel<?> object) {
iterator.add(object);
subList.sizeChanged(true);
end++;
}
public boolean hasNext() {
return iterator.nextIndex() < end;
}
public boolean hasPrevious() {
return iterator.previousIndex() >= start;
}
public EpoxyModel<?> next() {
if (iterator.nextIndex() < end) {
return iterator.next();
}
throw new NoSuchElementException();
}
public int nextIndex() {
return iterator.nextIndex() - start;
}
public EpoxyModel<?> previous() {
if (iterator.previousIndex() >= start) {
return iterator.previous();
}
throw new NoSuchElementException();
}
public int previousIndex() {
int previous = iterator.previousIndex();
if (previous >= start) {
return previous - start;
}
return -1;
}
public void remove() {
iterator.remove();
subList.sizeChanged(false);
end--;
}
public void set(EpoxyModel<?> object) {
iterator.set(object);
}
}
SubList(ModelList list, int start, int end) {
fullList = list;
modCount = fullList.modCount;
offset = start;
size = end - start;
}
@Override
public void add(int location, EpoxyModel<?> object) {
if (modCount == fullList.modCount) {
if (location >= 0 && location <= size) {
fullList.add(location + offset, object);
size++;
modCount = fullList.modCount;
} else {
throw new IndexOutOfBoundsException();
}
} else {
throw new ConcurrentModificationException();
}
}
@Override
public boolean addAll(int location, Collection<? extends EpoxyModel<?>> collection) {
if (modCount == fullList.modCount) {
if (location >= 0 && location <= size) {
boolean result = fullList.addAll(location + offset, collection);
if (result) {
size += collection.size();
modCount = fullList.modCount;
}
return result;
}
throw new IndexOutOfBoundsException();
}
throw new ConcurrentModificationException();
}
@Override
public boolean addAll(@NonNull Collection<? extends EpoxyModel<?>> collection) {
if (modCount == fullList.modCount) {
boolean result = fullList.addAll(offset + size, collection);
if (result) {
size += collection.size();
modCount = fullList.modCount;
}
return result;
}
throw new ConcurrentModificationException();
}
@Override
public EpoxyModel<?> get(int location) {
if (modCount == fullList.modCount) {
if (location >= 0 && location < size) {
return fullList.get(location + offset);
}
throw new IndexOutOfBoundsException();
}
throw new ConcurrentModificationException();
}
@NonNull
@Override
public Iterator<EpoxyModel<?>> iterator() {
return listIterator(0);
}
@NonNull
@Override
public ListIterator<EpoxyModel<?>> listIterator(int location) {
if (modCount == fullList.modCount) {
if (location >= 0 && location <= size) {
return new SubListIterator(fullList.listIterator(location + offset), this, offset, size);
}
throw new IndexOutOfBoundsException();
}
throw new ConcurrentModificationException();
}
@Override
public EpoxyModel<?> remove(int location) {
if (modCount == fullList.modCount) {
if (location >= 0 && location < size) {
EpoxyModel<?> result = fullList.remove(location + offset);
size--;
modCount = fullList.modCount;
return result;
}
throw new IndexOutOfBoundsException();
}
throw new ConcurrentModificationException();
}
@Override
protected void removeRange(int start, int end) {
if (start != end) {
if (modCount == fullList.modCount) {
fullList.removeRange(start + offset, end + offset);
size -= end - start;
modCount = fullList.modCount;
} else {
throw new ConcurrentModificationException();
}
}
}
@Override
public EpoxyModel<?> set(int location, EpoxyModel<?> object) {
if (modCount == fullList.modCount) {
if (location >= 0 && location < size) {
return fullList.set(location + offset, object);
}
throw new IndexOutOfBoundsException();
}
throw new ConcurrentModificationException();
}
@Override
public int size() {
if (modCount == fullList.modCount) {
return size;
}
throw new ConcurrentModificationException();
}
void sizeChanged(boolean increment) {
if (increment) {
size++;
} else {
size--;
}
modCount = fullList.modCount;
}
}
}
| 8,952 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelCheckedChangeListener.java | package com.airbnb.epoxy;
import android.widget.CompoundButton;
public interface OnModelCheckedChangeListener<T extends EpoxyModel<?>, V> {
/**
* Called when the view bound to the model is checked.
*
* @param model The model that the view is bound to.
* @param parentView The view bound to the model which received the click.
* @param checkedView The view that received the click. This is either a child of the parentView
* or the parentView itself
* @param isChecked The new value for isChecked property.
* @param position The position of the model in the adapter.
*/
void onChecked(T model, V parentView,
CompoundButton checkedView, boolean isChecked, int position);
}
| 8,953 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyControllerAdapter.java | package com.airbnb.epoxy;
import android.os.Handler;
import android.view.View;
import com.airbnb.epoxy.AsyncEpoxyDiffer.ResultCallback;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.recyclerview.widget.DiffUtil.ItemCallback;
import androidx.recyclerview.widget.RecyclerView;
public final class EpoxyControllerAdapter extends BaseEpoxyAdapter implements ResultCallback {
private final NotifyBlocker notifyBlocker = new NotifyBlocker();
private final AsyncEpoxyDiffer differ;
private final EpoxyController epoxyController;
private int itemCount;
private final List<OnModelBuildFinishedListener> modelBuildListeners = new ArrayList<>();
EpoxyControllerAdapter(@NonNull EpoxyController epoxyController, Handler diffingHandler) {
this.epoxyController = epoxyController;
differ = new AsyncEpoxyDiffer(
diffingHandler,
this,
ITEM_CALLBACK
);
registerAdapterDataObserver(notifyBlocker);
}
@Override
protected void onExceptionSwallowed(@NonNull RuntimeException exception) {
epoxyController.onExceptionSwallowed(exception);
}
@NonNull
@Override
List<? extends EpoxyModel<?>> getCurrentModels() {
return differ.getCurrentList();
}
@Override
public int getItemCount() {
// RecyclerView calls this A LOT. The base class implementation does
// getCurrentModels().size() which adds some overhead because of the method calls.
// We can easily memoize this, which seems to help when there are lots of models.
return itemCount;
}
/** This is set from whatever thread model building happened on, so must be thread safe. */
void setModels(@NonNull ControllerModelList models) {
// If debug model validations are on then we should help detect the error case where models
// were incorrectly mutated once they were added. That check is also done before and after
// bind, but there is no other check after that to see if a model is incorrectly
// mutated after being bound.
// If a data class inside a model is mutated, then when models are rebuilt the differ
// will still recognize the old and new models as equal, even though the old model was changed.
// To help catch that error case we check for mutations here, before running the differ.
//
// https://github.com/airbnb/epoxy/issues/805
List<? extends EpoxyModel<?>> currentModels = getCurrentModels();
if (!currentModels.isEmpty() && currentModels.get(0).isDebugValidationEnabled()) {
for (int i = 0; i < currentModels.size(); i++) {
EpoxyModel<?> model = currentModels.get(i);
model.validateStateHasNotChangedSinceAdded(
"The model was changed between being bound and when models were rebuilt",
i
);
}
}
differ.submitList(models);
}
/**
* @return True if a diff operation is in progress.
*/
public boolean isDiffInProgress() {
return differ.isDiffInProgress();
}
// Called on diff results from the differ
@Override
public void onResult(@NonNull DiffResult result) {
itemCount = result.newModels.size();
notifyBlocker.allowChanges();
result.dispatchTo(this);
notifyBlocker.blockChanges();
for (int i = modelBuildListeners.size() - 1; i >= 0; i--) {
modelBuildListeners.get(i).onModelBuildFinished(result);
}
}
public void addModelBuildListener(OnModelBuildFinishedListener listener) {
modelBuildListeners.add(listener);
}
public void removeModelBuildListener(OnModelBuildFinishedListener listener) {
modelBuildListeners.remove(listener);
}
@Override
boolean diffPayloadsEnabled() {
return true;
}
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
epoxyController.onAttachedToRecyclerViewInternal(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
epoxyController.onDetachedFromRecyclerViewInternal(recyclerView);
}
@Override
public void onViewAttachedToWindow(@NonNull EpoxyViewHolder holder) {
super.onViewAttachedToWindow(holder);
epoxyController.onViewAttachedToWindow(holder, holder.getModel());
}
@Override
public void onViewDetachedFromWindow(@NonNull EpoxyViewHolder holder) {
super.onViewDetachedFromWindow(holder);
epoxyController.onViewDetachedFromWindow(holder, holder.getModel());
}
@Override
protected void onModelBound(@NonNull EpoxyViewHolder holder, @NonNull EpoxyModel<?> model,
int position, @Nullable EpoxyModel<?> previouslyBoundModel) {
epoxyController.onModelBound(holder, model, position, previouslyBoundModel);
}
@Override
protected void onModelUnbound(@NonNull EpoxyViewHolder holder, @NonNull EpoxyModel<?> model) {
epoxyController.onModelUnbound(holder, model);
}
/** Get an unmodifiable copy of the current models set on the adapter. */
@NonNull
public List<EpoxyModel<?>> getCopyOfModels() {
//noinspection unchecked
return (List<EpoxyModel<?>>) getCurrentModels();
}
/**
* @throws IndexOutOfBoundsException If the given position is out of range of the current model
* list.
*/
@NonNull
public EpoxyModel<?> getModelAtPosition(int position) {
return getCurrentModels().get(position);
}
/**
* Searches the current model list for the model with the given id. Returns the matching model if
* one is found, otherwise null is returned.
*/
@Nullable
public EpoxyModel<?> getModelById(long id) {
for (EpoxyModel<?> model : getCurrentModels()) {
if (model.id() == id) {
return model;
}
}
return null;
}
@Override
public int getModelPosition(@NonNull EpoxyModel<?> targetModel) {
int size = getCurrentModels().size();
for (int i = 0; i < size; i++) {
EpoxyModel<?> model = getCurrentModels().get(i);
if (model.id() == targetModel.id()) {
return i;
}
}
return -1;
}
@NonNull
@Override
public BoundViewHolders getBoundViewHolders() {
return super.getBoundViewHolders();
}
@UiThread
void moveModel(int fromPosition, int toPosition) {
ArrayList<EpoxyModel<?>> updatedList = new ArrayList<>(getCurrentModels());
updatedList.add(toPosition, updatedList.remove(fromPosition));
notifyBlocker.allowChanges();
notifyItemMoved(fromPosition, toPosition);
notifyBlocker.blockChanges();
boolean interruptedDiff = differ.forceListOverride(updatedList);
if (interruptedDiff) {
// The move interrupted a model rebuild/diff that was in progress,
// so models may be out of date and we should force them to rebuilt
epoxyController.requestModelBuild();
}
}
@UiThread
void notifyModelChanged(int position) {
ArrayList<EpoxyModel<?>> updatedList = new ArrayList<>(getCurrentModels());
notifyBlocker.allowChanges();
notifyItemChanged(position);
notifyBlocker.blockChanges();
boolean interruptedDiff = differ.forceListOverride(updatedList);
if (interruptedDiff) {
// The move interrupted a model rebuild/diff that was in progress,
// so models may be out of date and we should force them to rebuilt
epoxyController.requestModelBuild();
}
}
private static final ItemCallback<EpoxyModel<?>> ITEM_CALLBACK =
new ItemCallback<EpoxyModel<?>>() {
@Override
public boolean areItemsTheSame(EpoxyModel<?> oldItem, EpoxyModel<?> newItem) {
return oldItem.id() == newItem.id();
}
@Override
public boolean areContentsTheSame(EpoxyModel<?> oldItem, EpoxyModel<?> newItem) {
return oldItem.equals(newItem);
}
@Override
public Object getChangePayload(EpoxyModel<?> oldItem, EpoxyModel<?> newItem) {
return new DiffPayload(oldItem);
}
};
/**
* Delegates the callbacks received in the adapter
* to the controller.
*/
@Override
public boolean isStickyHeader(int position) {
return epoxyController.isStickyHeader(position);
}
/**
* Delegates the callbacks received in the adapter
* to the controller.
*/
@Override
public void setupStickyHeaderView(@NotNull View stickyHeader) {
epoxyController.setupStickyHeaderView(stickyHeader);
}
/**
* Delegates the callbacks received in the adapter
* to the controller.
*/
@Override
public void teardownStickyHeaderView(@NotNull View stickyHeader) {
epoxyController.teardownStickyHeaderView(stickyHeader);
}
}
| 8,954 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/SimpleEpoxyController.java | package com.airbnb.epoxy;
import java.util.List;
/**
* A small wrapper around {@link com.airbnb.epoxy.EpoxyController} that lets you set a list of
* models directly.
*/
public class SimpleEpoxyController extends EpoxyController {
private List<? extends EpoxyModel<?>> currentModels;
private boolean insideSetModels;
/**
* Set the models to add to this controller. Clears any previous models and adds this new list
* .
*/
public void setModels(List<? extends EpoxyModel<?>> models) {
currentModels = models;
insideSetModels = true;
requestModelBuild();
insideSetModels = false;
}
@Override
public final void requestModelBuild() {
if (!insideSetModels) {
throw new IllegalEpoxyUsage(
"You cannot call `requestModelBuild` directly. Call `setModels` instead.");
}
super.requestModelBuild();
}
@Override
protected final void buildModels() {
if (!isBuildingModels()) {
throw new IllegalEpoxyUsage(
"You cannot call `buildModels` directly. Call `setModels` instead.");
}
add(currentModels);
}
}
| 8,955 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/NotifyBlocker.java | package com.airbnb.epoxy;
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver;
/**
* We don't allow any data change notifications except the ones done though diffing. Forcing
* changes to happen through diffing reduces the chance for developer error when implementing an
* adapter.
* <p>
* This observer throws upon any changes done outside of diffing.
*/
class NotifyBlocker extends AdapterDataObserver {
private boolean changesAllowed;
void allowChanges() {
changesAllowed = true;
}
void blockChanges() {
changesAllowed = false;
}
@Override
public void onChanged() {
if (!changesAllowed) {
throw new IllegalStateException(
"You cannot notify item changes directly. Call `requestModelBuild` instead.");
}
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
onChanged();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
onChanged();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
onChanged();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
onChanged();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
onChanged();
}
}
| 8,956 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyModelGroup.java | package com.airbnb.epoxy;
import android.view.View;
import android.view.ViewParent;
import android.view.ViewStub;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* An {@link EpoxyModel} that contains other models, and allows you to combine those models in
* whatever view configuration you want.
* <p>
* The constructors take a list of models and a layout resource. The layout must have a viewgroup as
* its top level view; it determines how the view of each model is laid out. There are two ways to
* specify this
* <p>
* 1. Leave the viewgroup empty. The view for each model will be inflated and added in order. This
* works fine if you don't need to include any other views, your model views don't need their layout
* params changed, and your views don't need ids (eg for saving state).
* <p>
* Alternatively you can have nested view groups, with the innermost viewgroup given the id
* "epoxy_model_group_child_container" to mark it as the viewgroup that should have the model views
* added to it. The viewgroup marked with this id should be empty. This allows you to nest
* viewgroups, such as a LinearLayout inside of a CardView.
* <p>
* 2. Include a {@link ViewStub} for each of the models in the list. There should be at least as
* many view stubs as models. Extra stubs will be ignored. Each model will have its view replace the
* stub in order of the view stub's position in the view group. That is, the view group's children
* will be iterated through in order. The first view stub found will be used for the first model in
* the models list, the second view stub will be used for the second model, and so on. A depth first
* recursive search through nested viewgroups is done to find these viewstubs.
* <p>
* The layout can be of any ViewGroup subclass, and can have arbitrary other child views besides the
* view stubs. It can arrange the views and view stubs however is needed.
* <p>
* Any layout param options set on the view stubs will be transferred to the corresponding model
* view by default. If you want a model to keep the layout params from it's own layout resource you
* can override {@link #useViewStubLayoutParams(EpoxyModel, int)}
* <p>
* If you want to override the id used for a model's view you can set {@link
* ViewStub#setInflatedId(int)} via xml. That id will be transferred over to the view taking that
* stub's place. This is necessary if you want your model to save view state, since without this the
* model's view won't have an id to associate the saved state with.
* <p>
* By default this model inherits the same id as the first model in the list. Call {@link #id(long)}
* to override that if needed.
* <p>
* When a model group is recycled, its child views are automatically recycled to a pool that is
* shared with all other model groups in the activity. This enables model groups to more efficiently
* manage their children. The shared pool is cleaned up when the activity is destroyed.
*/
@SuppressWarnings("rawtypes")
public class EpoxyModelGroup extends EpoxyModelWithHolder<ModelGroupHolder> {
protected final List<EpoxyModel<?>> models;
private boolean shouldSaveViewStateDefault = false;
@Nullable
private Boolean shouldSaveViewState = null;
/**
* @param layoutRes The layout to use with these models.
* @param models The models that will be used to bind the views in the given layout.
*/
public EpoxyModelGroup(@LayoutRes int layoutRes, Collection<? extends EpoxyModel<?>> models) {
this(layoutRes, new ArrayList<>(models));
}
/**
* @param layoutRes The layout to use with these models.
* @param models The models that will be used to bind the views in the given layout.
*/
public EpoxyModelGroup(@LayoutRes int layoutRes, EpoxyModel<?>... models) {
this(layoutRes, new ArrayList<>(Arrays.asList(models)));
}
/**
* @param layoutRes The layout to use with these models.
* @param models The models that will be used to bind the views in the given layout.
*/
private EpoxyModelGroup(@LayoutRes int layoutRes, List<EpoxyModel<?>> models) {
if (models.isEmpty()) {
throw new IllegalArgumentException("Models cannot be empty");
}
this.models = models;
layout(layoutRes);
id(models.get(0).id());
boolean saveState = false;
for (EpoxyModel<?> model : models) {
if (model.shouldSaveViewState()) {
saveState = true;
break;
}
}
// By default we save view state if any of the models need to save state.
shouldSaveViewStateDefault = saveState;
}
/**
* Constructor use for DSL
*/
protected EpoxyModelGroup() {
models = new ArrayList<>();
shouldSaveViewStateDefault = false;
}
/**
* Constructor use for DSL
*/
protected EpoxyModelGroup(@LayoutRes int layoutRes) {
this();
layout(layoutRes);
}
protected void addModel(@NonNull EpoxyModel<?> model) {
// By default we save view state if any of the models need to save state.
shouldSaveViewStateDefault |= model.shouldSaveViewState();
models.add(model);
}
@CallSuper
@Override
public void bind(@NonNull ModelGroupHolder holder) {
iterateModels(holder, new IterateModelsCallback() {
@Override
public void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex) {
setViewVisibility(model, viewHolder);
viewHolder.bind(model, null, Collections.emptyList(), modelIndex);
}
});
}
@CallSuper
@Override
public void bind(@NonNull ModelGroupHolder holder, @NonNull final List<Object> payloads) {
iterateModels(holder, new IterateModelsCallback() {
@Override
public void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex) {
setViewVisibility(model, viewHolder);
viewHolder.bind(model, null, Collections.emptyList(), modelIndex);
}
});
}
@Override
public void bind(@NonNull ModelGroupHolder holder, @NonNull EpoxyModel<?> previouslyBoundModel) {
if (!(previouslyBoundModel instanceof EpoxyModelGroup)) {
bind(holder);
return;
}
final EpoxyModelGroup previousGroup = (EpoxyModelGroup) previouslyBoundModel;
iterateModels(holder, new IterateModelsCallback() {
@Override
public void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex) {
setViewVisibility(model, viewHolder);
if (modelIndex < previousGroup.models.size()) {
EpoxyModel<?> previousModel = previousGroup.models.get(modelIndex);
if (previousModel.id() == model.id()) {
viewHolder.bind(model, previousModel, Collections.emptyList(), modelIndex);
return;
}
}
viewHolder.bind(model, null, Collections.emptyList(), modelIndex);
}
});
}
private static void setViewVisibility(EpoxyModel model, EpoxyViewHolder viewHolder) {
if (model.isShown()) {
viewHolder.itemView.setVisibility(View.VISIBLE);
} else {
viewHolder.itemView.setVisibility(View.GONE);
}
}
@CallSuper
@Override
public void unbind(@NonNull ModelGroupHolder holder) {
holder.unbindGroup();
}
@CallSuper
@Override
public void onViewAttachedToWindow(ModelGroupHolder holder) {
iterateModels(holder, new IterateModelsCallback() {
@Override
public void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex) {
//noinspection unchecked
model.onViewAttachedToWindow(viewHolder.objectToBind());
}
});
}
@CallSuper
@Override
public void onViewDetachedFromWindow(ModelGroupHolder holder) {
iterateModels(holder, new IterateModelsCallback() {
@Override
public void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex) {
//noinspection unchecked
model.onViewDetachedFromWindow(viewHolder.objectToBind());
}
});
}
private void iterateModels(ModelGroupHolder holder, IterateModelsCallback callback) {
holder.bindGroupIfNeeded(this);
int modelCount = models.size();
for (int i = 0; i < modelCount; i++) {
callback.onModel(models.get(i), holder.getViewHolders().get(i), i);
}
}
private interface IterateModelsCallback {
void onModel(EpoxyModel model, EpoxyViewHolder viewHolder, int modelIndex);
}
@Override
public int getSpanSize(int totalSpanCount, int position, int itemCount) {
// Defaults to using the span size of the first model. Override this if you need to customize it
return models.get(0).spanSize(totalSpanCount, position, itemCount);
}
@Override
protected final int getDefaultLayout() {
throw new UnsupportedOperationException(
"You should set a layout with layout(...) instead of using this.");
}
@NonNull
public EpoxyModelGroup shouldSaveViewState(boolean shouldSaveViewState) {
onMutation();
this.shouldSaveViewState = shouldSaveViewState;
return this;
}
@Override
public boolean shouldSaveViewState() {
// By default state is saved if any of the models have saved state enabled.
// Override this if you need custom behavior.
if (shouldSaveViewState != null) {
return shouldSaveViewState;
} else {
return shouldSaveViewStateDefault;
}
}
/**
* Whether the layout params set on the view stub for the given model should be carried over to
* the model's view. Default is true
* <p>
* Set this to false if you want the layout params on the model's layout resource to be kept.
*
* @param model The model who's view is being created
* @param modelPosition The position of the model in the models list
*/
protected boolean useViewStubLayoutParams(EpoxyModel<?> model, int modelPosition) {
return true;
}
@Override
protected final ModelGroupHolder createNewHolder(@NonNull ViewParent parent) {
return new ModelGroupHolder(parent);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EpoxyModelGroup)) {
return false;
}
if (!super.equals(o)) {
return false;
}
EpoxyModelGroup that = (EpoxyModelGroup) o;
return models.equals(that.models);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + models.hashCode();
return result;
}
}
| 8,957 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyItemSpacingDecorator.java | package com.airbnb.epoxy;
import android.graphics.Rect;
import android.view.View;
import androidx.annotation.Px;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;
import androidx.recyclerview.widget.RecyclerView.State;
/**
* Modifies item spacing in a recycler view so that items are equally spaced no matter where they
* are on the grid. Only designed to work with standard linear or grid layout managers.
*/
public class EpoxyItemSpacingDecorator extends RecyclerView.ItemDecoration {
private int pxBetweenItems;
private boolean verticallyScrolling;
private boolean horizontallyScrolling;
private boolean firstItem;
private boolean lastItem;
private boolean grid;
private boolean isFirstItemInRow;
private boolean fillsLastSpan;
private boolean isInFirstRow;
private boolean isInLastRow;
public EpoxyItemSpacingDecorator() {
this(0);
}
public EpoxyItemSpacingDecorator(@Px int pxBetweenItems) {
setPxBetweenItems(pxBetweenItems);
}
public void setPxBetweenItems(@Px int pxBetweenItems) {
this.pxBetweenItems = pxBetweenItems;
}
@Px
public int getPxBetweenItems() {
return pxBetweenItems;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
// Zero everything out for the common case
outRect.setEmpty();
int position = parent.getChildAdapterPosition(view);
if (position == RecyclerView.NO_POSITION) {
// View is not shown
return;
}
RecyclerView.LayoutManager layout = parent.getLayoutManager();
calculatePositionDetails(parent, position, layout);
boolean left = useLeftPadding();
boolean right = useRightPadding();
boolean top = useTopPadding();
boolean bottom = useBottomPadding();
if (shouldReverseLayout(layout, horizontallyScrolling)) {
if (horizontallyScrolling) {
boolean temp = left;
left = right;
right = temp;
} else {
boolean temp = top;
top = bottom;
bottom = temp;
}
}
// Divided by two because it is applied to the left side of one item and the right of another
// to add up to the total desired space
int padding = pxBetweenItems / 2;
outRect.right = right ? padding : 0;
outRect.left = left ? padding : 0;
outRect.top = top ? padding : 0;
outRect.bottom = bottom ? padding : 0;
}
private void calculatePositionDetails(RecyclerView parent, int position, LayoutManager layout) {
int itemCount = parent.getAdapter().getItemCount();
firstItem = position == 0;
lastItem = position == itemCount - 1;
horizontallyScrolling = layout.canScrollHorizontally();
verticallyScrolling = layout.canScrollVertically();
grid = layout instanceof GridLayoutManager;
if (grid) {
GridLayoutManager grid = (GridLayoutManager) layout;
final SpanSizeLookup spanSizeLookup = grid.getSpanSizeLookup();
int spanSize = spanSizeLookup.getSpanSize(position);
int spanCount = grid.getSpanCount();
int spanIndex = spanSizeLookup.getSpanIndex(position, spanCount);
isFirstItemInRow = spanIndex == 0;
fillsLastSpan = spanIndex + spanSize == spanCount;
isInFirstRow = isInFirstRow(position, spanSizeLookup, spanCount);
isInLastRow =
!isInFirstRow && isInLastRow(position, itemCount, spanSizeLookup, spanCount);
}
}
private static boolean shouldReverseLayout(LayoutManager layout, boolean horizontallyScrolling) {
boolean reverseLayout =
layout instanceof LinearLayoutManager && ((LinearLayoutManager) layout).getReverseLayout();
boolean rtl = layout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL;
if (horizontallyScrolling && rtl) {
// This is how linearlayout checks if it should reverse layout in #resolveShouldLayoutReverse
reverseLayout = !reverseLayout;
}
return reverseLayout;
}
private boolean useBottomPadding() {
if (grid) {
return (horizontallyScrolling && !fillsLastSpan)
|| (verticallyScrolling && !isInLastRow);
}
return verticallyScrolling && !lastItem;
}
private boolean useTopPadding() {
if (grid) {
return (horizontallyScrolling && !isFirstItemInRow)
|| (verticallyScrolling && !isInFirstRow);
}
return verticallyScrolling && !firstItem;
}
private boolean useRightPadding() {
if (grid) {
return (horizontallyScrolling && !isInLastRow)
|| (verticallyScrolling && !fillsLastSpan);
}
return horizontallyScrolling && !lastItem;
}
private boolean useLeftPadding() {
if (grid) {
return (horizontallyScrolling && !isInFirstRow)
|| (verticallyScrolling && !isFirstItemInRow);
}
return horizontallyScrolling && !firstItem;
}
private static boolean isInFirstRow(int position, SpanSizeLookup spanSizeLookup, int spanCount) {
int totalSpan = 0;
for (int i = 0; i <= position; i++) {
totalSpan += spanSizeLookup.getSpanSize(i);
if (totalSpan > spanCount) {
return false;
}
}
return true;
}
private static boolean isInLastRow(int position, int itemCount, SpanSizeLookup spanSizeLookup,
int spanCount) {
int totalSpan = 0;
for (int i = itemCount - 1; i >= position; i--) {
totalSpan += spanSizeLookup.getSpanSize(i);
if (totalSpan > spanCount) {
return false;
}
}
return true;
}
}
| 8,958 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxySwipeCallback.java | package com.airbnb.epoxy;
import android.graphics.Canvas;
import android.view.View;
import androidx.recyclerview.widget.ItemTouchHelper;
/**
* For use with {@link EpoxyModelTouchCallback}
*/
public interface EpoxySwipeCallback<T extends EpoxyModel> extends BaseEpoxyTouchCallback<T> {
/**
* Called when the view switches from an idle state to a swiped state, as the user begins a swipe
* interaction with it. You can use this callback to modify the view to indicate it is being
* swiped.
* <p>
* This is the first callback made in the lifecycle of a swipe event.
*
* @param model The model representing the view that is being swiped
* @param itemView The view that is being swiped
* @param adapterPosition The adapter position of the model
*/
void onSwipeStarted(T model, View itemView, int adapterPosition);
/**
* Once a view has begun swiping with {@link #onSwipeStarted(EpoxyModel, View, int)} it will
* receive this callback as the swipe distance changes. This can be called multiple times as the
* swipe interaction progresses.
*
* @param model The model representing the view that is being swiped
* @param itemView The view that is being swiped
* @param swipeProgress A float from -1 to 1 representing the percentage that the view has been
* swiped relative to its width. This will be positive if the view is being
* swiped to the right and negative if it is swiped to the left. For
* example,
* @param canvas The canvas on which RecyclerView is drawing its children. You can draw to
* this to support custom swipe animations.
*/
void onSwipeProgressChanged(T model, View itemView, float swipeProgress,
Canvas canvas);
/**
* Called when the user has released their touch on the view. If the displacement passed the swipe
* threshold then {@link #onSwipeCompleted(EpoxyModel, View, int, int)} will be called after this
* and the view will be animated off screen. Otherwise the view will animate back to its original
* position.
*
* @param model The model representing the view that was being swiped
* @param itemView The view that was being swiped
*/
void onSwipeReleased(T model, View itemView);
/**
* Called after {@link #onSwipeReleased(EpoxyModel, View)} if the swipe surpassed the threshold to
* be considered a full swipe. The view will now be animated off screen.
* <p>
* You MUST use this callback to remove this item from your backing data and request a model
* update.
* <p>
* {@link #clearView(EpoxyModel, View)} will be called after this.
*
* @param model The model representing the view that was being swiped
* @param itemView The view that was being swiped
* @param position The adapter position of the model
* @param direction The direction that the view was swiped. Can be any of {@link
* ItemTouchHelper#LEFT}, {@link ItemTouchHelper#RIGHT}, {@link
* ItemTouchHelper#UP}, {@link ItemTouchHelper#DOWN} depending on what swipe
* directions were enabled.
*/
void onSwipeCompleted(T model, View itemView, int position, int direction);
}
| 8,959 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/DebugTimer.java | package com.airbnb.epoxy;
import android.util.Log;
class DebugTimer implements Timer {
private final String tag;
private long startTime;
private String sectionName;
DebugTimer(String tag) {
this.tag = tag;
reset();
}
private void reset() {
startTime = -1;
sectionName = null;
}
@Override
public void start(String sectionName) {
if (startTime != -1) {
throw new IllegalStateException("Timer was already started");
}
startTime = System.nanoTime();
this.sectionName = sectionName;
}
@Override
public void stop() {
if (startTime == -1) {
throw new IllegalStateException("Timer was not started");
}
float durationMs = (System.nanoTime() - startTime) / 1000000f;
Log.d(tag, String.format(sectionName + ": %.3fms", durationMs));
reset();
}
}
| 8,960 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/UpdateOpHelper.java | package com.airbnb.epoxy;
import com.airbnb.epoxy.UpdateOp.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
import static com.airbnb.epoxy.UpdateOp.ADD;
import static com.airbnb.epoxy.UpdateOp.MOVE;
import static com.airbnb.epoxy.UpdateOp.REMOVE;
import static com.airbnb.epoxy.UpdateOp.UPDATE;
/** Helper class to collect changes in a diff, batching when possible. */
class UpdateOpHelper {
final List<UpdateOp> opList = new ArrayList<>();
// We have to be careful to update all item positions in the list when we
// do a MOVE. This adds some complexity.
// To do this we keep track of all moves and apply them to an item when we
// need the up to date position
final List<UpdateOp> moves = new ArrayList<>();
private UpdateOp lastOp;
private int numInsertions;
private int numInsertionBatches;
private int numRemovals;
private int numRemovalBatches;
void reset() {
opList.clear();
moves.clear();
lastOp = null;
numInsertions = 0;
numInsertionBatches = 0;
numRemovals = 0;
numRemovalBatches = 0;
}
void add(int indexToInsert) {
add(indexToInsert, 1);
}
void add(int startPosition, int itemCount) {
numInsertions += itemCount;
// We can append to a previously ADD batch if the new items are added anywhere in the
// range of the previous batch batch
boolean batchWithLast = isLastOp(ADD)
&& (lastOp.contains(startPosition) || lastOp.positionEnd() == startPosition);
if (batchWithLast) {
addItemsToLastOperation(itemCount, null);
} else {
numInsertionBatches++;
addNewOperation(ADD, startPosition, itemCount);
}
}
void update(int indexToChange) {
update(indexToChange, null);
}
void update(final int indexToChange, EpoxyModel<?> payload) {
if (isLastOp(UPDATE)) {
if (lastOp.positionStart == indexToChange + 1) {
// Change another item at the start of the batch range
addItemsToLastOperation(1, payload);
lastOp.positionStart = indexToChange;
} else if (lastOp.positionEnd() == indexToChange) {
// Add another item at the end of the batch range
addItemsToLastOperation(1, payload);
} else if (lastOp.contains(indexToChange)) {
// This item is already included in the existing batch range, so we don't add any items
// to the batch count, but we still need to add the new payload
addItemsToLastOperation(0, payload);
} else {
// The item can't be batched with the previous update operation
addNewOperation(UPDATE, indexToChange, 1, payload);
}
} else {
addNewOperation(UPDATE, indexToChange, 1, payload);
}
}
void remove(int indexToRemove) {
remove(indexToRemove, 1);
}
void remove(int startPosition, int itemCount) {
numRemovals += itemCount;
boolean batchWithLast = false;
if (isLastOp(REMOVE)) {
if (lastOp.positionStart == startPosition) {
// Remove additional items at the end of the batch range
batchWithLast = true;
} else if (lastOp.isAfter(startPosition)
&& startPosition + itemCount >= lastOp.positionStart) {
// Removes additional items at the start and (possibly) end of the batch
lastOp.positionStart = startPosition;
batchWithLast = true;
}
}
if (batchWithLast) {
addItemsToLastOperation(itemCount, null);
} else {
numRemovalBatches++;
addNewOperation(REMOVE, startPosition, itemCount);
}
}
private boolean isLastOp(@UpdateOp.Type int updateType) {
return lastOp != null && lastOp.type == updateType;
}
private void addNewOperation(@Type int type, int position, int itemCount) {
addNewOperation(type, position, itemCount, null);
}
private void addNewOperation(@Type int type, int position, int itemCount,
@Nullable EpoxyModel<?> payload) {
lastOp = UpdateOp.instance(type, position, itemCount, payload);
opList.add(lastOp);
}
private void addItemsToLastOperation(int numItemsToAdd, EpoxyModel<?> payload) {
lastOp.itemCount += numItemsToAdd;
lastOp.addPayload(payload);
}
void move(int from, int to) {
// We can't batch moves
lastOp = null;
UpdateOp op = UpdateOp.instance(MOVE, from, to, null);
opList.add(op);
moves.add(op);
}
int getNumRemovals() {
return numRemovals;
}
boolean hasRemovals() {
return numRemovals > 0;
}
int getNumInsertions() {
return numInsertions;
}
boolean hasInsertions() {
return numInsertions > 0;
}
int getNumMoves() {
return moves.size();
}
int getNumInsertionBatches() {
return numInsertionBatches;
}
int getNumRemovalBatches() {
return numRemovalBatches;
}
}
| 8,961 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/OnModelClickListener.java | package com.airbnb.epoxy;
import android.view.View;
/** Used to register a click listener on a generated model. */
public interface OnModelClickListener<T extends EpoxyModel<?>, V> {
/**
* Called when the view bound to the model is clicked.
*
* @param model The model that the view is bound to.
* @param parentView The view bound to the model which received the click.
* @param clickedView The view that received the click. This is either a child of the parentView
* or the parentView itself
* @param position The position of the model in the adapter.
*/
void onClick(T model, V parentView, View clickedView, int position);
}
| 8,962 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/AsyncEpoxyDiffer.java | package com.airbnb.epoxy;
import android.os.Handler;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.DiffUtil.ItemCallback;
/**
* An adaptation of Google's {@link androidx.recyclerview.widget.AsyncListDiffer}
* that adds support for payloads in changes.
* <p>
* Also adds support for canceling an in progress diff, and makes everything thread safe.
*/
class AsyncEpoxyDiffer {
interface ResultCallback {
void onResult(@NonNull DiffResult result);
}
private final Executor executor;
private final ResultCallback resultCallback;
private final ItemCallback<EpoxyModel<?>> diffCallback;
private final GenerationTracker generationTracker = new GenerationTracker();
AsyncEpoxyDiffer(
@NonNull Handler handler,
@NonNull ResultCallback resultCallback,
@NonNull ItemCallback<EpoxyModel<?>> diffCallback
) {
this.executor = new HandlerExecutor(handler);
this.resultCallback = resultCallback;
this.diffCallback = diffCallback;
}
@Nullable
private volatile List<? extends EpoxyModel<?>> list;
/**
* Non-null, unmodifiable version of list.
* <p>
* Collections.emptyList when list is null, wrapped by Collections.unmodifiableList otherwise
*/
@NonNull
private volatile List<? extends EpoxyModel<?>> readOnlyList = Collections.emptyList();
/**
* Get the current List - any diffing to present this list has already been computed and
* dispatched via the ListUpdateCallback.
* <p>
* If a <code>null</code> List, or no List has been submitted, an empty list will be returned.
* <p>
* The returned list may not be mutated - mutations to content must be done through
* {@link #submitList(List)}.
*
* @return current List.
*/
@AnyThread
@NonNull
public List<? extends EpoxyModel<?>> getCurrentList() {
return readOnlyList;
}
/**
* Prevents any ongoing diff from dispatching results. Returns true if there was an ongoing
* diff to cancel, false otherwise.
*/
@SuppressWarnings("WeakerAccess")
@AnyThread
public boolean cancelDiff() {
return generationTracker.finishMaxGeneration();
}
/**
* @return True if a diff operation is in progress.
*/
@SuppressWarnings("WeakerAccess")
@AnyThread
public boolean isDiffInProgress() {
return generationTracker.hasUnfinishedGeneration();
}
/**
* Set the current list without performing any diffing. Cancels any diff in progress.
* <p>
* This can be used if you notified a change to the adapter manually and need this list to be
* synced.
*/
@AnyThread
public synchronized boolean forceListOverride(@Nullable List<EpoxyModel<?>> newList) {
// We need to make sure that generation changes and list updates are synchronized
final boolean interruptedDiff = cancelDiff();
int generation = generationTracker.incrementAndGetNextScheduled();
tryLatchList(newList, generation);
return interruptedDiff;
}
/**
* Set a new List representing your latest data.
* <p>
* A diff will be computed between this list and the last list set. If this has not previously
* been called then an empty list is used as the previous list.
* <p>
* The diff computation will be done on the thread given by the handler in the constructor.
* When the diff is done it will be applied (dispatched to the result callback),
* and the new List will be swapped in.
*/
@AnyThread
@SuppressWarnings("WeakerAccess")
public void submitList(@Nullable final List<? extends EpoxyModel<?>> newList) {
final int runGeneration;
@Nullable final List<? extends EpoxyModel<?>> previousList;
synchronized (this) {
// Incrementing generation means any currently-running diffs are discarded when they finish
// We synchronize to guarantee list object and generation number are in sync
runGeneration = generationTracker.incrementAndGetNextScheduled();
previousList = list;
}
if (newList == previousList) {
// nothing to do
onRunCompleted(runGeneration, newList, DiffResult.noOp(previousList));
return;
}
if (newList == null || newList.isEmpty()) {
// fast simple clear all
DiffResult result = null;
if (previousList != null && !previousList.isEmpty()) {
result = DiffResult.clear(previousList);
}
onRunCompleted(runGeneration, null, result);
return;
}
if (previousList == null || previousList.isEmpty()) {
// fast simple first insert
onRunCompleted(runGeneration, newList, DiffResult.inserted(newList));
return;
}
final DiffCallback wrappedCallback = new DiffCallback(previousList, newList, diffCallback);
executor.execute(new Runnable() {
@Override
public void run() {
DiffUtil.DiffResult result = DiffUtil.calculateDiff(wrappedCallback);
onRunCompleted(runGeneration, newList, DiffResult.diff(previousList, newList, result));
}
});
}
private void onRunCompleted(
final int runGeneration,
@Nullable final List<? extends EpoxyModel<?>> newList,
@Nullable final DiffResult result
) {
// We use an asynchronous handler so that the Runnable can be posted directly back to the main
// thread without waiting on view invalidation synchronization.
MainThreadExecutor.ASYNC_INSTANCE.execute(new Runnable() {
@Override
public void run() {
final boolean dispatchResult = tryLatchList(newList, runGeneration);
if (result != null && dispatchResult) {
resultCallback.onResult(result);
}
}
});
}
/**
* Marks the generation as done, and updates the list if the generation is the most recent.
*
* @return True if the given generation is the most recent, in which case the given list was
* set. False if the generation is old and the list was ignored.
*/
@AnyThread
private synchronized boolean tryLatchList(@Nullable List<? extends EpoxyModel<?>> newList,
int runGeneration) {
if (generationTracker.finishGeneration(runGeneration)) {
list = newList;
if (newList == null) {
readOnlyList = Collections.emptyList();
} else {
readOnlyList = Collections.unmodifiableList(newList);
}
return true;
}
return false;
}
/**
* The concept of a "generation" is used to associate a diff result with a point in time when
* it was created. This allows us to handle list updates concurrently, and ignore outdated diffs.
* <p>
* We track the highest start generation, and the highest finished generation, and these must
* be kept in sync, so all access to this class is synchronized.
* <p>
* The general synchronization strategy for this class is that when a generation number
* is queried that action must be synchronized with accessing the current list, so that the
* generation number is synced with the list state at the time it was created.
*/
private static class GenerationTracker {
// Max generation of currently scheduled runnable
private volatile int maxScheduledGeneration;
private volatile int maxFinishedGeneration;
synchronized int incrementAndGetNextScheduled() {
return ++maxScheduledGeneration;
}
synchronized boolean finishMaxGeneration() {
boolean isInterrupting = hasUnfinishedGeneration();
maxFinishedGeneration = maxScheduledGeneration;
return isInterrupting;
}
synchronized boolean hasUnfinishedGeneration() {
return maxScheduledGeneration > maxFinishedGeneration;
}
synchronized boolean finishGeneration(int runGeneration) {
boolean isLatestGeneration =
maxScheduledGeneration == runGeneration && runGeneration > maxFinishedGeneration;
if (isLatestGeneration) {
maxFinishedGeneration = runGeneration;
}
return isLatestGeneration;
}
}
private static class DiffCallback extends DiffUtil.Callback {
final List<? extends EpoxyModel<?>> oldList;
final List<? extends EpoxyModel<?>> newList;
private final ItemCallback<EpoxyModel<?>> diffCallback;
DiffCallback(List<? extends EpoxyModel<?>> oldList, List<? extends EpoxyModel<?>> newList,
ItemCallback<EpoxyModel<?>> diffCallback) {
this.oldList = oldList;
this.newList = newList;
this.diffCallback = diffCallback;
}
@Override
public int getOldListSize() {
return oldList.size();
}
@Override
public int getNewListSize() {
return newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return diffCallback.areItemsTheSame(
oldList.get(oldItemPosition),
newList.get(newItemPosition)
);
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return diffCallback.areContentsTheSame(
oldList.get(oldItemPosition),
newList.get(newItemPosition)
);
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
return diffCallback.getChangePayload(
oldList.get(oldItemPosition),
newList.get(newItemPosition)
);
}
}
}
| 8,963 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/HiddenEpoxyModel.java |
package com.airbnb.epoxy;
import android.widget.Space;
import com.airbnb.viewmodeladapter.R;
/**
* Used by the {@link EpoxyAdapter} as a placeholder for when {@link EpoxyModel#isShown()} is false.
* Using a zero height and width {@link Space} view, as well as 0 span size, to exclude itself from
* view.
*/
class HiddenEpoxyModel extends EpoxyModel<Space> {
@Override
public int getDefaultLayout() {
return R.layout.view_holder_empty_view;
}
@Override
public int getSpanSize(int spanCount, int position, int itemCount) {
return 0;
}
}
| 8,964 |
0 | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-adapter/src/main/java/com/airbnb/epoxy/StyleBuilderCallback.java | package com.airbnb.epoxy;
/**
* Used for specifying dynamic styling for a view when creating a model. This is only used if the
* view is set up to be styled with the Paris library.
*/
public interface StyleBuilderCallback<T> {
void buildStyle(T builder);
}
| 8,965 |
0 | Create_ds/epoxy/epoxy-modelfactory/src/main/java/com/airbnb | Create_ds/epoxy/epoxy-modelfactory/src/main/java/com/airbnb/epoxy/ModelProperties.java | package com.airbnb.epoxy;
import android.view.View.OnClickListener;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import com.airbnb.paris.styles.Style;
import java.util.List;
public interface ModelProperties {
@NonNull
String getId();
boolean has(@NonNull String propertyName);
boolean getBoolean(@NonNull String propertyName);
double getDouble(@NonNull String propertyName);
@DrawableRes
int getDrawableRes(@NonNull String propertyName);
@Nullable
List<? extends EpoxyModel<?>> getEpoxyModelList(@NonNull String propertyName);
int getInt(@NonNull String propertyName);
long getLong(@NonNull String propertyName);
@Nullable
OnClickListener getOnClickListener(@NonNull String propertyName);
@RawRes
int getRawRes(@NonNull String propertyName);
@Nullable
String getString(@NonNull String propertyName);
@Nullable
List<String> getStringList(@NonNull String propertyName);
/**
* @return Null to apply the default style.
*/
@Nullable
Style getStyle();
}
| 8,966 |
0 | Create_ds/epoxy/epoxy-processortest2/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-processortest2/src/main/java/com/airbnb/epoxy/processortest2/ProcessorTest2Model.java | package com.airbnb.epoxy.processortest2;
import android.view.View;
import com.airbnb.epoxy.EpoxyAttribute;
import com.airbnb.epoxy.EpoxyModel;
public class ProcessorTest2Model<T extends View> extends EpoxyModel<T> {
@EpoxyAttribute protected int processorTest2ValueProtected;
@EpoxyAttribute public int processorTest2ValuePublic;
@EpoxyAttribute int processorTest2ValuePackagePrivate;
@EpoxyAttribute public int someAttributeAlsoWithSetter;
@EpoxyAttribute public final int someFinalAttribute = 0;
@Override
protected int getDefaultLayout() {
return 0;
}
public ProcessorTest2Model<T> someAttributeAlsoWithSetter(int foo) {
someAttributeAlsoWithSetter = foo;
return this;
}
}
| 8,967 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/EpoxyConfig.java | package com.airbnb.epoxy.sample;
import com.airbnb.epoxy.EpoxyDataBindingLayouts;
import com.airbnb.epoxy.PackageModelViewConfig;
@PackageModelViewConfig(rClass = R.class)
@EpoxyDataBindingLayouts(R.layout.button)
interface EpoxyConfig {}
| 8,968 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/ColorData.java | package com.airbnb.epoxy.sample;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.ColorInt;
public class ColorData implements Parcelable {
private final long id;
@ColorInt private int colorInt;
private boolean playAnimation;
public ColorData(int colorInt, long id) {
this.colorInt = colorInt;
this.id = id;
}
public long getId() {
return id;
}
@ColorInt
public int getColorInt() {
return colorInt;
}
public void setColorInt(@ColorInt int colorInt) {
this.colorInt = colorInt;
}
public void setPlayAnimation(boolean playAnimation) {
this.playAnimation = playAnimation;
}
public boolean shouldPlayAnimation() {
return playAnimation;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.colorInt);
dest.writeLong(this.id);
}
protected ColorData(Parcel in) {
this.colorInt = in.readInt();
this.id = in.readLong();
}
public static final Creator<ColorData> CREATOR = new Creator<ColorData>() {
@Override
public ColorData createFromParcel(Parcel source) {
return new ColorData(source);
}
@Override
public ColorData[] newArray(int size) {
return new ColorData[size];
}
};
}
| 8,969 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/MainActivity.java | package com.airbnb.epoxy.sample;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import com.airbnb.epoxy.EpoxyRecyclerView;
import com.airbnb.epoxy.EpoxyTouchHelper;
import com.airbnb.epoxy.EpoxyTouchHelper.DragCallbacks;
import com.airbnb.epoxy.sample.SampleController.AdapterCallbacks;
import com.airbnb.epoxy.sample.models.CarouselModelGroup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import androidx.annotation.ColorInt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import static android.animation.ValueAnimator.ofObject;
/**
* Example activity usage for {@link com.airbnb.epoxy.EpoxyController}.
*/
public class MainActivity extends AppCompatActivity implements AdapterCallbacks {
private static final Random RANDOM = new Random();
private static final String CAROUSEL_DATA_KEY = "carousel_data_key";
private final SampleController controller = new SampleController(this);
private List<CarouselData> carousels = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EpoxyRecyclerView recyclerView = (EpoxyRecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setController(controller);
if (savedInstanceState != null) {
carousels = savedInstanceState.getParcelableArrayList(CAROUSEL_DATA_KEY);
}
initTouch(recyclerView);
updateController();
}
private void initTouch(final RecyclerView recyclerView) {
// Swiping is not used since it interferes with the carousels, but here is an example of
// how we would set it up.
// EpoxyTouchHelper.initSwiping(recyclerView)
// .leftAndRight()
// .withTarget(CarouselModelGroup.class)
// .andCallbacks(new SwipeCallbacks<CarouselModelGroup>() {
//
// @Override
// public void onSwipeProgressChanged(CarouselModelGroup model, View itemView,
// float swipeProgress) {
//
// Fades a background color in the further you swipe. A different color is used
// for swiping left vs right.
// int alpha = (int) (Math.abs(swipeProgress) * 255);
// if (swipeProgress > 0) {
// itemView.setBackgroundColor(Color.argb(alpha, 0, 255, 0));
// } else {
// itemView.setBackgroundColor(Color.argb(alpha, 255, 0, 0));
// }
// }
//
// @Override
// public void onSwipeCompleted(CarouselModelGroup model, View itemView, int position,
// int direction) {
// carousels.remove(model.data);
// updateController();
// }
//
// @Override
// public void clearView(CarouselModelGroup model, View itemView) {
// itemView.setBackgroundColor(Color.WHITE);
// }
// });
EpoxyTouchHelper.initDragging(controller)
.withRecyclerView(recyclerView)
.forVerticalList()
.withTarget(CarouselModelGroup.class)
.andCallbacks(new DragCallbacks<CarouselModelGroup>() {
@ColorInt final int selectedBackgroundColor = Color.argb(200, 200, 200, 200);
ValueAnimator backgroundAnimator = null;
@Override
public void onModelMoved(int fromPosition, int toPosition,
CarouselModelGroup modelBeingMoved, View itemView) {
int carouselIndex = carousels.indexOf(modelBeingMoved.data);
carousels
.add(carouselIndex + (toPosition - fromPosition), carousels.remove(carouselIndex));
}
@Override
public void onDragStarted(CarouselModelGroup model, View itemView, int adapterPosition) {
backgroundAnimator = ValueAnimator
.ofObject(new ArgbEvaluator(), Color.WHITE, selectedBackgroundColor);
backgroundAnimator.addUpdateListener(
animator -> itemView.setBackgroundColor((int) animator.getAnimatedValue())
);
backgroundAnimator.start();
itemView
.animate()
.scaleX(1.05f)
.scaleY(1.05f);
}
@Override
public void onDragReleased(CarouselModelGroup model, View itemView) {
if (backgroundAnimator != null) {
backgroundAnimator.cancel();
}
backgroundAnimator =
ofObject(new ArgbEvaluator(), ((ColorDrawable) itemView.getBackground()).getColor(),
Color.WHITE);
backgroundAnimator.addUpdateListener(
animator -> itemView.setBackgroundColor((int) animator.getAnimatedValue())
);
backgroundAnimator.start();
itemView
.animate()
.scaleX(1f)
.scaleY(1f);
}
@Override
public void clearView(CarouselModelGroup model, View itemView) {
onDragReleased(model, itemView);
}
});
}
@Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putParcelableArrayList(CAROUSEL_DATA_KEY, (ArrayList<? extends Parcelable>) carousels);
controller.onSaveInstanceState(state);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
controller.onRestoreInstanceState(savedInstanceState);
}
private void updateController() {
controller.setData(carousels);
}
@Override
public void onAddCarouselClicked() {
CarouselData carousel = new CarouselData(carousels.size(), new ArrayList<>());
addColorToCarousel(carousel);
carousels.add(0, carousel);
updateController();
}
private void addColorToCarousel(CarouselData carousel) {
List<ColorData> colors = carousel.getColors();
colors.add(0, new ColorData(randomColor(), colors.size()));
}
@Override
public void onClearCarouselsClicked() {
carousels.clear();
updateController();
}
@Override
public void onShuffleCarouselsClicked() {
Collections.shuffle(carousels);
updateController();
}
@Override
public void onChangeAllColorsClicked() {
for (CarouselData carouselData : carousels) {
for (ColorData colorData : carouselData.getColors()) {
colorData.setColorInt(randomColor());
}
}
updateController();
}
@Override
public void onAddColorToCarouselClicked(CarouselData carousel) {
addColorToCarousel(carousel);
updateController();
}
@Override
public void onClearCarouselClicked(CarouselData carousel) {
carousel.getColors().clear();
updateController();
}
@Override
public void onShuffleCarouselColorsClicked(CarouselData carousel) {
Collections.shuffle(carousel.getColors());
updateController();
}
@Override
public void onChangeCarouselColorsClicked(CarouselData carousel) {
for (ColorData colorData : carousel.getColors()) {
colorData.setColorInt(randomColor());
}
updateController();
}
@Override
public void onColorClicked(CarouselData carousel, int colorPosition) {
int carouselPosition = carousels.indexOf(carousel);
ColorData colorData = carousels.get(carouselPosition).getColors().get(colorPosition);
colorData.setPlayAnimation(!colorData.shouldPlayAnimation());
updateController();
}
private static int randomColor() {
int r = RANDOM.nextInt(256);
int g = RANDOM.nextInt(256);
int b = RANDOM.nextInt(256);
return Color.rgb(r, g, b);
}
}
| 8,970 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/CarouselData.java | package com.airbnb.epoxy.sample;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
public class CarouselData implements Parcelable {
private final long id;
private final List<ColorData> colors;
public CarouselData(long id, List<ColorData> colors) {
this.id = id;
this.colors = colors;
}
public List<ColorData> getColors() {
return colors;
}
public long getId() {
return id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeTypedList(this.colors);
}
protected CarouselData(Parcel in) {
this.id = in.readLong();
this.colors = in.createTypedArrayList(ColorData.CREATOR);
}
public static final Creator<CarouselData> CREATOR = new Creator<CarouselData>() {
@Override
public CarouselData createFromParcel(Parcel source) {
return new CarouselData(source);
}
@Override
public CarouselData[] newArray(int size) {
return new CarouselData[size];
}
};
}
| 8,971 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/BaseView.java | package com.airbnb.epoxy.sample.models;
import android.content.Context;
import com.airbnb.epoxy.ModelProp;
import com.airbnb.epoxy.ModelView;
import androidx.appcompat.widget.AppCompatTextView;
@ModelView
public abstract class BaseView extends AppCompatTextView {
public BaseView(Context context) {
super(context);
}
@ModelProp
public void setVerticalPadding(CharSequence tex) {
}
}
| 8,972 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/CarouselModelGroup.java | package com.airbnb.epoxy.sample.models;
import com.airbnb.epoxy.EpoxyModel;
import com.airbnb.epoxy.EpoxyModelGroup;
import com.airbnb.epoxy.sample.CarouselData;
import com.airbnb.epoxy.sample.ColorData;
import com.airbnb.epoxy.sample.R;
import com.airbnb.epoxy.sample.SampleController.AdapterCallbacks;
import com.airbnb.epoxy.sample.views.GridCarouselModel_;
import java.util.ArrayList;
import java.util.List;
public class CarouselModelGroup extends EpoxyModelGroup {
public final CarouselData data;
public CarouselModelGroup(CarouselData carousel, AdapterCallbacks callbacks) {
super(R.layout.model_carousel_group, buildModels(carousel, callbacks));
this.data = carousel;
id(carousel.getId());
}
private static List<EpoxyModel<?>> buildModels(CarouselData carousel,
AdapterCallbacks callbacks) {
List<ColorData> colors = carousel.getColors();
ArrayList<EpoxyModel<?>> models = new ArrayList<>();
models.add(new ImageButtonModel_()
.id("add")
.imageRes(R.drawable.ic_add_circle)
.clickListener((model, parentView, clickedView, position) -> callbacks
.onAddColorToCarouselClicked(carousel)));
models.add(new ImageButtonModel_()
.id("delete")
.imageRes(R.drawable.ic_delete)
.clickListener(v -> callbacks.onClearCarouselClicked(carousel))
.show(colors.size() > 0));
models.add(new ImageButtonModel_()
.id("change")
.imageRes(R.drawable.ic_change)
.clickListener(v -> callbacks.onChangeCarouselColorsClicked(carousel))
.show(colors.size() > 0));
models.add(new ImageButtonModel_()
.id("shuffle")
.imageRes(R.drawable.ic_shuffle)
.clickListener(v -> callbacks.onShuffleCarouselColorsClicked(carousel))
.show(colors.size() > 1));
List<ColorModel_> colorModels = new ArrayList<>();
for (ColorData colorData : colors) {
colorModels.add(new ColorModel_()
.id(colorData.getId(), carousel.getId())
.color(colorData.getColorInt())
.playAnimation(colorData.shouldPlayAnimation())
.clickListener((model, parentView, clickedView, position) -> {
// A model click listener is used instead of a normal click listener so that we can get
// the current position of the view. Since the view may have been moved when the colors
// were shuffled we can't rely on the position of the model when it was added here to
// be correct, since the model won't have been rebound when shuffled.
callbacks.onColorClicked(carousel, position);
}));
}
models.add(new GridCarouselModel_()
.id("carousel")
.models(colorModels));
return models;
}
@Override
public int getSpanSize(int totalSpanCount, int position, int itemCount) {
return totalSpanCount;
}
}
| 8,973 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/SimpleAnimatorListener.java | package com.airbnb.epoxy.sample.models;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
public class SimpleAnimatorListener implements AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
| 8,974 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/views/HeaderView.java | package com.airbnb.epoxy.sample.views;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.airbnb.epoxy.ModelProp;
import com.airbnb.epoxy.ModelProp.Option;
import com.airbnb.epoxy.ModelView;
import com.airbnb.epoxy.TextProp;
import com.airbnb.epoxy.sample.R;
import com.airbnb.paris.annotations.Style;
import com.airbnb.paris.annotations.Styleable;
@Styleable // Dynamic styling via the Paris library
@ModelView
public class HeaderView extends LinearLayout {
private TextView title;
private TextView caption;
public HeaderView(Context context) {
super(context);
init();
}
@Style(isDefault = true)
static void headerStyle(HeaderViewStyleApplier.StyleBuilder builder) {
builder.layoutWidth(ViewGroup.LayoutParams.MATCH_PARENT)
.layoutHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void init() {
setOrientation(VERTICAL);
inflate(getContext(), R.layout.view_header, this);
title = findViewById(R.id.title_text);
caption = findViewById(R.id.caption_text);
}
@TextProp(defaultRes = R.string.app_name)
public void setTitle(CharSequence title) {
this.title.setText(title);
}
@ModelProp(options = Option.GenerateStringOverloads)
public void setCaption(CharSequence caption) {
this.caption.setText(caption);
}
}
| 8,975 |
0 | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample | Create_ds/epoxy/epoxy-sample/src/main/java/com/airbnb/epoxy/sample/views/GridCarousel.java | package com.airbnb.epoxy.sample.views;
import android.content.Context;
import com.airbnb.epoxy.Carousel;
import com.airbnb.epoxy.ModelView;
import com.airbnb.epoxy.ModelView.Size;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
@ModelView(saveViewState = true, autoLayout = Size.MATCH_WIDTH_WRAP_HEIGHT)
public class GridCarousel extends Carousel {
private static final int SPAN_COUNT = 2;
public GridCarousel(Context context) {
super(context);
}
@NonNull
@Override
protected LayoutManager createLayoutManager() {
return new GridLayoutManager(getContext(), SPAN_COUNT, LinearLayoutManager.HORIZONTAL, false);
}
}
| 8,976 |
0 | Create_ds/epoxy/epoxy-processor/src/main/java/com/airbnb/epoxy | Create_ds/epoxy/epoxy-processor/src/main/java/com/airbnb/epoxy/processor/ImportScanner.java | package com.airbnb.epoxy.processor;
import java.util.HashSet;
import java.util.Set;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementScanner7;
public class ImportScanner extends ElementScanner7<Void, Void> {
private Set<String> types = new HashSet<>();
public Set<String> getImportedTypes() {
return types;
}
@Override
public Void visitType(TypeElement e, Void p) {
for (TypeMirror interfaceType : e.getInterfaces()) {
types.add(interfaceType.toString());
}
TypeMirror superclass = e.getSuperclass();
SynchronizationKt.ensureLoaded(superclass);
types.add(superclass.toString());
return super.visitType(e, p);
}
@Override
public Void visitExecutable(ExecutableElement e, Void p) {
if (e.getReturnType().getKind() == TypeKind.DECLARED) {
types.add(e.getReturnType().toString());
}
return super.visitExecutable(e, p);
}
@Override
public Void visitTypeParameter(TypeParameterElement e, Void p) {
if (e.asType().getKind() == TypeKind.DECLARED) {
types.add(e.asType().toString());
}
return super.visitTypeParameter(e, p);
}
@Override
public Void visitVariable(VariableElement e, Void p) {
if (e.asType().getKind() == TypeKind.DECLARED) {
types.add(e.asType().toString());
}
return super.visitVariable(e, p);
}
}
| 8,977 |
0 | Create_ds/TaBERT/contrib/wiki_extractor/src/main | Create_ds/TaBERT/contrib/wiki_extractor/src/main/java/MediaWikiToHtml.java | // Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
import info.bliki.wiki.model.WikiModel;
public class MediaWikiToHtml {
public static String convert(String mediaWikiText){
String htmlText = WikiModel.toHtml(mediaWikiText);
return htmlText;
}
public static void main(String[] args) {
System.out.println(convert("{| class=wikitable\n" +
"|+ Voter Registration and Party Enrollment {{as of|2018|July|3|lc=y|df=US}}<ref>{{cite web|url=http://www.elections.alaska.gov/statistics/2018/JUL/VOTERS%20BY%20PARTY%20AND%20PRECINCT.htm#STATEWIDE |title=Alaska Voter Registration by Party/Precinct |publisher=Elections.alaska.gov |date= |accessdate=January 9, 2019}}</ref>\n" +
"|-\n" +
"! colspan = 2 | Party\n" +
"! Number of Voters\n" +
"! Percentage\n" +
"|-\n" +
"{{party color|Independent politician}}\n" +
"| [[Independent voter|Unaffiliated]]\n" +
"| style=\"text-align:center;\"| 299,365\n" +
"| style=\"text-align:center;\"| 55.25%\n" +
"|-\n" +
"{{party color|Republican Party (United States)}}\n" +
"| [[Republican Party (United States)|Republican]]\n" +
"| style=\"text-align:center;\"| 139,615\n" +
"| style=\"text-align:center;\"| 25.77%\n" +
"|-\n" +
"{{party color|Democratic Party (United States)}}\n" +
"|[[Democratic Party (United States)|Democratic]]\n" +
"| style=\"text-align:center;\"| 74,865\n" +
"| style=\"text-align:center;\"| 13.82%\n" +
"|-\n" +
"{{party color|Alaskan Independence Party}}\n" +
"|[[Alaskan Independence Party|AKIP]]\n" +
"| style=\"text-align:center;\"| 17,118\n" +
"| style=\"text-align:center;\"| 3.16%\n" +
"|-\n" +
"{{party color|Libertarian Party (United States)}}\n" +
"|[[Libertarian Party (United States)|Libertarian]]\n" +
"| style=\"text-align:center;\"| 7,422\n" +
"| style=\"text-align:center;\"| 1.37%\n" +
"|-\n" +
"{{party color|Independent (politician)}}\n" +
"|[[List of political parties in the United States|Other]]\n" +
"| style=\"text-align:center;\"| 3,436\n" +
"| style=\"text-align:center;\"| 0.36%\n" +
"|-\n" +
"! colspan=\"2\" | Total\n" +
"! style=\"text-align:center;\" | 541,821\n" +
"! style=\"text-align:center;\" | 100%\n" +
"|}"));
}
}
| 8,978 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/androidTest/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/androidTest/java/software/amazon/freertos/amazonfreertossdk/ExampleInstrumentedTest.java | package software.amazon.freertos.amazonfreertossdk;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.amazon.aws.amazonfreertossdk.test", appContext.getPackageName());
}
}
| 8,979 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/test/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/test/java/software/amazon/freertos/amazonfreertossdk/ExampleUnitTest.java | package software.amazon.freertos.amazonfreertossdk;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 8,980 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/DeviceInfoCallback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
/**
* This is a callback class to notify the app of device information, including mtu, broker endpoint
* and device software version.
*/
public abstract class DeviceInfoCallback {
/**
* This callback is triggered when device sends the current mtu number in response to getMtu.
* @param mtu the current mtu value negotiated between device and Android phone.
*/
public void onObtainMtu(int mtu){}
/**
* This callback is triggered when device sends its MQTT broker endpoint in response to
* getBrokerEndpoint.
* @param endpoint The current MQTT broker endpoint set on the device.
*/
public void onObtainBrokerEndpoint(String endpoint){}
/**
* This callback is triggered when device sends its current software version in response to
* getDeviceVersion.
* @param version The current device library version on the device.
*/
public void onObtainDeviceSoftwareVersion(String version){}
public void onError(AmazonFreeRTOSConstants.AmazonFreeRTOSError Error) {}
}
| 8,981 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/AmazonFreeRTOSConstants.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import java.util.HashMap;
import java.util.Map;
/**
* This class defines some constants used in the SDK.
*/
public class AmazonFreeRTOSConstants {
/**
* Network security types.
*/
public static final int NETWORK_SECURITY_TYPE_OPEN = 0;
public static final int NETWORK_SECURITY_TYPE_WEP = 1;
public static final int NETWORK_SECURITY_TYPE_WPA = 2;
public static final int NETWORK_SECURITY_TYPE_WPA2 = 3;
public static final int NETWORK_SECURITY_TYPE_NOT_SUPPORTED = 4;
/**
* MQTT proxy state.
*/
public static final int MQTT_PROXY_CONTROL_OFF = 0;
public static final int MQTT_PROXY_CONTROL_ON = 1;
/**
* message type.
*/
public static final int MQTT_MSG_CONNECT = 1;
public static final int MQTT_MSG_CONNACK = 2;
public static final int MQTT_MSG_PUBLISH = 3;
public static final int MQTT_MSG_PUBACK = 4;
public static final int MQTT_MSG_PUBREC = 5;
public static final int MQTT_MSG_PUBREL = 6;
public static final int MQTT_MSG_PUBCOMP = 7;
public static final int MQTT_MSG_SUBSCRIBE = 8;
public static final int MQTT_MSG_SUBACK = 9;
public static final int MQTT_MSG_UNSUBSCRIBE = 10;
public static final int MQTT_MSG_UNSUBACK = 11;
public static final int MQTT_MSG_PINGREQ = 12;
public static final int MQTT_MSG_PINGRESP = 13;
public static final int MQTT_MSG_DISCONNECT = 14;
public static final int LIST_NETWORK_REQ = 1;
public static final int LIST_NETWORK_RESP = 2;
public static final int SAVE_NETWORK_REQ = 3;
public static final int SAVE_NETWORK_RESP = 4;
public static final int EDIT_NETWORK_REQ = 5;
public static final int EDIT_NETWORK_RESP = 6;
public static final int DELETE_NETWORK_REQ = 7;
public static final int DELETE_NETWORK_RESP = 8;
/**
* Bluetooth connection state. This is matching with BluetoothProfile in the Android SDK.
*/
public enum BleConnectionState {
BLE_DISCONNECTED, // = 0
BLE_CONNECTING, // = 1
BLE_CONNECTED, // = 2
BLE_DISCONNECTING, // = 3
BLE_INITIALIZED, // = 4
BLE_INITIALIZING // = 5
}
public enum AmazonFreeRTOSError {
BLE_DISCONNECTED_ERROR
}
/**
* The MQTT connection state.
* Do not change the order of this enum. This is a contract between device library and our sdk.
*/
public enum MqttConnectionState {
MQTT_Unknown,
MQTT_Connecting,
MQTT_Connected,
MQTT_Disconnected,
MQTT_ConnectionRefused,
MQTT_ConnectionError,
MQTT_ProtocolError
}
/**
* This defines how much time the SDK scans for nearby BLE devices.
*/
public static final long SCAN_PERIOD = 20000; //ms
/**
* After sending BLE commands to device, the SDK will wait for this amount of time, after which
* it will time out and continue to process the next BLE command.
*/
public static final int BLE_COMMAND_TIMEOUT = 3000; //ms
public static final String UUID_AmazonFreeRTOS = "8a7f1168-48af-4efb-83b5-e679f932ff00";
public static final String UUID_NETWORK_SERVICE = "a9d7166a-d72e-40a9-a002-48044cc30100";
public static final String UUID_NETWORK_CONTROL = "a9d7166a-d72e-40a9-a002-48044cc30101";
public static final String UUID_NETWORK_TX = "a9d7166a-d72e-40a9-a002-48044cc30102";
public static final String UUID_NETWORK_RX = "a9d7166a-d72e-40a9-a002-48044cc30103";
public static final String UUID_NETWORK_TXLARGE = "a9d7166a-d72e-40a9-a002-48044cc30104";
public static final String UUID_NETWORK_RXLARGE = "a9d7166a-d72e-40a9-a002-48044cc30105";
public static final String UUID_MQTT_PROXY_SERVICE = "a9d7166a-d72e-40a9-a002-48044cc30000";
public static final String UUID_MQTT_PROXY_CONTROL = "a9d7166a-d72e-40a9-a002-48044cc30001";
public static final String UUID_MQTT_PROXY_TX = "a9d7166a-d72e-40a9-a002-48044cc30002";
public static final String UUID_MQTT_PROXY_RX = "a9d7166a-d72e-40a9-a002-48044cc30003";
public static final String UUID_MQTT_PROXY_TXLARGE = "a9d7166a-d72e-40a9-a002-48044cc30004";
public static final String UUID_MQTT_PROXY_RXLARGE = "a9d7166a-d72e-40a9-a002-48044cc30005";
public static final String UUID_DEVICE_INFORMATION_SERVICE = "8a7f1168-48af-4efb-83b5-e679f932ff00";
public static final String UUID_DEVICE_VERSION = "8a7f1168-48af-4efb-83b5-e679f932ff01";
public static final String UUID_IOT_ENDPOINT = "8a7f1168-48af-4efb-83b5-e679f932ff02";
public static final String UUID_DEVICE_MTU = "8a7f1168-48af-4efb-83b5-e679f932ff03";
public static final String UUID_DEVICE_PLATFORM = "8a7f1168-48af-4efb-83b5-e679f932ff04";
public static final String UUID_DEVICE_ID = "8a7f1168-48af-4efb-83b5-e679f932ff05";
public static final Map<String, String> uuidToName = new HashMap<String, String>() {
{
put(UUID_NETWORK_CONTROL, "NETWORK_CONTROL");
put(UUID_NETWORK_TX, "NETWORK_TX");
put(UUID_NETWORK_RX, "NETWORK_RX");
put(UUID_NETWORK_TXLARGE, "NETWORK_TXLARGE");
put(UUID_NETWORK_RXLARGE, "NETWORK_RXLARGE");
put(UUID_MQTT_PROXY_CONTROL, "MQTT_CONTROL");
put(UUID_MQTT_PROXY_TX, "MQTT_TX");
put(UUID_MQTT_PROXY_TXLARGE, "MQTT_TXLARGE");
put(UUID_MQTT_PROXY_RX, "MQTT_RX");
put(UUID_MQTT_PROXY_RXLARGE, "MQTT_RXLARGE");
put(UUID_DEVICE_VERSION, "DEVICE_VERSION");
put(UUID_IOT_ENDPOINT, "IOT_ENDPOINT");
put(UUID_DEVICE_MTU, "DEVICE_MTU");
put(UUID_DEVICE_PLATFORM, "DEVICE_PLATFORM");
put(UUID_DEVICE_ID, "DEVICE_ID");
}
};
}
| 8,982 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/BleCommand.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import java.nio.ByteBuffer;
import lombok.Getter;
/**
* This class defines the BLE command that is sent from SDK to device.
*/
@Getter
public class BleCommand {
enum CommandType {
WRITE_DESCRIPTOR,
WRITE_CHARACTERISTIC,
READ_CHARACTERISTIC,
DISCOVER_SERVICES,
REQUEST_MTU,
NOTIFICATION
}
/**
* The type of the BLE command.
*/
private CommandType type;
/**
* The characteristic uuid of the BLE command.
*/
private String characteristicUuid;
/**
* The service uuid of the BLE command.
*/
private String serviceUuid;
/**
* The data to be sent with the BLE command.
*/
private byte[] data;
/**
* Construct a BLE command with data.
* @param t the BLE command type.
* @param cUuid the characteristic uuid.
* @param sUuid the service uuid.
* @param d the data to be sent with the BLE command.
*/
public BleCommand(CommandType t, String cUuid, String sUuid, byte[] d) {
type = t;
characteristicUuid = cUuid;
serviceUuid = sUuid;
data = d;
}
/**
* Construct a BLE command without any data.
* @param t the BLE command type.
* @param cUuid the characteristic uuid.
* @param sUuid the service uuid.
*/
public BleCommand(CommandType t, String cUuid, String sUuid) {
this(t, cUuid, sUuid, null);
}
public BleCommand(CommandType t) {
this(t, null, null);
}
public BleCommand(CommandType t, int mtu) {
this(t, null, null, ByteBuffer.allocate(4).putInt(mtu).array());
}
}
| 8,983 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/NetworkConfigCallback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import software.amazon.freertos.amazonfreertossdk.networkconfig.DeleteNetworkResp;
import software.amazon.freertos.amazonfreertossdk.networkconfig.EditNetworkResp;
import software.amazon.freertos.amazonfreertossdk.networkconfig.ListNetworkResp;
import software.amazon.freertos.amazonfreertossdk.networkconfig.SaveNetworkResp;
public abstract class NetworkConfigCallback {
public void onListNetworkResponse(ListNetworkResp response){}
public void onSaveNetworkResponse(SaveNetworkResp response){}
public void onEditNetworkResponse(EditNetworkResp response){}
public void onDeleteNetworkResponse(DeleteNetworkResp response){}
}
| 8,984 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/AmazonFreeRTOSDevice.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.BrokerEndpoint;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.Mtu;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.Version;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttMessageDeliveryCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import lombok.Getter;
import lombok.NonNull;
import software.amazon.freertos.amazonfreertossdk.mqttproxy.*;
import software.amazon.freertos.amazonfreertossdk.networkconfig.*;
import static android.bluetooth.BluetoothDevice.BOND_BONDING;
import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.*;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.AmazonFreeRTOSError.BLE_DISCONNECTED_ERROR;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.DISCOVER_SERVICES;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.NOTIFICATION;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.READ_CHARACTERISTIC;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.REQUEST_MTU;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.WRITE_CHARACTERISTIC;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.WRITE_DESCRIPTOR;
public class AmazonFreeRTOSDevice {
private static final String TAG = "FRD";
private static final boolean VDBG = false;
private Context mContext;
@Getter
private BluetoothDevice mBluetoothDevice;
private BluetoothGatt mBluetoothGatt;
private BleConnectionStatusCallback mBleConnectionStatusCallback;
private NetworkConfigCallback mNetworkConfigCallback;
private DeviceInfoCallback mDeviceInfoCallback;
private BleConnectionState mBleConnectionState = BleConnectionState.BLE_DISCONNECTED;
private String mAmazonFreeRTOSLibVersion = "NA";
private String mAmazonFreeRTOSDeviceType = "NA";
private String mAmazonFreeRTOSDeviceId = "NA";
private boolean mGattAutoReconnect = false;
private BroadcastReceiver mBondStateCallback = null;
private int mMtu = 0;
private boolean rr = false;
private Queue<BleCommand> mMqttQueue = new LinkedList<>();
private Queue<BleCommand> mNetworkQueue = new LinkedList<>();
private Queue<BleCommand> mIncomingQueue = new LinkedList<>();
private boolean mBleOperationInProgress = false;
private boolean mRWinProgress = false;
private Handler mHandler;
private HandlerThread mHandlerThread;
private byte[] mValueWritten;
private Semaphore mutex = new Semaphore(1);
private Semaphore mIncomingMutex = new Semaphore(1);
//Buffer for receiving messages from device
private ByteArrayOutputStream mTxLargeObject = new ByteArrayOutputStream();
private ByteArrayOutputStream mTxLargeNw = new ByteArrayOutputStream();
//Buffer for sending messages to device.
private int mTotalPackets = 0;
private int mPacketCount = 1;
private int mMessageId = 0;
private int mMaxPayloadLen = 0;
private AWSIotMqttManager mIotMqttManager;
private MqttConnectionState mMqttConnectionState = MqttConnectionState.MQTT_Disconnected;
private AWSCredentialsProvider mAWSCredential;
private KeyStore mKeystore;
/**
* Construct an AmazonFreeRTOSDevice instance.
*
* @param context The app context. Should be passed in by the app that creates a new instance
* of AmazonFreeRTOSDevice.
* @param device BluetoothDevice returned from BLE scan result.
* @param cp AWS credential for connection to AWS IoT. If null is passed in,
* then it will not be able to do MQTT proxy over BLE as it cannot
* connect to AWS IoT.
*/
AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context, AWSCredentialsProvider cp) {
this(device, context, cp, null);
}
/**
* Construct an AmazonFreeRTOSDevice instance.
*
* @param context The app context. Should be passed in by the app that creates a new instance
* of AmazonFreeRTOSDevice.
* @param device BluetoothDevice returned from BLE scan result.
* @param ks the KeyStore which contains the certificate used to connect to AWS IoT.
*/
AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context, KeyStore ks) {
this(device, context, null, ks);
}
private AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context,
AWSCredentialsProvider cp, KeyStore ks) {
mContext = context;
mBluetoothDevice = device;
mAWSCredential = cp;
mKeystore = ks;
}
void connect(@NonNull final BleConnectionStatusCallback connectionStatusCallback,
final boolean autoReconnect) {
mBleConnectionStatusCallback = connectionStatusCallback;
mHandlerThread = new HandlerThread("BleCommandHandler"); //TODO: unique thread name for each device?
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mGattAutoReconnect = autoReconnect;
mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback, TRANSPORT_LE);
}
private void cleanUp() {
// If ble connection is lost, clear any pending ble command.
mMqttQueue.clear();
mNetworkQueue.clear();
mIncomingQueue.clear();
mMessageId = 0;
mMtu = 0;
mMaxPayloadLen = 0;
mTxLargeObject.reset();
mTotalPackets = 0;
mPacketCount = 1;
}
/**
* User initiated disconnect
*/
void disconnect() {
if (mBluetoothGatt != null) {
mGattAutoReconnect = false;
mBluetoothGatt.disconnect();
}
}
/**
* Sends a ListNetworkReq command to the connected BLE device. The available WiFi networks found
* by the connected BLE device will be returned in the callback as a ListNetworkResp. Each found
* WiFi network should trigger the callback once. For example, if there are 10 available networks
* found by the BLE device, this callback will be triggered 10 times, each containing one
* ListNetworkResp that represents that WiFi network. In addition, the order of the callbacks will
* be triggered as follows: the saved networks will be returned first, in decreasing order of their
* preference, as denoted by their index. (The smallest non-negative index denotes the highest
* preference, and is therefore returned first.) For example, the saved network with index 0 will
* be returned first, then the saved network with index 1, then index 2, etc. After all saved
* networks have been returned, the non-saved networks will be returned, in the decreasing order
* of their RSSI value, a network with higher RSSI value will be returned before one with lower
* RSSI value.
*
* @param listNetworkReq The ListNetwork request
* @param callback The callback which will be triggered once the BLE device sends a ListNetwork
* response.
*/
public void listNetworks(ListNetworkReq listNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] listNetworkReqBytes = listNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, listNetworkReqBytes);
}
/**
* Sends a SaveNetworkReq command to the connected BLE device. The SaveNetworkReq contains the
* network credential. A SaveNetworkResp will be sent by the BLE device and triggers the callback.
* To get the updated order of all networks, call listNetworks again.
*
* @param saveNetworkReq The SaveNetwork request.
* @param callback The callback that is triggered once the BLE device sends a SaveNetwork response.
*/
public void saveNetwork(SaveNetworkReq saveNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] saveNetworkReqBytes = saveNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, saveNetworkReqBytes);
}
/**
* Sends an EditNetworkReq command to the connected BLE device. The EditNetwork request is used
* to update the preference of a saved network. It contains the current index of the saved network
* to be updated, and the desired new index of the save network to be updated to. Both the current
* index and the new index must be one of those saved networks. Behavior is undefined if an index
* of an unsaved network is provided in the EditNetworkReq.
* To get the updated order of all networks, call listNetworks again.
*
* @param editNetworkReq The EditNetwork request.
* @param callback The callback that is triggered once the BLE device sends an EditNetwork response.
*/
public void editNetwork(EditNetworkReq editNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] editNetworkReqBytes = editNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, editNetworkReqBytes);
}
/**
* Sends a DeleteNetworkReq command to the connected BLE device. The saved network with the index
* specified in the delete network request will be deleted, making it a non-saved network again.
* To get the updated order of all networks, call listNetworks again.
*
* @param deleteNetworkReq The DeleteNetwork request.
* @param callback The callback that is triggered once the BLE device sends a DeleteNetwork response.
*/
public void deleteNetwork(DeleteNetworkReq deleteNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] deleteNetworkReqBytes = deleteNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, deleteNetworkReqBytes);
}
/**
* Get the current mtu value between device and Android phone. This method returns immediately.
* The request to get mtu value is asynchronous through BLE command. The response will be delivered
* through DeviceInfoCallback.
*
* @param callback The callback to notify app of current mtu value.
*/
public void getMtu(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getMtu() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Get the current broker endpoint on the device. This broker endpoint is used to connect to AWS
* IoT, hence, this is also the AWS IoT endpoint. This method returns immediately.
* The request is sent asynchronously through BLE command. The response will be delivered
* through DeviceInfoCallback.
*
* @param callback The callback to notify app of current broker endpoint on device.
*/
public void getBrokerEndpoint(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getBrokerEndpoint() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Get the AmazonFreeRTOS library software version running on the device. This method returns
* immediately. The request is sent asynchronously through BLE command. The response will be
* delivered through DeviceInfoCallback.
*
* @param callback The callback to notify app of current software version.
*/
public void getDeviceVersion(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getDeviceVersion() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Try to read a characteristic from the Gatt service. If pairing is enabled, it will be triggered
* by this action.
*/
private void probe() {
getDeviceVersion();
}
/**
* Initialize the Gatt services
*/
private void initialize() {
getDeviceType();
getDeviceId();
getMtu();
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_MQTT_PROXY_TX, UUID_MQTT_PROXY_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_NETWORK_TX, UUID_NETWORK_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
}
private void enableService(final String serviceUuid, final boolean enable) {
byte[] ready = new byte[1];
if (enable) {
ready[0] = 1;
} else {
ready[0] = 0;
}
switch (serviceUuid) {
case UUID_NETWORK_SERVICE:
Log.i(TAG, (enable ? "Enabling" : "Disabling") + " Wifi provisioning");
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, UUID_NETWORK_CONTROL, UUID_NETWORK_SERVICE, ready));
break;
case UUID_MQTT_PROXY_SERVICE:
if (mKeystore != null || mAWSCredential != null) {
Log.i(TAG, (enable ? "Enabling" : "Disabling") + " MQTT Proxy");
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, UUID_MQTT_PROXY_CONTROL, UUID_MQTT_PROXY_SERVICE, ready));
}
break;
default:
Log.w(TAG, "Unknown service. Ignoring.");
}
}
private void processIncomingQueue() {
try {
mIncomingMutex.acquire();
while (mIncomingQueue.size() != 0) {
BleCommand bleCommand = mIncomingQueue.poll();
Log.d(TAG, "Processing incoming queue. size: " + mIncomingQueue.size());
byte[] responseBytes = bleCommand.getData();
String cUuid = bleCommand.getCharacteristicUuid();
switch (cUuid) {
case UUID_MQTT_PROXY_TX:
handleMqttTxMessage(responseBytes);
break;
case UUID_MQTT_PROXY_TXLARGE:
try {
mTxLargeObject.write(responseBytes);
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_NETWORK_TX:
handleNwTxMessage(responseBytes);
break;
case UUID_NETWORK_TXLARGE:
try {
mTxLargeNw.write(responseBytes);
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
default:
Log.e(TAG, "Unknown characteristic " + cUuid);
}
}
mIncomingMutex.release();
} catch (InterruptedException e) {
Log.e(TAG, "Incoming mutex error, ", e);
}
}
private void registerBondStateCallback() {
mBondStateCallback = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothDevice.ACTION_BOND_STATE_CHANGED: {
int prev = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
int now = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
Log.d(TAG, "Bond state changed from " + prev + " to " + now);
/**
* If the state changed from bonding to bonded, then we have a valid bond created
* for the device.
* If discovery is not performed initiate discovery.
* If services are discovered start initialization by reading device version characteristic.
*/
if (prev == BluetoothDevice.BOND_BONDING && now == BluetoothDevice.BOND_BONDED) {
List<BluetoothGattService> services = mBluetoothGatt.getServices();
if (services == null || services.isEmpty()) {
discoverServices();
} else {
probe();
}
}
break;
}
default:
break;
}
}
};
final IntentFilter bondFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
mContext.registerReceiver(mBondStateCallback, bondFilter);
}
private void unRegisterBondStateCallback() {
if (mBondStateCallback != null) {
try {
mContext.unregisterReceiver(mBondStateCallback);
mBondStateCallback = null;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Caught exception while unregistering broadcast receiver" );
}
}
}
/**
* This is the callback for all BLE commands sent from SDK to device. The response of BLE
* command is included in the callback, together with the status code.
*/
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
Log.i(TAG, "BLE connection state changed: " + status + "; new state: "
+ AmazonFreeRTOSConstants.BleConnectionState.values()[newState]);
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
int bondState = mBluetoothDevice.getBondState();
Log.i(TAG, "Connected to GATT server.");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_CONNECTED;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
// If the device is already bonded or will not bond we can call discoverServices() immediately
if (mBluetoothDevice.getBondState() != BOND_BONDING) {
discoverServices();
} else {
registerBondStateCallback();
}
} else {
Log.i(TAG, "Disconnected from GATT server due to error or peripheral initiated disconnect.");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
disconnectFromIot();
}
unRegisterBondStateCallback();
cleanUp();
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
/**
* If auto reconnect is enabled, start a reconnect procedure in background
* using connect() method. Else close the GATT.
* Auto reconnect will be disabled when user initiates disconnect.
*/
if (!mGattAutoReconnect) {
gatt.close();
mBluetoothGatt = null;
} else {
mBluetoothGatt.connect();
}
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "Discovered Ble gatt services successfully. Bonding state: "
+ mBluetoothDevice.getBondState());
describeGattServices(mBluetoothGatt.getServices());
/**
* Trigger bonding if needed, by reading device version characteristic, if bonding is not already
* in progress by the stack.
*/
if (mBluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDING) {
probe();
}
} else {
Log.e(TAG, "onServicesDiscovered received: " + status);
disconnect();
}
processNextBleCommand();
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
byte[] responseBytes = characteristic.getValue();
Log.d(TAG, "->->-> Characteristic changed for: "
+ uuidToName.get(characteristic.getUuid().toString())
+ " with data: " + bytesToHexString(responseBytes));
BleCommand incomingCommand = new BleCommand(NOTIFICATION,
characteristic.getUuid().toString(),
characteristic.getService().getUuid().toString(), responseBytes);
mIncomingQueue.add(incomingCommand);
if (!mRWinProgress) {
processIncomingQueue();
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
int status) {
Log.d(TAG, "onDescriptorWrite for characteristic: "
+ uuidToName.get(descriptor.getCharacteristic().getUuid().toString())
+ "; Status: " + (status == 0 ? "Success" : status));
processNextBleCommand();
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
Log.i(TAG, "onMTUChanged : " + mtu + " status: " + (status == 0 ? "Success" : status));
mMtu = mtu;
mMaxPayloadLen = Math.max(mMtu - 3, 0);
// The BLE service should be initialized at this stage
if (mBleConnectionState == BleConnectionState.BLE_INITIALIZING) {
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZED;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
}
enableService(UUID_NETWORK_SERVICE, true);
enableService(UUID_MQTT_PROXY_SERVICE, true);
processNextBleCommand();
}
@Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
mRWinProgress = false;
Log.d(TAG, "->->-> onCharacteristicRead status: " + (status == 0 ? "Success. " : status));
if (status == BluetoothGatt.GATT_SUCCESS) {
// On the first successful read we enable the services
if (mBleConnectionState == BleConnectionState.BLE_CONNECTED) {
Log.d(TAG, "GATT services initializing...");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZING;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
initialize();
}
byte[] responseBytes = characteristic.getValue();
Log.d(TAG, "->->-> onCharacteristicRead: " + bytesToHexString(responseBytes));
switch (characteristic.getUuid().toString()) {
case UUID_MQTT_PROXY_TXLARGE:
try {
mTxLargeObject.write(responseBytes);
if (responseBytes.length < mMaxPayloadLen) {
byte[] largeMessage = mTxLargeObject.toByteArray();
Log.d(TAG, "MQTT Large object received from device successfully: "
+ bytesToHexString(largeMessage));
handleMqttTxMessage(largeMessage);
mTxLargeObject.reset();
} else {
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
}
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_NETWORK_TXLARGE:
try {
mTxLargeNw.write(responseBytes);
if (responseBytes.length < mMaxPayloadLen) {
byte[] largeMessage = mTxLargeNw.toByteArray();
Log.d(TAG, "NW Large object received from device successfully: "
+ bytesToHexString(largeMessage));
handleNwTxMessage(largeMessage);
mTxLargeNw.reset();
} else {
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
}
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_DEVICE_MTU:
Mtu currentMtu = new Mtu();
currentMtu.mtu = new String(responseBytes);
Log.i(TAG, "Default MTU is set to: " + currentMtu.mtu);
try {
mMtu = Integer.parseInt(currentMtu.mtu);
mMaxPayloadLen = Math.max(mMtu - 3, 0);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainMtu(mMtu);
}
setMtu(mMtu);
} catch (NumberFormatException e) {
Log.e(TAG, "Cannot parse default MTU value.");
}
break;
case UUID_IOT_ENDPOINT:
BrokerEndpoint currentEndpoint = new BrokerEndpoint();
currentEndpoint.brokerEndpoint = new String(responseBytes);
Log.i(TAG, "Current broker endpoint is set to: "
+ currentEndpoint.brokerEndpoint);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainBrokerEndpoint(currentEndpoint.brokerEndpoint);
}
break;
case UUID_DEVICE_VERSION:
Version currentVersion = new Version();
currentVersion.version = new String(responseBytes);
if (!currentVersion.version.isEmpty()) {
mAmazonFreeRTOSLibVersion = currentVersion.version;
}
Log.i(TAG, "Ble software version on device is: " + currentVersion.version);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainDeviceSoftwareVersion(currentVersion.version);
}
break;
case UUID_DEVICE_PLATFORM:
String platform = new String(responseBytes);
if (!platform.isEmpty()) {
mAmazonFreeRTOSDeviceType = platform;
}
Log.i(TAG, "Device type is: " + mAmazonFreeRTOSDeviceType);
break;
case UUID_DEVICE_ID:
String devId = new String(responseBytes);
if (!devId.isEmpty()) {
mAmazonFreeRTOSDeviceId = devId;
}
Log.i(TAG, "Device id is: " + mAmazonFreeRTOSDeviceId);
break;
default:
Log.w(TAG, "Unknown characteristic read. ");
}
}
processIncomingQueue();
processNextBleCommand();
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
mRWinProgress = false;
byte[] value = characteristic.getValue();
Log.d(TAG, "onCharacteristicWrite for: "
+ uuidToName.get(characteristic.getUuid().toString())
+ "; status: " + (status == 0 ? "Success" : status) + "; value: " + bytesToHexString(value));
if (Arrays.equals(mValueWritten, value)) {
processIncomingQueue();
processNextBleCommand();
} else {
Log.e(TAG, "values don't match!");
}
}
};
/**
* Handle mqtt messages received from device.
*
* @param message message received from device.
*/
private void handleMqttTxMessage(byte[] message) {
MessageType messageType = new MessageType();
if (!messageType.decode(message)) {
return;
}
Log.i(TAG, "Handling Mqtt Message type : " + messageType.type);
switch (messageType.type) {
case MQTT_MSG_CONNECT:
final Connect connect = new Connect();
if (connect.decode(message)) {
connectToIoT(connect);
}
break;
case MQTT_MSG_SUBSCRIBE:
final Subscribe subscribe = new Subscribe();
if (subscribe.decode(message)) {
Log.d(TAG, subscribe.toString());
subscribeToIoT(subscribe);
/*
Currently, because the IoT part of aws mobile sdk for Android
does not provide suback callback when subscribe is successful,
we create a fake suback message and send to device as a workaround.
Wait for 0.5 sec so that the subscribe is complete. Potential bug:
Message is received from the subscribed topic before suback
is sent to device.
*/
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
sendSubAck(subscribe);
}
}, 500);
}
break;
case MQTT_MSG_UNSUBSCRIBE:
final Unsubscribe unsubscribe = new Unsubscribe();
if (unsubscribe.decode(message)) {
unsubscribeToIoT(unsubscribe);
/*
TODO: add unsuback support in Aws Mobile sdk
*/
sendUnsubAck(unsubscribe);
}
break;
case MQTT_MSG_PUBLISH:
final Publish publish = new Publish();
if (publish.decode(message)) {
mMessageId = publish.getMsgID();
publishToIoT(publish);
}
break;
case MQTT_MSG_DISCONNECT:
disconnectFromIot();
break;
case MQTT_MSG_PUBACK:
/*
AWS Iot SDK currently sends pub ack back to cloud without waiting
for pub ack from device.
*/
final Puback puback = new Puback();
if (puback.decode(message)) {
Log.w(TAG, "Received mqtt pub ack from device. MsgID: " + puback.msgID);
}
break;
case MQTT_MSG_PINGREQ:
PingResp pingResp = new PingResp();
byte[] pingRespBytes = pingResp.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, pingRespBytes);
break;
default:
Log.e(TAG, "Unknown mqtt message type: " + messageType.type);
}
}
private void handleNwTxMessage(byte[] message) {
MessageType messageType = new MessageType();
if (!messageType.decode(message)) {
return;
}
Log.i(TAG, "Handling Network Message type : " + messageType.type);
switch (messageType.type) {
case LIST_NETWORK_RESP:
ListNetworkResp listNetworkResp = new ListNetworkResp();
if (listNetworkResp.decode(message) && mNetworkConfigCallback != null) {
Log.d(TAG, listNetworkResp.toString());
mNetworkConfigCallback.onListNetworkResponse(listNetworkResp);
}
break;
case SAVE_NETWORK_RESP:
SaveNetworkResp saveNetworkResp = new SaveNetworkResp();
if (saveNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onSaveNetworkResponse(saveNetworkResp);
}
break;
case EDIT_NETWORK_RESP:
EditNetworkResp editNetworkResp = new EditNetworkResp();
if (editNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onEditNetworkResponse(editNetworkResp);
}
break;
case DELETE_NETWORK_RESP:
DeleteNetworkResp deleteNetworkResp = new DeleteNetworkResp();
if (deleteNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onDeleteNetworkResponse(deleteNetworkResp);
}
break;
default:
Log.e(TAG, "Unknown network message type: " + messageType.type);
}
}
private void connectToIoT(final Connect connect) {
if (mMqttConnectionState == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.w(TAG, "Already connected to IOT, sending connack to device again.");
sendConnAck();
return;
}
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
Log.w(TAG, "Previous connection is active, please retry or disconnect mqtt first.");
return;
}
mIotMqttManager = new AWSIotMqttManager(connect.clientID, connect.brokerEndpoint);
Map<String, String> userMetaData = new HashMap<>();
userMetaData.put("AFRSDK", "Android");
//userMetaData.put("AFRSDKVersion", AMAZONFREERTOS_SDK_VERSION);
userMetaData.put("AFRLibVersion", mAmazonFreeRTOSLibVersion);
userMetaData.put("Platform", mAmazonFreeRTOSDeviceType);
userMetaData.put("AFRDevID", mAmazonFreeRTOSDeviceId);
mIotMqttManager.updateUserMetaData(userMetaData);
AWSIotMqttClientStatusCallback mqttClientStatusCallback = new AWSIotMqttClientStatusCallback() {
@Override
public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) {
Log.i(TAG, "mqtt connection status changed to: " + status);
switch (status) {
case Connected:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected;
//sending connack
if (isBLEConnected() && mBluetoothGatt != null) {
sendConnAck();
} else {
Log.e(TAG, "Cannot send CONNACK because BLE connection is: " + mBleConnectionState);
}
break;
case Connecting:
case Reconnecting:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connecting;
break;
case ConnectionLost:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected;
break;
default:
Log.e(TAG, "Unknown mqtt connection state: " + status);
}
}
};
if (mKeystore != null) {
Log.i(TAG, "Connecting to IoT using KeyStore: " + connect.brokerEndpoint);
mIotMqttManager.connect(mKeystore, mqttClientStatusCallback);
} else {
Log.i(TAG, "Connecting to IoT using AWS credential: " + connect.brokerEndpoint);
mIotMqttManager.connect(mAWSCredential, mqttClientStatusCallback);
}
}
private void disconnectFromIot() {
if (mIotMqttManager != null) {
try {
mIotMqttManager.disconnect();
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected;
} catch (Exception e) {
Log.e(TAG, "Mqtt disconnect error: ", e);
}
}
}
private void subscribeToIoT(final Subscribe subscribe) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot subscribe because mqtt state is not connected.");
return;
}
for (int i = 0; i < subscribe.topics.size(); i++) {
try {
String topic = subscribe.topics.get(i);
Log.i(TAG, "Subscribing to IoT on topic : " + topic);
final int QoS = subscribe.qoSs.get(i);
AWSIotMqttQos qos = (QoS == 0 ? AWSIotMqttQos.QOS0 : AWSIotMqttQos.QOS1);
mIotMqttManager.subscribeToTopic(topic, qos, new AWSIotMqttNewMessageCallback() {
@Override
public void onMessageArrived(final String topic, final byte[] data) {
String message = new String(data, StandardCharsets.UTF_8);
Log.i(TAG, " Message arrived on topic: " + topic);
Log.v(TAG, " Message: " + message);
Publish publish = new Publish(
MQTT_MSG_PUBLISH,
topic,
mMessageId,
QoS,
data
);
publishToDevice(publish);
}
});
} catch (Exception e) {
Log.e(TAG, "Subscription error.", e);
}
}
}
private void unsubscribeToIoT(final Unsubscribe unsubscribe) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot unsubscribe because mqtt state is not connected.");
return;
}
for (int i = 0; i < unsubscribe.topics.size(); i++) {
try {
String topic = unsubscribe.topics.get(i);
Log.i(TAG, "UnSubscribing to IoT on topic : " + topic);
mIotMqttManager.unsubscribeTopic(topic);
} catch (Exception e) {
Log.e(TAG, "Unsubscribe error.", e);
}
}
}
private void publishToIoT(final Publish publish) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot publish message to IoT because mqtt connection state is not connected.");
return;
}
AWSIotMqttMessageDeliveryCallback deliveryCallback = new AWSIotMqttMessageDeliveryCallback() {
@Override
public void statusChanged(MessageDeliveryStatus messageDeliveryStatus, Object o) {
Log.d(TAG, "Publish msg delivery status: " + messageDeliveryStatus.toString());
if (messageDeliveryStatus == MessageDeliveryStatus.Success && publish.getQos() == 1) {
sendPubAck(publish);
}
}
};
try {
String topic = publish.getTopic();
byte[] data = publish.getPayload();
Log.i(TAG, "Sending mqtt message to IoT on topic: " + topic
+ " message: " + new String(data)
+ " MsgID: " + publish.getMsgID());
mIotMqttManager.publishData(data, topic, AWSIotMqttQos.values()[publish.getQos()],
deliveryCallback, null);
} catch (Exception e) {
Log.e(TAG, "Publish error.", e);
}
}
private void sendConnAck() {
Connack connack = new Connack();
connack.type = MQTT_MSG_CONNACK;
connack.status = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected.ordinal();
byte[] connackBytes = connack.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, connackBytes);
}
private boolean isBLEConnected() {
return mBleConnectionState == BleConnectionState.BLE_CONNECTED ||
mBleConnectionState == BleConnectionState.BLE_INITIALIZED ||
mBleConnectionState == BleConnectionState.BLE_INITIALIZING;
}
private void sendSubAck(final Subscribe subscribe) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send SUB ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending SUB ACK back to device.");
Suback suback = new Suback();
suback.type = MQTT_MSG_SUBACK;
suback.msgID = subscribe.msgID;
suback.status = subscribe.qoSs.get(0);
byte[] subackBytes = suback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, subackBytes);
}
private void sendUnsubAck(final Unsubscribe unsubscribe) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send Unsub ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending Unsub ACK back to device.");
Unsuback unsuback = new Unsuback();
unsuback.type = MQTT_MSG_UNSUBACK;
unsuback.msgID = unsubscribe.msgID;
byte[] unsubackBytes = unsuback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, unsubackBytes);
}
private void sendPubAck(final Publish publish) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send PUB ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending PUB ACK back to device. MsgID: " + publish.getMsgID());
Puback puback = new Puback();
puback.type = MQTT_MSG_PUBACK;
puback.msgID = publish.getMsgID();
byte[] pubackBytes = puback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, pubackBytes);
}
private void publishToDevice(final Publish publish) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot deliver mqtt message to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.d(TAG, "Sending received mqtt message back to device, topic: " + publish.getTopic()
+ " payload bytes: " + bytesToHexString(publish.getPayload())
+ " MsgID: " + publish.getMsgID());
byte[] publishBytes = publish.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, publishBytes);
}
private void discoverServices() {
if (isBLEConnected() && mBluetoothGatt != null) {
sendBleCommand(new BleCommand(DISCOVER_SERVICES));
} else {
Log.w(TAG, "Bluetooth connection state is not connected.");
}
}
private void setMtu(int mtu) {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.i(TAG, "Setting mtu to: " + mtu);
sendBleCommand(new BleCommand(REQUEST_MTU, mtu));
} else {
Log.w(TAG, "Bluetooth connection state is not connected.");
}
}
private boolean getMtu() {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.d(TAG, "Getting current MTU.");
sendBleCommand(new BleCommand(READ_CHARACTERISTIC, UUID_DEVICE_MTU, UUID_DEVICE_INFORMATION_SERVICE));
return true;
} else {
Log.w(TAG, "Bluetooth is not connected.");
return false;
}
}
private boolean getBrokerEndpoint() {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.d(TAG, "Getting broker endpoint.");
sendBleCommand(new BleCommand(READ_CHARACTERISTIC, UUID_IOT_ENDPOINT, UUID_DEVICE_INFORMATION_SERVICE));
return true;
} else {
Log.w(TAG, "Bluetooth is not connected.");
return false;
}
}
private boolean getDeviceVersion() {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.d(TAG, "Getting ble software version on device.");
sendBleCommand(new BleCommand(READ_CHARACTERISTIC, UUID_DEVICE_VERSION, UUID_DEVICE_INFORMATION_SERVICE));
return true;
} else {
Log.w(TAG, "Bluetooth is not connected.");
return false;
}
}
private boolean getDeviceType() {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.d(TAG, "Getting device type...");
sendBleCommand(new BleCommand(READ_CHARACTERISTIC, UUID_DEVICE_PLATFORM, UUID_DEVICE_INFORMATION_SERVICE));
return true;
} else {
Log.w(TAG, "Bluetooth is not connected.");
return false;
}
}
private boolean getDeviceId() {
if (isBLEConnected() && mBluetoothGatt != null) {
Log.d(TAG, "Getting device cert id...");
sendBleCommand(new BleCommand(READ_CHARACTERISTIC, UUID_DEVICE_ID, UUID_DEVICE_INFORMATION_SERVICE));
return true;
} else {
Log.w(TAG, "Bluetooth is not connected.");
return false;
}
}
private void sendDataToDevice(final String service, final String rx, final String rxlarge, byte[] data) {
if (data != null) {
if (data.length < mMaxPayloadLen) {
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, rx, service, data));
} else {
mTotalPackets = data.length / mMaxPayloadLen + 1;
Log.i(TAG, "This message is larger than max payload size: " + mMaxPayloadLen
+ ". Breaking down to " + mTotalPackets + " packets.");
mPacketCount = 0; //reset packet count
while (mMaxPayloadLen * mPacketCount <= data.length) {
byte[] packet = Arrays.copyOfRange(data, mMaxPayloadLen * mPacketCount,
Math.min(data.length, mMaxPayloadLen * mPacketCount + mMaxPayloadLen));
mPacketCount++;
Log.d(TAG, "Packet #" + mPacketCount + ": " + bytesToHexString(packet));
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, rxlarge, service, packet));
}
}
}
}
private void sendBleCommand(final BleCommand command) {
if (UUID_MQTT_PROXY_SERVICE.equals(command.getServiceUuid())) {
mMqttQueue.add(command);
} else {
mNetworkQueue.add(command);
}
processBleCommandQueue();
}
private void processBleCommandQueue() {
try {
mutex.acquire();
if (mBleOperationInProgress) {
Log.d(TAG, "Ble operation is in progress. mqtt queue: " + mMqttQueue.size()
+ " network queue: " + mNetworkQueue.size());
} else {
if (mMqttQueue.peek() == null && mNetworkQueue.peek() == null) {
Log.d(TAG, "There's no ble command in the queue.");
mBleOperationInProgress = false;
} else {
mBleOperationInProgress = true;
BleCommand bleCommand;
if (mNetworkQueue.peek() != null && mMqttQueue.peek() != null) {
if (rr) {
bleCommand = mMqttQueue.poll();
} else {
bleCommand = mNetworkQueue.poll();
}
rr = !rr;
} else if (mNetworkQueue.peek() != null) {
bleCommand = mNetworkQueue.poll();
} else {
bleCommand = mMqttQueue.poll();
}
Log.d(TAG, "Processing BLE command: " + bleCommand.getType()
+ " remaining mqtt queue " + mMqttQueue.size()
+ ", network queue " + mNetworkQueue.size());
boolean commandSent = false;
switch (bleCommand.getType()) {
case WRITE_DESCRIPTOR:
if (writeDescriptor(bleCommand.getServiceUuid(), bleCommand.getCharacteristicUuid())) {
commandSent = true;
}
break;
case WRITE_CHARACTERISTIC:
if (writeCharacteristic(bleCommand.getServiceUuid(), bleCommand.getCharacteristicUuid(),
bleCommand.getData())) {
commandSent = true;
}
break;
case READ_CHARACTERISTIC:
if (readCharacteristic(bleCommand.getServiceUuid(), bleCommand.getCharacteristicUuid())) {
commandSent = true;
}
break;
case DISCOVER_SERVICES:
if (mBluetoothGatt.discoverServices()) {
commandSent = true;
} else {
Log.e(TAG, "Failed to discover services!");
}
break;
case REQUEST_MTU:
if (mBluetoothGatt.requestMtu(ByteBuffer.wrap(bleCommand.getData()).getInt())) {
commandSent = true;
} else {
Log.e(TAG, "Failed to set MTU.");
}
break;
default:
Log.w(TAG, "Unknown Ble command, cannot process.");
}
if (commandSent) {
mHandler.postDelayed(resetOperationInProgress, BLE_COMMAND_TIMEOUT);
} else {
mHandler.post(resetOperationInProgress);
}
}
}
mutex.release();
} catch (InterruptedException e) {
Log.e(TAG, "Mutex error", e);
}
}
private Runnable resetOperationInProgress = new Runnable() {
@Override
public void run() {
Log.e(TAG, "Ble command failed to be sent OR timeout after " + BLE_COMMAND_TIMEOUT + "ms");
// If current ble command timed out, process the next ble command.
if (mBluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDING) {
processNextBleCommand();
}
}
};
private void processNextBleCommand() {
mHandler.removeCallbacks(resetOperationInProgress);
mBleOperationInProgress = false;
processBleCommandQueue();
}
private boolean writeDescriptor(final String serviceUuid, final String characteristicUuid) {
BluetoothGattCharacteristic characteristic = getCharacteristic(serviceUuid, characteristicUuid);
if (characteristic != null) {
mBluetoothGatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
convertFromInteger(0x2902));
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
return true;
} else {
Log.w(TAG, "There's no such descriptor on characteristic: " + characteristicUuid);
}
}
return false;
}
private boolean writeCharacteristic(final String serviceUuid, final String characteristicUuid, final byte[] value) {
BluetoothGattCharacteristic characteristic = getCharacteristic(serviceUuid, characteristicUuid);
if (characteristic != null) {
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
Log.d(TAG, "<-<-<- Writing to characteristic: " + uuidToName.get(characteristicUuid)
+ " with data: " + bytesToHexString(value));
mValueWritten = value;
characteristic.setValue(value);
if (!mBluetoothGatt.writeCharacteristic(characteristic)) {
mRWinProgress = false;
Log.e(TAG, "Failed to write characteristic.");
} else {
mRWinProgress = true;
return true;
}
}
return false;
}
private BluetoothGattCharacteristic getCharacteristic(final String serviceUuid,
final String characteristicUuid) {
BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(serviceUuid));
if (service == null) {
Log.w(TAG, "There's no such service found with uuid: " + serviceUuid);
return null;
}
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUuid));
if (characteristic == null) {
Log.w(TAG, "There's no such characteristic with uuid: " + characteristicUuid);
return null;
}
return characteristic;
}
private boolean readCharacteristic(final String serviceUuid, final String characteristicUuid) {
BluetoothGattCharacteristic characteristic = getCharacteristic(serviceUuid, characteristicUuid);
if (characteristic != null) {
Log.d(TAG, "<-<-<- Reading from characteristic: " + uuidToName.get(characteristicUuid));
if (!mBluetoothGatt.readCharacteristic(characteristic)) {
mRWinProgress = false;
Log.e(TAG, "Failed to read characteristic.");
} else {
mRWinProgress = true;
return true;
}
}
return false;
}
private static void describeGattServices(List<BluetoothGattService> gattServices) {
for (BluetoothGattService service : gattServices) {
Log.d(TAG, "GattService: " + service.getUuid());
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
Log.d(TAG, " |-characteristics: " +
(uuidToName.containsKey(characteristic.getUuid().toString()) ?
uuidToName.get(characteristic.getUuid().toString()) : characteristic.getUuid()));
}
}
}
private static UUID convertFromInteger(int i) {
final long MSB = 0x0000000000001000L;
final long LSB = 0x800000805f9b34fbL;
long value = i & 0xFFFFFFFF;
return new UUID(MSB | (value << 32), LSB);
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (int i = 0; i < bytes.length; i++) {
formatter.format("%02x", bytes[i]);
if (!VDBG && i > 10) {
break;
}
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
AmazonFreeRTOSDevice aDevice = (AmazonFreeRTOSDevice) obj;
return Objects.equals(aDevice.mBluetoothDevice.getAddress(), mBluetoothDevice.getAddress());
}
}
| 8,985 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/BleConnectionStatusCallback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
/**
* This is a callback to notify the app of BLE connection state change.
*/
public abstract class BleConnectionStatusCallback {
/**
* This callback is triggered when BLE connection between SDK and device has changed. The app
* @param connectionStatus The BLE connection state.
*/
public void onBleConnectionStatusChanged(AmazonFreeRTOSConstants.BleConnectionState connectionStatus) {}
}
| 8,986 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/MessageType.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.util.List;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* This class represents the message type.
*/
public class MessageType {
private static final String TAG = "MessageType";
private static final String TYPE_KEY = "w";
/**
* MQTT message type.
*/
public int type;
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,987 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/BleScanResultCallback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import android.bluetooth.le.ScanResult;
/**
* This is a callback to notify app of BLE Scan results.
*/
public abstract class BleScanResultCallback {
/**
* This method is called when a nearby BLE device is found during scanning.
* @param result BLE ScanResult
*/
public void onBleScanResult(ScanResult result){}
public void onBleScanFailed(int errorcode) {}
}
| 8,988 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/AmazonFreeRTOSManager.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import java.security.KeyStore;
import java.util.Arrays;
import android.os.ParcelUuid;
import android.util.Log;
import com.amazonaws.auth.AWSCredentialsProvider;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import lombok.NonNull;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.*;
public class AmazonFreeRTOSManager {
private static final String TAG = "AmazonFreeRTOSManager";
private Context mContext;
private Handler mScanHandler;
private HandlerThread mScanHandlerThread;
private boolean mScanning = false;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private List<ScanFilter> mScanFilters = Arrays.asList(
new ScanFilter.Builder().setServiceUuid(
new ParcelUuid(UUID.fromString(UUID_AmazonFreeRTOS))).build());
private Map<String, AmazonFreeRTOSDevice> mAFreeRTOSDevices = new HashMap<>();
private BleScanResultCallback mBleScanResultCallback;
/**
* Construct an AmazonFreeRTOSManager instance.
*
* @param context The app context. Should be passed in by the app that creates a new instance
* of AmazonFreeRTOSManager.
* @param bluetoothAdapter BluetoothAdaptor passed in by the app.
*/
public AmazonFreeRTOSManager(Context context, BluetoothAdapter bluetoothAdapter) {
mContext = context;
mBluetoothAdapter = bluetoothAdapter;
}
/**
* Setting the criteria for which exact the BLE devices to scan for. This overrides the default
* mScanFilters which is by default set to scan for UUID_AmazonFreeRTOS.
*
* @param filters The list of ScanFilter for BLE devices.
*/
public void setScanFilters(List<ScanFilter> filters) {
mScanFilters = filters;
}
/**
* Start scanning of nearby BLE devices. It filters the scan result only with AmazonFreeRTOS
* service UUID unless setScanFilters was explicitly called. It keeps scanning for a period of
* AmazonFreeRTOSConstants.class#SCAN_PERIOD ms, then stops the scanning automatically.
* The scan result is passed back through the BleScanResultCallback. If at the time of calling
* this API, there's already an ongoing scanning, then this will return immediately without
* starting another scan.
*
* @param scanResultCallback The callback to notify the calling app of the scanning result. The
* callback will be triggered, every time it finds a BLE device
* nearby that meets the ScanFilter criteria.
*/
public void startScanDevices(final BleScanResultCallback scanResultCallback) {
startScanDevices(scanResultCallback, SCAN_PERIOD);
}
/**
* Start scanning nearby BLE devices for a total duration of scanDuration milliseconds.
*
* @param scanResultCallback The callback to notify the calling app of the scanning result.
* @param scanDuration The duration of scanning. Keep scanning if 0.
*/
public void startScanDevices(final BleScanResultCallback scanResultCallback, long scanDuration) {
if (scanResultCallback == null) {
throw new IllegalArgumentException("BleScanResultCallback is null");
}
mBleScanResultCallback = scanResultCallback;
if (mBluetoothAdapter != null) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (mScanHandlerThread == null) {
mScanHandlerThread = new HandlerThread("ScanBleDeviceThread");
mScanHandlerThread.start();
mScanHandler = new Handler(mScanHandlerThread.getLooper());
}
scanLeDevice(scanDuration);
} else {
Log.e(TAG, "BluetoothAdaptor is null, please enable bluetooth.");
}
}
private void scanLeDevice(long duration) {
if (mScanning) {
Log.d(TAG, "Scanning is already in progress.");
return;
}
// Stops scanning after a pre-defined scan period.
if (duration != 0) {
mScanHandler.postDelayed(new Runnable() {
@Override
public void run() {
stopScanDevices();
}
}, duration);
}
Log.i(TAG, "Starting ble device scan");
mScanning = true;
ScanSettings scanSettings = new ScanSettings.Builder().build();
mBluetoothLeScanner.startScan(mScanFilters, scanSettings, mScanCallback);
}
/**
* Stop scanning of nearby BLE devices. If there's no ongoing BLE scanning, then it will return
* immediately.
*/
public void stopScanDevices() {
if (!mScanning) {
Log.w(TAG, "No ble device scan is currently in progress.");
return;
}
Log.i(TAG, "Stopping ble device scan");
mBluetoothLeScanner.stopScan(mScanCallback);
mScanning = false;
}
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d(TAG, "Found ble device: " + result.getDevice().getAddress()
+ " RSSI: " + result.getRssi());
if (mBleScanResultCallback != null) {
mBleScanResultCallback.onBleScanResult(result);
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e(TAG, "Error when scanning ble device. Error code: " + errorCode);
if (mBleScanResultCallback != null) {
mBleScanResultCallback.onBleScanFailed(errorCode);
}
}
};
/**
* Connect to the BLE device, and notify the connection state via BleConnectionStatusCallback.
*
* @param connectionStatusCallback The callback to notify app whether the BLE connection is
* successful. Must not be null.
* @param btDevice the BLE device to be connected to.
* @param cp the AWSCredential used to connect to AWS IoT.
* @param autoReconnect auto reconnect to device after unexpected disconnect
*/
public AmazonFreeRTOSDevice connectToDevice(@NonNull final BluetoothDevice btDevice,
@NonNull final BleConnectionStatusCallback connectionStatusCallback,
final AWSCredentialsProvider cp,
final boolean autoReconnect) {
AmazonFreeRTOSDevice aDevice = new AmazonFreeRTOSDevice(btDevice, mContext, cp);
mAFreeRTOSDevices.put(btDevice.getAddress(), aDevice);
aDevice.connect(connectionStatusCallback, autoReconnect);
return aDevice;
}
/**
* Connect to the BLE device, and notify the connection state via BleConnectionStatusCallback.
*
* @param connectionStatusCallback The callback to notify app whether the BLE connection is
* successful. Must not be null.
* @param btDevice the BLE device to be connected to.
* @param ks the KeyStore that contains certificate used to connect to AWS IoT.
* @param autoReconnect auto reconnect to device after unexpected disconnect
*/
public AmazonFreeRTOSDevice connectToDevice(@NonNull final BluetoothDevice btDevice,
@NonNull final BleConnectionStatusCallback connectionStatusCallback,
final KeyStore ks,
final boolean autoReconnect) {
AmazonFreeRTOSDevice aDevice = new AmazonFreeRTOSDevice(btDevice, mContext, ks);
mAFreeRTOSDevices.put(btDevice.getAddress(), aDevice);
aDevice.connect(connectionStatusCallback, autoReconnect);
return aDevice;
}
/**
* Closing BLE connection for the AmazonFreeRTOSDevice, reset all variables, and disconnect from AWS IoT.
*
* @param aDevice The AmazonFreeRTOSDevice to be disconnected.
*/
public void disconnectFromDevice(@NonNull final AmazonFreeRTOSDevice aDevice) {
mAFreeRTOSDevices.remove(aDevice.getMBluetoothDevice().getAddress());
aDevice.disconnect();
}
/**
* Get the instance of AmazonFreeRTOSDevice given the mac address of the BLE device
*
* @param macAddr the mac address of the connected BLE device
* @return the corresponding AmazonFreeRTOSDevice instance that represents the connected BLE device.
*/
public AmazonFreeRTOSDevice getConnectedDevice(String macAddr) {
return mAFreeRTOSDevices.get(macAddr);
}
}
| 8,989 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Unsubscribe.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.builder.ArrayBuilder;
import co.nstant.in.cbor.builder.MapBuilder;
import co.nstant.in.cbor.model.Array;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* This class represents the MQTT UNSUBSCRIBE message.
*/
public class Unsubscribe {
private static final String TAG = "MqttUnsubscribe";
private static final String TYPE_KEY = "w";
private static final String TOPICS_KEY = "v";
private static final String MSGID_KEY = "i";
/**
* MQTT message type.
*/
public int type;
/**
* Arrary of topics to unsubscribe.
*/
public List<String> topics = new ArrayList<>();
/**
* MQTT message ID.
*/
public int msgID;
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("UnSubscribe message: ");
stringBuilder.append("\n type: " + type);
stringBuilder.append("\n msgId: " + msgID);
for (int i = 0; i < topics.size(); i++) {
stringBuilder.append("\n topic: " + topics.get(i));
}
return stringBuilder.toString();
}
public byte[] encode() {
byte[] unsubscribeBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ArrayBuilder<MapBuilder<CborBuilder>> topicsArray = new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.putArray(TOPICS_KEY);
for (String topic : topics) {
topicsArray = topicsArray.add(topic);
}
List<DataItem> cbordata = topicsArray.end().end().build();
new CborEncoder(baos).encode(cbordata);
unsubscribeBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return unsubscribeBytes;
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(MSGID_KEY));
msgID = ((Number) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(TOPICS_KEY));
List<DataItem> topicDataItems = ((Array) dataItem).getDataItems();
for (DataItem topicDataItem : topicDataItems) {
topics.add(((UnicodeString) topicDataItem).getString());
}
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,990 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Publish.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.ByteString;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
/**
* This class represents the MQTT PUBLISH message.
*/
@AllArgsConstructor
@NoArgsConstructor
public class Publish {
private static final String TAG = "MqttPublish";
private static final String TYPE_KEY = "w";
private static final String TOPIC_KEY = "u";
private static final String MSGID_KEY = "i";
private static final String QOS_KEY = "n";
private static final String PAYLOAD_KEY = "k";
/**
* MQTT message type.
*/
private int type;
/**
* MQTT PUBLISH message topic.
*/
private String topic;
/**
* MQTT message ID.
*/
private int msgID;
/**
* MQTT PUBLISH message QOS.
*/
private int qoS;
/**
* The data in the MQTT PUBLISH message.
*/
private byte[] payloadBytes;
public String toString() {
return String.format(" Publish message -> \n topic:%s\n msgID:%d\n qos:%d\n payload:%s",
topic, msgID, qoS, new String(payloadBytes));
}
public String getTopic() {
return topic;
}
public byte[] getPayload() {
return payloadBytes;
}
public int getMsgID() {
return msgID;
}
public int getQos() {
return qoS;
}
public byte[] encode() {
byte[] publishBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(TOPIC_KEY, topic)
.put(MSGID_KEY, msgID)
.put(QOS_KEY, qoS)
.put(PAYLOAD_KEY, payloadBytes)
.end()
.build());
publishBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return publishBytes;
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(TOPIC_KEY));
topic = ((UnicodeString) dataItem).getString();
dataItem = map.get(new UnicodeString(QOS_KEY));
qoS = ((Number) dataItem).getValue().intValue();
if (qoS != 0) {
dataItem = map.get(new UnicodeString(MSGID_KEY));
msgID = ((Number) dataItem).getValue().intValue();
}
dataItem = map.get(new UnicodeString(PAYLOAD_KEY));
payloadBytes = ((ByteString) dataItem).getBytes();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,991 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Suback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
/**
* This class represents the MQTT SUBACK message.
*/
public class Suback {
private static final String TAG = "MqttSuback";
private static final String TYPE_KEY = "w";
private static final String MSGID_KEY = "i";
private static final String STATUS_KEY = "s";
/**
* MQTT message type.
*/
public int type;
/**
* MQTT message ID.
*/
public int msgID;
/**
* MQTT SUBACK status. This is set to the QOS number in the corresponding MQTT SUBSCRIBE
* message, to which this SUBACK is acknowledging.
*/
public int status;
public byte[] encode() {
byte[] subackBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(MSGID_KEY, msgID)
.put(STATUS_KEY, status)
.end()
.build());
subackBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return subackBytes;
}
}
| 8,992 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Subscribe.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.builder.ArrayBuilder;
import co.nstant.in.cbor.builder.MapBuilder;
import co.nstant.in.cbor.model.Array;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* This class represents the MQTT SUBSCRIBE message.
*/
public class Subscribe {
private static final String TAG = "MqttSubscribe";
private static final String TYPE_KEY = "w";
private static final String TOPICS_KEY = "v";
private static final String MSGID_KEY = "i";
private static final String QOSS_KEY = "o";
/**
* MQTT message type.
*/
public int type;
/**
* Arrary of topics to subscribe to.
*/
public List<String> topics = new ArrayList<>();
/**
* MQTT message ID.
*/
public int msgID;
/**
* Arrary of QOS for each subscribe topic.
*/
public List<Integer> qoSs = new ArrayList<>();
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Subscribe message: ");
stringBuilder.append("\n type: " + type);
stringBuilder.append("\n msgId: " + msgID);
for (int i = 0; i < topics.size(); i++) {
stringBuilder.append("\n topic: " + topics.get(i) + ", qos: " + qoSs.get(i));
}
return stringBuilder.toString();
}
public byte[] encode() {
byte[] subscribeBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ArrayBuilder<MapBuilder<CborBuilder>> topicsArray = new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.putArray(TOPICS_KEY);
for (String topic : topics) {
topicsArray = topicsArray.add(topic);
}
MapBuilder<CborBuilder> map = topicsArray.end();
ArrayBuilder<MapBuilder<CborBuilder>> qosArray = map.put(MSGID_KEY, msgID)
.putArray(QOSS_KEY);
for (int qos : qoSs) {
qosArray = qosArray.add(qos);
}
List<DataItem> cbordata = qosArray.end().end().build();
new CborEncoder(baos).encode(cbordata);
subscribeBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return subscribeBytes;
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(MSGID_KEY));
msgID = ((Number) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(TOPICS_KEY));
List<DataItem> topicDataItems = ((Array) dataItem).getDataItems();
for (DataItem topicDataItem : topicDataItems) {
topics.add(((UnicodeString) topicDataItem).getString());
}
dataItem = map.get(new UnicodeString(QOSS_KEY));
List<DataItem> qosDataItems = ((Array) dataItem).getDataItems();
for (DataItem qosDataItem : qosDataItems) {
qoSs.add(((UnsignedInteger) qosDataItem).getValue().intValue());
}
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,993 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/MqttProxyControl.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
/**
* This class represents the MQTT proxy state. SDK sends this object to device to switch on/off
* MQTT proxy.
*/
public class MqttProxyControl {
private static final String TAG = "MqttProxyControl";
private static final String PROXYSTATE_KEY = "l";
/**
* The state of MQTT proxy.
*/
public int proxyState;
public byte[] encode() {
byte[] mqttProxyControlBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(PROXYSTATE_KEY, proxyState)
.end()
.build());
mqttProxyControlBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return mqttProxyControlBytes;
}
}
| 8,994 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Puback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* This class represents the MQTT PUBACK message.
*/
public class Puback {
private static final String TAG = "MqttPuback";
private static final String TYPE_KEY = "w";
private static final String MSGID_KEY = "i";
/**
* MQTT message type.
*/
public int type;
/**
* MQTT message ID.
*/
public int msgID;
public byte[] encode() {
byte[] pubackBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(MSGID_KEY, msgID)
.end()
.build());
pubackBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return pubackBytes;
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(MSGID_KEY));
msgID = ((Number) dataItem).getValue().intValue();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,995 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Connack.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
/**
* This class represents the MQTT CONNACK message.
*/
public class Connack {
private static final String TAG = "MqttConnack";
private static final String TYPE_KEY = "w";
private static final String STATUS_KEY = "s";
/**
* MQTT message type.
*/
public int type;
/**
* The MQTT connection status defined in {@code MqttConnectionState} enum.
*/
public int status;
public byte[] encode() {
byte[] connackBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(STATUS_KEY, status)
.end()
.build());
connackBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return connackBytes;
}
}
| 8,996 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/PingResp.java | package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.MQTT_MSG_PINGRESP;
public class PingResp {
private static final String TAG = "PingResp";
private static final String TYPE_KEY = "w";
public byte[] encode() {
byte[] bytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, MQTT_MSG_PINGRESP)
.end()
.build());
bytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return bytes;
}
}
| 8,997 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/PingReq.java | package software.amazon.freertos.amazonfreertossdk.mqttproxy;
public class PingReq {
}
| 8,998 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Connect.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.SimpleValue;
import co.nstant.in.cbor.model.SimpleValueType;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* This class represents the MQTT CONNECT message.
*/
public class Connect {
private static final String TAG = "MqttConnect";
private static final String TYPE_KEY = "w";
private static final String CLIENTID_KEY = "d";
private static final String BROKERENDPOINT_KEY = "a";
private static final String CLEANSESSION_KEY = "c";
/**
* MQTT message type.
*/
public int type;
/**
* MQTT client id.
*/
public String clientID;
/**
* MQTT broker endpoint.
*/
public String brokerEndpoint;
/**
* MQTT clean session.
*/
public boolean cleanSession;
public String toString() {
return String.format(" Connect message -> \n clientID: %s\n endpoint: %s\n cleansession: %s",
clientID, brokerEndpoint, (cleanSession? "true":"false") );
}
public byte[] encode() {
byte[] connectBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(CLIENTID_KEY, clientID)
.put(BROKERENDPOINT_KEY, brokerEndpoint)
.put(CLEANSESSION_KEY, cleanSession)
.end()
.build());
connectBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return connectBytes;
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(TYPE_KEY));
type = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(CLIENTID_KEY));
clientID = ((UnicodeString) dataItem).getString();
dataItem = map.get(new UnicodeString(BROKERENDPOINT_KEY));
brokerEndpoint = ((UnicodeString) dataItem).getString();
dataItem = map.get(new UnicodeString(CLEANSESSION_KEY));
cleanSession = (((SimpleValue) dataItem).getSimpleValueType() == SimpleValueType.TRUE) ? true:false;
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 8,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.