feat: Add option to clear home screen in settings (#6125)

Signed-off-by: abhixv <abhi.sharma1@hotmail.com>
This commit is contained in:
Abhishek Sharma authored and Pun Butrach committed 2026-01-10 20:51:01 +07:00
1 parent 9898749619
commit 5f3a03f4fb
1577 files changed
+112559 -80244

No files matched your search

+163 -208
View File
@@ -12,14 +12,18 @@
* 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.
*
* Modifications copyright 2021, Lawnchair
*/
package com.android.launcher3.folder;
import static android.text.TextUtils.isEmpty;
import static com.android.launcher3.Flags.enableLauncherVisualRefresh;
import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.LauncherState.EDIT_MODE;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
@@ -27,7 +31,6 @@ import static com.android.launcher3.config.FeatureFlags.ALWAYS_USE_HARDWARE_OPTI
import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_LABEL_UPDATED;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROP_COMPLETED;
import static com.android.launcher3.model.data.FolderInfo.willAcceptItemType;
import static com.android.launcher3.testing.shared.TestProtocol.FOLDER_OPENED_MESSAGE;
import static com.android.launcher3.util.window.RefreshRateTracker.getSingleFrameMs;
@@ -65,12 +68,11 @@ import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.WindowInsetsCompat;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Alarm;
import com.android.launcher3.CellLayout;
@@ -96,24 +98,26 @@ import com.android.launcher3.logger.LauncherAtom.ToState;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.logging.StatsLogManager.StatsLogger;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.FolderInfo.FolderListener;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemFactory;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.LauncherBindableItemsContainer;
import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.views.ClipPathView;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import com.androidinternal.graphics.ColorUtils;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -121,7 +125,6 @@ import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.theme.color.ColorOption;
import app.lawnchair.theme.color.tokens.ColorTokens;
@@ -133,9 +136,8 @@ import app.lawnchair.util.LawnchairUtilsKt;
* Represents a set of icons chosen by the user or generated by the system.
*/
public class Folder extends AbstractFloatingView implements ClipPathView, DragSource,
View.OnLongClickListener, DropTarget, TextView.OnEditorActionListener,
View.OnFocusChangeListener, DragListener, ExtendedEditText.OnBackKeyListener,
LauncherBindableItemsContainer {
View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
View.OnFocusChangeListener, DragListener, ExtendedEditText.OnBackKeyListener {
private static final String TAG = "Launcher.Folder";
private static final boolean DEBUG = false;
@@ -190,6 +192,15 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return o instanceof ItemInfo info && willAcceptItemType(info.itemType);
}
/**
* Checks if {@code itemType} is a type that can be placed in folders.
*/
public static boolean willAcceptItemType(int itemType) {
return itemType == ITEM_TYPE_APPLICATION
|| itemType == ITEM_TYPE_DEEP_SHORTCUT
|| itemType == ITEM_TYPE_APP_PAIR;
}
private Alarm mReorderAlarm = new Alarm(Looper.getMainLooper());
private Alarm mOnExitAlarm = new Alarm(Looper.getMainLooper());
private Alarm mOnScrollHintAlarm = new Alarm(Looper.getMainLooper());
@@ -229,26 +240,23 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
private Path mClipPath;
@ViewDebug.ExportedProperty(category = "launcher",
mapping = {
@ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"),
@ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
@ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
})
mapping = {
@ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"),
@ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
@ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
})
private int mState = STATE_CLOSED;
private final List<OnFolderStateChangedListener> mOnFolderStateChangedListeners =
new ArrayList<>();
new ArrayList<>();
private OnFolderStateChangedListener mPriorityOnFolderStateChangedListener;
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mRearrangeOnClose = false;
boolean mItemsInvalidated = false;
private boolean mItemsInvalidated = false;
private View mCurrentDragView;
private boolean mIsExternalDrag;
private boolean mIsDragInProgress = false;
private boolean mDeleteFolderOnDropCompleted = false;
private boolean mSuppressFolderDeletion = false;
private boolean mSuppressContentUpdate = false;
private boolean mItemAddedBackToSelfViaIcon = false;
private boolean mIsEditingName = false;
@@ -268,8 +276,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Nullable
private KeyboardInsetAnimationCallback mKeyboardInsetAnimationCallback;
private @NonNull GradientDrawable mBackground;
private GradientDrawable mBackground;
PreferenceManager2 preferenceManager2;
/**
@@ -291,11 +298,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// reliable behavior when clicking the text field (since it will always gain focus on
// click).
setFocusableInTouchMode(true);
mBackground = (GradientDrawable) Objects.requireNonNull(
ResourcesCompat.getDrawable(getResources(),
R.drawable.round_rect_folder, getContext().getTheme()));
mBackground.setCallback(this);
preferenceManager2 = PreferenceManager2.INSTANCE.get(context);
}
@@ -311,7 +313,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
final int paddingLeftRight = dp.folderContentPaddingLeftRight;
mBackground = DrawableTokens.RoundRectFolder.resolve(getContext());
// TODO-Myself: this is interesting, we can customise this.
var alpha = LawnchairUtilsKt.getFolderBackgroundAlpha(getContext());
mBackground.setAlpha(alpha);
@@ -320,13 +321,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mContent.setFolder(this);
mPageIndicator = findViewById(R.id.folder_page_indicator);
if (enableLauncherVisualRefresh()) {
MarginLayoutParams params = ((MarginLayoutParams) mPageIndicator.getLayoutParams());
int horizontalMargin = getContext().getResources()
.getDimensionPixelSize(R.dimen.folder_footer_horiz_padding);
params.setMarginStart(horizontalMargin);
params.setMarginEnd(horizontalMargin);
}
mFooter = findViewById(R.id.folder_footer);
mFooterHeight = dp.folderFooterHeightPx;
mFolderName = findViewById(R.id.folder_name);
@@ -335,10 +329,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mFolderName.setOnEditorActionListener(this);
mFolderName.setSelectAllOnFocus(true);
mFolderName.setInputType(mFolderName.getInputType()
& ~InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
| InputType.TYPE_TEXT_FLAG_CAP_WORDS);
& ~InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
| InputType.TYPE_TEXT_FLAG_CAP_WORDS);
mFolderName.forceDisableSuggestions(true);
mFolderName.setPadding(mFolderName.getPaddingLeft(),
(getFooterHeight() - mFolderName.getLineHeight()) / 2,
mFolderName.getPaddingRight(),
(getFooterHeight() - mFolderName.getLineHeight()) / 2);
@ColorInt
int accentColor = Themes.getColorAccent(mFolderName.getContext());
@@ -378,11 +376,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return true;
}
@Override
protected boolean verifyDrawable(@NonNull Drawable who) {
return super.verifyDrawable(who) || (who == mBackground);
}
void callBeginDragShared(View v, DragOptions options) {
mLauncherDelegate.beginDragShared(v, this, options);
}
@@ -393,14 +386,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return;
}
getDragController().addDragListener(new AccessibleDragListenerAdapter(
mContent, FolderAccessibilityHelper::new) {
mContent, FolderAccessibilityHelper::new) {
@Override
protected void enableAccessibleDrag(boolean enable,
@Nullable DragObject dragObject) {
@Nullable DragObject dragObject) {
super.enableAccessibleDrag(enable, dragObject);
mFooter.setImportantForAccessibility(enable
? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
: IMPORTANT_FOR_ACCESSIBILITY_AUTO);
? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
: IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
});
}
@@ -412,7 +405,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
if (isInAppDrawer()) {
close(true);
// LC-Note: Do not remove item
// Do not remove item
return;
}
@@ -421,8 +414,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// We do not want to get events for the item being removed, as they will get handled
// when the drop completes
executeWithContentUpdateSuppressed(() -> removeFolderContent(true, dragObject.dragInfo));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mInfo.remove(dragObject.dragInfo, true);
}
mIsDragInProgress = true;
mItemAddedBackToSelfViaIcon = false;
}
@@ -465,8 +459,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
sendCustomAccessibilityEvent(
this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
getContext().getString(R.string.folder_renamed, newTitle));
this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
getContext().getString(R.string.folder_renamed, newTitle));
// This ensures that focus is gained every time the field is clicked, which selects all
// the text and brings up the soft keyboard if necessary.
@@ -480,7 +474,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (DEBUG) {
Log.d(TAG, "onEditorAction actionId=" + actionId + " key="
+ (event != null ? event.getKeyCode() : "null event"));
+ (event != null ? event.getKeyCode() : "null event"));
}
if (actionId == EditorInfo.IME_ACTION_DONE) {
mFolderName.dispatchBackKey();
@@ -505,7 +499,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
}
} catch (Throwable t) {
// LC-Catch
WindowInsetsCompat insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(windowInsets);
if (insetsCompat.isVisible(WindowInsetsCompat.Type.ime())) {
androidx.core.graphics.Insets keyboardInsets = insetsCompat.getInsets(WindowInsetsCompat.Type.ime());
@@ -578,6 +571,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mInfo = info;
mFromTitle = info.title;
mFromLabelState = info.getFromLabelState();
ArrayList<ItemInfo> children = info.getContents();
Collections.sort(children, ITEM_POS_COMPARATOR);
updateItemLocationsInDatabaseBatch(true);
BaseDragLayer.LayoutParams lp = (BaseDragLayer.LayoutParams) getLayoutParams();
@@ -586,17 +581,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
lp.customPosition = true;
setLayoutParams(lp);
}
reapplyItemInfo();
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(() -> {
if (getItemCount() <= 1) {
replaceFolderWithFinalItem();
}
});
}
public void reapplyItemInfo() {
mItemsInvalidated = true;
mInfo.addListener(this);
if (!isEmpty(mInfo.title)) {
mFolderName.setText(mInfo.title);
@@ -605,8 +591,15 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mFolderName.setText("");
mFolderName.setHint(R.string.folder_hint_text);
}
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(() -> {
if (getItemCount() <= 1 && !isInAppDrawer()) {
replaceFolderWithFinalItem();
}
});
}
/**
* Show suggested folder title in FolderEditText if the first suggestion is non-empty, push
* rest of the suggestions to InputMethodManager.
@@ -626,12 +619,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
mFolderName.showKeyboard();
mFolderName.displayCompletions(
Stream.of(mInfo.suggestedFolderNames.getLabels())
.filter(Objects::nonNull)
.map(Object::toString)
.filter(s -> !s.isEmpty())
.filter(s -> !s.equalsIgnoreCase(mFolderName.getText().toString()))
.collect(Collectors.toList()));
Stream.of(mInfo.suggestedFolderNames.getLabels())
.filter(Objects::nonNull)
.map(Object::toString)
.filter(s -> !s.isEmpty())
.filter(s -> !s.equalsIgnoreCase(mFolderName.getText().toString()))
.collect(Collectors.toList()));
}
}
@@ -645,12 +638,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@SuppressLint("InflateParams")
static <T extends Context & ActivityContext> Folder fromXml(T activityContext) {
return (Folder) LayoutInflater.from(activityContext).cloneInContext(activityContext)
.inflate(R.layout.user_folder_icon_normalized, null);
.inflate(R.layout.user_folder_icon_normalized, null);
}
private void addAnimationStartListeners(AnimatorSet a) {
mLauncherDelegate.forEachVisibleWorkspacePage(
visiblePage -> addAnimatorListenerForPage(a, (CellLayout) visiblePage));
visiblePage -> addAnimatorListenerForPage(a, (CellLayout) visiblePage));
a.addListener(new AnimatorListenerAdapter() {
@Override
@@ -736,11 +729,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (!shouldAnimateOpen(items)) {
return;
}
Folder openFolder = getOpen(mActivityContext);
closeOpenFolder(openFolder);
mContent.bindItems(items);
mContent.setCanAnnouncePageDescriptionForFolder(true);
centerAboutIcon();
mItemsInvalidated = true;
updateTextViewFocus();
@@ -756,27 +749,19 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
} else {
if (FeatureFlags.IS_STUDIO_BUILD) {
Log.e(TAG, "Opening folder (" + this + ") which already has a parent:"
+ getParent());
+ getParent());
}
}
Log.d("b/383526431", "animateOpen: content child count before: "
+ mContent.getTotalChildCount());
mContent.completePendingPageChanges();
mContent.setCurrentPage(pageNo);
Log.d("b/383526431", "animateOpen: content child count after pending page"
+ " changes: " + mContent.getTotalChildCount());
// This is set to true in close(), but isn't reset to false until onDropCompleted(). This
// leads to an inconsistent state if you drag out of the folder and drag back in without
// dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
mDeleteFolderOnDropCompleted = false;
cancelRunningAnimations();
Log.d("b/383526431", "animateOpen: content child count after cancelling"
+ " animation: " + mContent.getTotalChildCount());
FolderAnimationManager fam = new FolderAnimationManager(this, true /* isOpening */);
AnimatorSet anim = fam.getAnimator();
anim.addListener(new AnimatorListenerAdapter() {
@@ -791,7 +776,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
setState(STATE_OPEN);
announceAccessibilityChanges();
AccessibilityManagerCompat.sendTestProtocolEventToTest(getContext(),
FOLDER_OPENED_MESSAGE);
FOLDER_OPENED_MESSAGE);
mContent.setFocusOnFirstChild();
}
@@ -800,7 +785,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Footer animation
if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
int footerWidth = mContent.getDesiredWidth()
- mFooter.getPaddingLeft() - mFooter.getPaddingRight();
- mFooter.getPaddingLeft() - mFooter.getPaddingRight();
float textWidth = mFolderName.getPaint().measureText(mFolderName.getText().toString());
float translation = (footerWidth - textWidth) / 2;
@@ -816,14 +801,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public void onAnimationEnd(Animator animation) {
mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
.translationX(0)
.setInterpolator(AnimationUtils.loadInterpolator(
getContext(), android.R.interpolator.fast_out_slow_in));
.translationX(0)
.setInterpolator(AnimationUtils.loadInterpolator(
getContext(), android.R.interpolator.fast_out_slow_in));
mPageIndicator.playEntryAnimation();
if (updateAnimationFlag) {
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
}
});
@@ -882,7 +867,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
protected void handleClose(boolean animate) {
mIsOpen = false;
mContent.setCanAnnouncePageDescriptionForFolder(false);
if (!animate && mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
mCurrentAnimator.cancel();
@@ -906,7 +890,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Notify the accessibility manager that this folder "window" has disappeared and no
// longer occludes the workspace items
mActivityContext.getDragLayer().sendAccessibilityEvent(
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
private void cancelRunningAnimations() {
@@ -961,7 +945,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
protected Pair<View, String> getAccessibilityTarget() {
return Pair.create(mContent, mIsOpen ? mContent.getAccessibilityDescription()
: getContext().getString(R.string.folder_closed));
: getContext().getString(R.string.folder_closed));
}
@Override
@@ -997,7 +981,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mRearrangeOnClose = false;
}
if (getItemCount() <= 1) {
if (!mIsDragInProgress && !mSuppressFolderDeletion) {
if (!mIsDragInProgress && !mSuppressFolderDeletion && !isInAppDrawer()) {
replaceFolderWithFinalItem();
} else if (mIsDragInProgress) {
mDeleteFolderOnDropCompleted = true;
@@ -1013,7 +997,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean acceptDrop(DragObject d) {
return willAcceptItemType(d.dragInfo.itemType);
final ItemInfo item = d.dragInfo;
final int itemType = item.itemType;
return Folder.willAcceptItemType(itemType);
}
public void onDragEnter(DragObject d) {
@@ -1038,7 +1024,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
private int getTargetRank(DragObject d, float[] recycle) {
recycle = d.getVisualCenter(recycle);
return mContent.findNearestArea(
(int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
(int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
}
@Override
@@ -1057,7 +1043,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (d.stateAnnouncer != null) {
d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position,
mTargetRank + 1));
mTargetRank + 1));
}
}
@@ -1065,14 +1051,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int currentPage = mContent.getNextPage();
float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
* ICON_OVERSCROLL_WIDTH_FACTOR;
* ICON_OVERSCROLL_WIDTH_FACTOR;
boolean isOutsideLeftEdge = x < cellOverlap;
boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
showScrollHint(SCROLL_LEFT, d);
} else if (currentPage < (mContent.getPageCount() - 1)
&& (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
&& (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
showScrollHint(SCROLL_RIGHT, d);
} else {
mOnScrollHintAlarm.cancelAlarm();
@@ -1110,7 +1096,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
public void completeDragExit() {
if (isInAppDrawer()) {
// LC: ff8c5a827b85f47a0d8ed5e6ac449ab8042705c6
return;
}
if (mIsOpen) {
@@ -1161,29 +1146,28 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public void onDropCompleted(final View target, final DragObject d,
final boolean success) {
final boolean success) {
if (success) {
if (getItemCount() <= 1) {
mDeleteFolderOnDropCompleted = true;
}
if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon
&& target != this) {
&& target != this) {
replaceFolderWithFinalItem();
}
} else {
// The drag failed, we need to return the item to the folder
ItemInfo info = d.dragInfo;
View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
? mCurrentDragView : mContent.createNewView(info);
? mCurrentDragView : mContent.createNewView(info);
ArrayList<View> views = getIconsInReadingOrder();
if (!views.contains(icon)) {
info.rank = Utilities.boundToRange(info.rank, 0, views.size());
views.add(info.rank, icon);
mContent.arrangeChildren(views);
mItemsInvalidated = true;
info.rank = Utilities.boundToRange(info.rank, 0, views.size());
views.add(info.rank, icon);
mContent.arrangeChildren(views);
mItemsInvalidated = true;
executeWithContentUpdateSuppressed(
() -> mFolderIcon.onDrop(d, true /* itemReturnedOnFailedDrop */));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mFolderIcon.onDrop(d, true /* itemReturnedOnFailedDrop */);
}
}
@@ -1211,13 +1195,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (getItemCount() <= mContent.itemsPerPage()) {
// Show the animation, next time something is added to the folder.
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
}
private void updateItemLocationsInDatabaseBatch(boolean isBind) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
ArrayList<ItemInfo> items = new ArrayList<>();
int total = mInfo.getContents().size();
@@ -1286,7 +1270,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
protected int getContentAreaHeight() {
int height = Math.min(getMaxContentAreaHeight(),
mContent.getDesiredHeight());
mContent.getDesiredHeight());
return Math.max(height, MIN_CONTENT_DIMEN);
}
@@ -1294,7 +1278,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int getMaxContentAreaHeight() {
DeviceProfile grid = mActivityContext.getDeviceProfile();
return grid.availableHeightPx - grid.getTotalWorkspacePadding().y
- getFooterHeight();
- getFooterHeight();
}
@VisibleForTesting
@@ -1333,30 +1317,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec);
mFooter.measure(contentAreaWidthSpec,
MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
int folderHeight = getFolderHeight(contentHeight);
setMeasuredDimension(folderWidth, folderHeight);
}
/**
* If the Folder Title has less than 100dp of available width, we hide it. The reason we do this
* calculation in onSizeChange is because this callback is called 1x when the folder is opened.
* <p>
* The PageIndicator and the Folder Title share the same horizontal linear layout, but both
* are dynamically sized. Therefore, we are setting visibility of the folder title AFTER the
* layout is measured.
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int minTitleWidth = getResources().getDimensionPixelSize(R.dimen.folder_title_min_width);
if (enableLauncherVisualRefresh() && mFolderName.getMeasuredWidth() < minTitleWidth) {
mFolderName.setVisibility(View.GONE);
}
}
/**
* Rearranges the children based on their rank.
*/
@@ -1404,7 +1371,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB &&
event.hasModifiers(KeyEvent.META_SHIFT_ON);
event.hasModifiers(KeyEvent.META_SHIFT_ON);
if (isShiftPlusTab && Folder.this.isFocused()) {
return lastChild.requestFocus();
}
@@ -1437,16 +1404,16 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo
? (PendingAddShortcutInfo) d.dragInfo : null;
? (PendingAddShortcutInfo) d.dragInfo : null;
WorkspaceItemInfo pasiSi =
pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null;
pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null;
if (pasi != null && pasiSi == null) {
// There is no WorkspaceItemInfo, so we have to go through a configuration activity.
pasi.container = mInfo.id;
pasi.rank = mEmptyCellRank;
launcher.addPendingItem(pasi, pasi.container, pasi.screenId, null, pasi.spanX,
pasi.spanY);
pasi.spanY);
d.deferDragViewCleanupPostAnimation = false;
mRearrangeOnClose = true;
} else {
@@ -1468,7 +1435,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Actually move the item in the database if it was an external drag. Call this
// before creating the view, so that the ItemInfo is updated appropriately.
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(
si, mInfo.id, 0, si.cellX, si.cellY);
si, mInfo.id, 0, si.cellX, si.cellY);
mIsExternalDrag = false;
} else {
currentDragView = mCurrentDragView;
@@ -1494,7 +1461,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
rearrangeChildren();
// Temporarily suppress the listener, as we did all the work already here.
executeWithContentUpdateSuppressed(() -> addFolderContent(si, mEmptyCellRank, false));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mInfo.add(si, mEmptyCellRank, false);
}
// We only need to update the locations if it doesn't get handled in
// #onDropCompleted.
@@ -1509,7 +1478,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (mContent.getPageCount() > 1) {
// The animation has already been shown while opening the folder.
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
if (!launcher.isInState(EDIT_MODE)) {
@@ -1520,7 +1489,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
d.stateAnnouncer.completeAction(R.string.item_moved);
}
mStatsLogManager.logger().withItemInfo(d.dragInfo).withInstanceId(d.logInstanceId)
.log(LAUNCHER_ITEM_DROP_COMPLETED);
.log(LAUNCHER_ITEM_DROP_COMPLETED);
}
// This is used so the item doesn't immediately appear in the folder when added. In one case
@@ -1540,66 +1509,40 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
}
/** Add an app or shortcut */
public void addFolderContent(ItemInfo item) {
addFolderContent(item, mInfo.getContents().size(), true);
}
/** Add an app or shortcut for a specified rank */
public void addFolderContent(ItemInfo item, int rank, boolean animate) {
if (!willAcceptItemType(item.itemType)) {
throw new RuntimeException("tried to add an illegal type into a folder");
}
rank = Utilities.boundToRange(rank, 0, mInfo.getContents().size());
mInfo.getContents().add(rank, item);
if (!mSuppressContentUpdate) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
@Override
public void onAdd(ItemInfo item, int rank) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
verifier.updateRankAndPos(item, rank);
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0,
item.cellX,
verifier.updateRankAndPos(item, rank);
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX,
item.cellY);
updateItemLocationsInDatabaseBatch(false);
updateItemLocationsInDatabaseBatch(false);
if (mContent.areViewsBound()) {
mContent.createAndAddViewForRank(item, rank);
}
mItemsInvalidated = true;
updateTextViewFocus();
if (mContent.areViewsBound()) {
mContent.createAndAddViewForRank(item, rank);
}
mLauncherDelegate.getModelWriter().notifyItemModified(mInfo);
mFolderIcon.onItemsChanged(animate);
mItemsInvalidated = true;
}
/** Remove all matching app or shortcut. Does not change the DB. */
public void removeFolderContent(boolean animate, ItemInfo... items) {
List<ItemInfo> itemArray = Arrays.asList(items);
if (mInfo.getContents().removeAll(itemArray)) {
mLauncherDelegate.getModelWriter().notifyItemModified(mInfo);
@Override
public void onRemove(List<ItemInfo> items) {
if (isInAppDrawer()) {
return;
}
if (!mSuppressContentUpdate) {
mItemsInvalidated = true;
itemArray.forEach(item -> mContent.removeItem(getViewForInfo(item)));
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
mItemsInvalidated = true;
items.stream().map(this::getViewForInfo).forEach(mContent::removeItem);
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
} else {
rearrangeChildren();
}
if (getItemCount() <= 1) {
if (mIsOpen) {
close(true);
} else {
rearrangeChildren();
replaceFolderWithFinalItem();
}
if (getItemCount() <= 1) {
if (mIsOpen) {
close(true);
} else {
replaceFolderWithFinalItem();
}
}
updateTextViewFocus();
}
mFolderIcon.onItemsChanged(animate);
}
@VisibleForTesting
@@ -1607,13 +1550,21 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return mContent.iterateOverItems((info, view) -> info == item);
}
@Override
public void onItemsChanged(boolean animate) {
updateTextViewFocus();
}
@Override
public void onTitleChanged(CharSequence title) {
mFolderName.setText(title);
}
/**
* Utility methods to iterate over items of the view
*/
@Override
@Nullable
public View mapOverItems(@NonNull ItemOperator op) {
return mContent.iterateOverItems(op);
public void iterateOverItems(ItemOperator op) {
mContent.iterateOverItems(op);
}
/**
@@ -1634,8 +1585,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int totalItemsInFolder = allItems.size();
int itemsPerPage = mContent.itemsPerPage();
int numItemsOnCurrentPage = page == lastPage
? totalItemsInFolder - (itemsPerPage * page)
: itemsPerPage;
? totalItemsInFolder - (itemsPerPage * page)
: itemsPerPage;
int startIndex = page * itemsPerPage;
int endIndex = Math.min(startIndex + numItemsOnCurrentPage, allItems.size());
@@ -1656,8 +1607,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
post(this::startEditingFolderName);
} else {
StatsLogger statsLogger = mStatsLogManager.logger()
.withItemInfo(mInfo)
.withFromState(mFromLabelState);
.withItemInfo(mInfo)
.withFromState(mFromLabelState);
// If the folder label is suggested, it is logged to improve prediction model.
// When both old and new labels are logged together delimiter is used.
@@ -1722,7 +1673,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Pause drag event until the scrolling is finished
mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
int rescrollDelay = getResources().getInteger(
R.integer.config_pageSnapAnimationDuration) + RESCROLL_EXTRA_DELAY;
R.integer.config_pageSnapAnimationDuration) + RESCROLL_EXTRA_DELAY;
mScrollPauseAlarm.setAlarm(rescrollDelay);
}
}
@@ -1760,14 +1711,18 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
};
/** Executes the task while suppressing the content update for the folder */
private void executeWithContentUpdateSuppressed(Runnable task) {
if (mSuppressContentUpdate) {
task.run();
} else {
mSuppressContentUpdate = true;
task.run();
mSuppressContentUpdate = false;
/**
* Temporary resource held while we don't want to handle info changes
*/
private class SuppressInfoChanges implements AutoCloseable {
SuppressInfoChanges() {
mInfo.removeListener(Folder.this);
}
@Override
public void close() {
mInfo.addListener(Folder.this);
updateTextViewFocus();
}
}
@@ -1801,7 +1756,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
return false;
} else if (!dl.isEventOverView(this, ev)
&& mLauncherDelegate.interceptOutsideTouch(ev, dl, this)) {
&& mLauncherDelegate.interceptOutsideTouch(ev, dl, this)) {
return true;
}
}
@@ -1810,7 +1765,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean canInterceptEventsInSystemGestureRegion() {
return !mIsEditingName;
return true;
}
/**