dropTargets = mDropTargets;
+ final int count = dropTargets.size();
+ for (int i=count-1; i>=0; i--) {
+ final DropTarget target = dropTargets.get(i);
+ target.getHitRect(r);
+ target.getLocationOnScreen(dropCoordinates);
+ r.offset(dropCoordinates[0] - target.getLeft(), dropCoordinates[1] - target.getTop());
+ if (r.contains(x, y)) {
+ dropCoordinates[0] = x - dropCoordinates[0];
+ dropCoordinates[1] = y - dropCoordinates[1];
+ return target;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Get the screen size so we can clamp events to the screen size so even if
+ * you drag off the edge of the screen, we find something.
+ */
+ private void recordScreenSize() {
+ ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
+ .getDefaultDisplay().getMetrics(mDisplayMetrics);
+ }
+
+ /**
+ * Clamp val to be >= min and < max.
+ */
+ private static int clamp(int val, int min, int max) {
+ if (val < min) {
+ return min;
+ } else if (val >= max) {
+ return max - 1;
+ } else {
+ return val;
+ }
+ }
+
+ public void setDragScoller(DragScroller scroller) {
+ mDragScroller = scroller;
+ }
+
+ public void setWindowToken(IBinder token) {
+ mWindowToken = token;
+ }
+
+ /**
+ * Sets the drag listner which will be notified when a drag starts or ends.
+ */
+ public void setDragListener(DragListener l) {
+ mListener = l;
+ }
+
+ /**
+ * Remove a previously installed drag listener.
+ */
+ public void removeDragListener(DragListener l) {
+ mListener = null;
+ }
+
+ /**
+ * Add a DropTarget to the list of potential places to receive drop events.
+ */
+ public void addDropTarget(DropTarget target) {
+ mDropTargets.add(target);
+ }
+
+ /**
+ * Don't send drop events to target any more.
+ */
+ public void removeDropTarget(DropTarget target) {
+ mDropTargets.remove(target);
+ }
+
+ /**
+ * Set which view scrolls for touch events near the edge of the screen.
+ */
+ public void setScrollView(View v) {
+ mScrollView = v;
+ }
+
+ /**
+ * Specifies the delete region. We won't scroll on touch events over the delete region.
+ *
+ * @param region The rectangle in screen coordinates of the delete region.
+ */
+ void setDeleteRegion(RectF region) {
+ mDeleteRegion = region;
+ }
+
+ private class ScrollRunnable implements Runnable {
+ private int mDirection;
+
+ ScrollRunnable() {
+ }
+
+ public void run() {
+ if (mDragScroller != null) {
+ if (mDirection == SCROLL_LEFT) {
+ mDragScroller.scrollLeft();
+ } else {
+ mDragScroller.scrollRight();
+ }
+ mScrollState = SCROLL_OUTSIDE_ZONE;
+ }
+ }
+
+ void setDirection(int direction) {
+ mDirection = direction;
+ }
+ }
+}
diff --git a/src/com/android/launcher2/DragLayer.java b/src/com/android/launcher2/DragLayer.java
new file mode 100644
index 0000000000..7ae98917d2
--- /dev/null
+++ b/src/com/android/launcher2/DragLayer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.KeyEvent;
+import android.widget.FrameLayout;
+
+/**
+ * A ViewGroup that coordinated dragging across its dscendants
+ */
+public class DragLayer extends FrameLayout {
+ DragController mDragController;
+
+ /**
+ * Used to create a new DragLayer from XML.
+ *
+ * @param context The application's context.
+ * @param attrs The attribtues set containing the Workspace's customization values.
+ */
+ public DragLayer(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public void setDragController(DragController controller) {
+ mDragController = controller;
+ }
+
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ return mDragController.dispatchKeyEvent(event) || super.dispatchKeyEvent(event);
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ return mDragController.onInterceptTouchEvent(ev);
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+ return mDragController.onTouchEvent(ev);
+ }
+}
diff --git a/src/com/android/launcher2/DragScroller.java b/src/com/android/launcher2/DragScroller.java
new file mode 100644
index 0000000000..c3c251c2f1
--- /dev/null
+++ b/src/com/android/launcher2/DragScroller.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+/**
+ * Handles scrolling while dragging
+ *
+ */
+public interface DragScroller {
+ void scrollLeft();
+ void scrollRight();
+}
diff --git a/src/com/android/launcher2/DragSource.java b/src/com/android/launcher2/DragSource.java
new file mode 100644
index 0000000000..7c6ca58aee
--- /dev/null
+++ b/src/com/android/launcher2/DragSource.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.view.View;
+
+/**
+ * Interface defining an object that can originate a drag.
+ *
+ */
+public interface DragSource {
+ void setDragController(DragController dragger);
+ void onDropCompleted(View target, boolean success);
+}
diff --git a/src/com/android/launcher2/DragView.java b/src/com/android/launcher2/DragView.java
new file mode 100644
index 0000000000..7a86273e61
--- /dev/null
+++ b/src/com/android/launcher2/DragView.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.PixelFormat;
+import android.graphics.Point;
+import android.os.IBinder;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.KeyEvent;
+import android.view.WindowManager;
+import android.view.WindowManagerImpl;
+
+public class DragView extends View implements TweenCallback {
+ // Number of pixels to add to the dragged item for scaling. Should be even for pixel alignment.
+ private static final int DRAG_SCALE = 24;
+
+ private Bitmap mBitmap;
+ private Paint mPaint;
+ private int mRegistrationX;
+ private int mRegistrationY;
+
+ SymmetricalLinearTween mTween;
+ private float mScale;
+ private float mAnimationScale = 1.0f;
+
+ private WindowManager.LayoutParams mLayoutParams;
+ private WindowManager mWindowManager;
+
+ /**
+ * Construct the drag view.
+ *
+ * The registration point is the point inside our view that the touch events should
+ * be centered upon.
+ *
+ * @param context A context
+ * @param bitmap The view that we're dragging around. We scale it up when we draw it.
+ * @param registrationX The x coordinate of the registration point.
+ * @param registrationY The y coordinate of the registration point.
+ */
+ public DragView(Context context, Bitmap bitmap, int registrationX, int registrationY,
+ int left, int top, int width, int height) {
+ super(context);
+
+ mWindowManager = WindowManagerImpl.getDefault();
+
+ mTween = new SymmetricalLinearTween(false, 110 /*ms duration*/, this);
+
+ Matrix scale = new Matrix();
+ float scaleFactor = width;
+ scaleFactor = mScale = (scaleFactor + DRAG_SCALE) / scaleFactor;
+ scale.setScale(scaleFactor, scaleFactor);
+
+ mBitmap = Bitmap.createBitmap(bitmap, left, top, width, height, scale, true);
+
+ // The point in our scaled bitmap that the touch events are located
+ mRegistrationX = registrationX + (DRAG_SCALE / 2);
+ mRegistrationY = registrationY + (DRAG_SCALE / 2);
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ setMeasuredDimension(mBitmap.getWidth(), mBitmap.getHeight());
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ if (false) {
+ // for debugging
+ Paint p = new Paint();
+ p.setStyle(Paint.Style.FILL);
+ p.setColor(0xaaffffff);
+ canvas.drawRect(0, 0, getWidth(), getHeight(), p);
+ }
+ float scale = mAnimationScale;
+ if (scale < 0.999f) { // allow for some float error
+ float width = mBitmap.getWidth();
+ float offset = (width-(width*scale))/2;
+ canvas.translate(offset, offset);
+ canvas.scale(scale, scale);
+ }
+ canvas.drawBitmap(mBitmap, 0.0f, 0.0f, mPaint);
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ mBitmap.recycle();
+ }
+
+ public void onTweenValueChanged(float value, float oldValue) {
+ mAnimationScale = (1.0f+((mScale-1.0f)*value))/mScale;
+ invalidate();
+ }
+
+ public void onTweenStarted() {
+ }
+
+ public void onTweenFinished() {
+ }
+
+ public void setPaint(Paint paint) {
+ mPaint = paint;
+ invalidate();
+ }
+
+ /**
+ * Create a window containing this view and show it.
+ *
+ * @param windowToken obtained from v.getWindowToken() from one of your views
+ * @param touchX the x coordinate the user touched in screen coordinates
+ * @param touchY the y coordinate the user touched in screen coordinates
+ */
+ public void show(IBinder windowToken, int touchX, int touchY) {
+ WindowManager.LayoutParams lp;
+ int pixelFormat;
+
+ pixelFormat = PixelFormat.TRANSLUCENT;
+
+ lp = new WindowManager.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ touchX-mRegistrationX, touchY-mRegistrationY,
+ WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
+ | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
+ /*| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM*/,
+ pixelFormat);
+// lp.token = mStatusBarView.getWindowToken();
+ lp.gravity = Gravity.LEFT | Gravity.TOP;
+ lp.token = windowToken;
+ lp.setTitle("DragView");
+ mLayoutParams = lp;
+
+ mWindowManager.addView(this, lp);
+
+ mAnimationScale = 1.0f/mScale;
+ mTween.start(true);
+ }
+
+ /**
+ * Move the window containing this view.
+ *
+ * @param touchX the x coordinate the user touched in screen coordinates
+ * @param touchY the y coordinate the user touched in screen coordinates
+ */
+ void move(int touchX, int touchY) {
+ WindowManager.LayoutParams lp = mLayoutParams;
+ lp.x = touchX - mRegistrationX;
+ lp.y = touchY - mRegistrationY;
+ mWindowManager.updateViewLayout(this, lp);
+ }
+
+ void remove() {
+ mWindowManager.removeView(this);
+ }
+}
+
diff --git a/src/com/android/launcher2/DropTarget.java b/src/com/android/launcher2/DropTarget.java
new file mode 100644
index 0000000000..72eb330948
--- /dev/null
+++ b/src/com/android/launcher2/DropTarget.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.graphics.Rect;
+
+/**
+ * Interface defining an object that can receive a drag.
+ *
+ */
+public interface DropTarget {
+
+ /**
+ * Handle an object being dropped on the DropTarget
+ *
+ * @param source DragSource where the drag started
+ * @param x X coordinate of the drop location
+ * @param y Y coordinate of the drop location
+ * @param xOffset Horizontal offset with the object being dragged where the original
+ * touch happened
+ * @param yOffset Vertical offset with the object being dragged where the original
+ * touch happened
+ * @param dragView The DragView that's being dragged around on screen.
+ * @param dragInfo Data associated with the object being dragged
+ *
+ */
+ void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo);
+
+ void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo);
+
+ void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo);
+
+ void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo);
+
+ /**
+ * Check if a drop action can occur at, or near, the requested location.
+ * This may be called repeatedly during a drag, so any calls should return
+ * quickly.
+ *
+ * @param source DragSource where the drag started
+ * @param x X coordinate of the drop location
+ * @param y Y coordinate of the drop location
+ * @param xOffset Horizontal offset with the object being dragged where the
+ * original touch happened
+ * @param yOffset Vertical offset with the object being dragged where the
+ * original touch happened
+ * @param dragView The DragView that's being dragged around on screen.
+ * @param dragInfo Data associated with the object being dragged
+ * @return True if the drop will be accepted, false otherwise.
+ */
+ boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo);
+
+ /**
+ * Estimate the surface area where this object would land if dropped at the
+ * given location.
+ *
+ * @param source DragSource where the drag started
+ * @param x X coordinate of the drop location
+ * @param y Y coordinate of the drop location
+ * @param xOffset Horizontal offset with the object being dragged where the
+ * original touch happened
+ * @param yOffset Vertical offset with the object being dragged where the
+ * original touch happened
+ * @param dragView The DragView that's being dragged around on screen.
+ * @param dragInfo Data associated with the object being dragged
+ * @param recycle {@link Rect} object to be possibly recycled.
+ * @return Estimated area that would be occupied if object was dropped at
+ * the given location. Should return null if no estimate is found,
+ * or if this target doesn't provide estimations.
+ */
+ Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo, Rect recycle);
+
+ // These methods are implemented in Views
+ void getHitRect(Rect outRect);
+ void getLocationOnScreen(int[] loc);
+ int getLeft();
+ int getTop();
+}
diff --git a/src/com/android/launcher2/FastBitmapDrawable.java b/src/com/android/launcher2/FastBitmapDrawable.java
new file mode 100644
index 0000000000..db2c01c4f8
--- /dev/null
+++ b/src/com/android/launcher2/FastBitmapDrawable.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.graphics.drawable.Drawable;
+import android.graphics.PixelFormat;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.ColorFilter;
+
+class FastBitmapDrawable extends Drawable {
+ private Bitmap mBitmap;
+
+ FastBitmapDrawable(Bitmap b) {
+ mBitmap = b;
+ }
+
+ @Override
+ public void draw(Canvas canvas) {
+ canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
+ }
+
+ @Override
+ public int getOpacity() {
+ return PixelFormat.TRANSLUCENT;
+ }
+
+ @Override
+ public void setAlpha(int alpha) {
+ }
+
+ @Override
+ public void setColorFilter(ColorFilter cf) {
+ }
+
+ @Override
+ public int getIntrinsicWidth() {
+ return mBitmap.getWidth();
+ }
+
+ @Override
+ public int getIntrinsicHeight() {
+ return mBitmap.getHeight();
+ }
+
+ @Override
+ public int getMinimumWidth() {
+ return mBitmap.getWidth();
+ }
+
+ @Override
+ public int getMinimumHeight() {
+ return mBitmap.getHeight();
+ }
+
+ public Bitmap getBitmap() {
+ return mBitmap;
+ }
+}
diff --git a/src/com/android/launcher2/Folder.java b/src/com/android/launcher2/Folder.java
new file mode 100644
index 0000000000..4f66ad0520
--- /dev/null
+++ b/src/com/android/launcher2/Folder.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.LinearLayout;
+import android.widget.AbsListView;
+import android.widget.BaseAdapter;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.AdapterView.OnItemLongClickListener;
+
+/**
+ * Represents a set of icons chosen by the user or generated by the system.
+ */
+public class Folder extends LinearLayout implements DragSource, OnItemLongClickListener,
+ OnItemClickListener, OnClickListener, View.OnLongClickListener {
+
+ protected AbsListView mContent;
+ protected DragController mDragController;
+
+ protected Launcher mLauncher;
+
+ protected Button mCloseButton;
+
+ protected FolderInfo mInfo;
+
+ /**
+ * Which item is being dragged
+ */
+ protected ApplicationInfo mDragItem;
+ private boolean mCloneInfo;
+
+ /**
+ * Used to inflate the Workspace from XML.
+ *
+ * @param context The application's context.
+ * @param attrs The attribtues set containing the Workspace's customization values.
+ */
+ public Folder(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ setAlwaysDrawnWithCacheEnabled(false);
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+
+ mContent = (AbsListView) findViewById(R.id.folder_content);
+ mContent.setOnItemClickListener(this);
+ mContent.setOnItemLongClickListener(this);
+
+ mCloseButton = (Button) findViewById(R.id.folder_close);
+ mCloseButton.setOnClickListener(this);
+ mCloseButton.setOnLongClickListener(this);
+ }
+
+ public void onItemClick(AdapterView parent, View v, int position, long id) {
+ ApplicationInfo app = (ApplicationInfo) parent.getItemAtPosition(position);
+ mLauncher.startActivitySafely(app.intent);
+ }
+
+ public void onClick(View v) {
+ mLauncher.closeFolder(this);
+ }
+
+ public boolean onLongClick(View v) {
+ mLauncher.closeFolder(this);
+ mLauncher.showRenameDialog(mInfo);
+ return true;
+ }
+
+ public boolean onItemLongClick(AdapterView> parent, View view, int position, long id) {
+ if (!view.isInTouchMode()) {
+ return false;
+ }
+
+ ApplicationInfo app = (ApplicationInfo) parent.getItemAtPosition(position);
+ if (mCloneInfo) {
+ app = new ApplicationInfo(app);
+ }
+
+ mDragController.startDrag(view, this, app, DragController.DRAG_ACTION_COPY);
+ mLauncher.closeFolder(this);
+ mDragItem = app;
+
+ return true;
+ }
+
+ void setCloneInfo(boolean cloneInfo) {
+ mCloneInfo = cloneInfo;
+ }
+
+ public void setDragController(DragController dragController) {
+ mDragController = dragController;
+ }
+
+ public void onDropCompleted(View target, boolean success) {
+ }
+
+ /**
+ * Sets the adapter used to populate the content area. The adapter must only
+ * contains ApplicationInfo items.
+ *
+ * @param adapter The list of applications to display in the folder.
+ */
+ void setContentAdapter(BaseAdapter adapter) {
+ mContent.setAdapter(adapter);
+ }
+
+ void notifyDataSetChanged() {
+ ((BaseAdapter) mContent.getAdapter()).notifyDataSetChanged();
+ }
+
+ void setLauncher(Launcher launcher) {
+ mLauncher = launcher;
+ }
+
+ /**
+ * @return the FolderInfo object associated with this folder
+ */
+ FolderInfo getInfo() {
+ return mInfo;
+ }
+
+ // When the folder opens, we need to refresh the GridView's selection by
+ // forcing a layout
+ void onOpen() {
+ mContent.requestLayout();
+ }
+
+ void onClose() {
+ final Workspace workspace = mLauncher.getWorkspace();
+ workspace.getChildAt(workspace.getCurrentScreen()).requestFocus();
+ }
+
+ void bind(FolderInfo info) {
+ mInfo = info;
+ mCloseButton.setText(info.title);
+ }
+}
diff --git a/src/com/android/launcher2/FolderIcon.java b/src/com/android/launcher2/FolderIcon.java
new file mode 100644
index 0000000000..85fc3a7547
--- /dev/null
+++ b/src/com/android/launcher2/FolderIcon.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+
+/**
+ * An icon that can appear on in the workspace representing an {@link UserFolder}.
+ */
+public class FolderIcon extends BubbleTextView implements DropTarget {
+ private UserFolderInfo mInfo;
+ private Launcher mLauncher;
+ private Drawable mCloseIcon;
+ private Drawable mOpenIcon;
+
+ public FolderIcon(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public FolderIcon(Context context) {
+ super(context);
+ }
+
+ static FolderIcon fromXml(int resId, Launcher launcher, ViewGroup group,
+ UserFolderInfo folderInfo) {
+
+ FolderIcon icon = (FolderIcon) LayoutInflater.from(launcher).inflate(resId, group, false);
+
+ final Resources resources = launcher.getResources();
+ Drawable d = resources.getDrawable(R.drawable.ic_launcher_folder);
+ d = Utilities.createIconThumbnail(d, launcher);
+ icon.mCloseIcon = d;
+ icon.mOpenIcon = resources.getDrawable(R.drawable.ic_launcher_folder_open);
+ icon.setCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
+ icon.setText(folderInfo.title);
+ icon.setTag(folderInfo);
+ icon.setOnClickListener(launcher);
+ icon.mInfo = folderInfo;
+ icon.mLauncher = launcher;
+
+ return icon;
+ }
+
+ public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ final ItemInfo item = (ItemInfo) dragInfo;
+ final int itemType = item.itemType;
+ return (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
+ itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT)
+ && item.container != mInfo.id;
+ }
+
+ public Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo, Rect recycle) {
+ return null;
+ }
+
+ public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ final ApplicationInfo item = (ApplicationInfo) dragInfo;
+ // TODO: update open folder that is looking at this data
+ mInfo.add(item);
+ LauncherModel.addOrMoveItemInDatabase(mLauncher, item, mInfo.id, 0, 0, 0);
+ }
+
+ public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ setCompoundDrawablesWithIntrinsicBounds(null, mOpenIcon, null, null);
+ }
+
+ public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ setCompoundDrawablesWithIntrinsicBounds(null, mCloseIcon, null, null);
+ }
+}
diff --git a/src/com/android/launcher2/FolderInfo.java b/src/com/android/launcher2/FolderInfo.java
new file mode 100644
index 0000000000..8732690c3e
--- /dev/null
+++ b/src/com/android/launcher2/FolderInfo.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+
+/**
+ * Represents a folder containing shortcuts or apps.
+ */
+class FolderInfo extends ItemInfo {
+
+ /**
+ * Whether this folder has been opened
+ */
+ boolean opened;
+
+ /**
+ * The folder name.
+ */
+ CharSequence title;
+}
diff --git a/src/com/android/launcher2/HandleView.java b/src/com/android/launcher2/HandleView.java
new file mode 100644
index 0000000000..e07334e9f3
--- /dev/null
+++ b/src/com/android/launcher2/HandleView.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.widget.ImageView;
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+import android.view.KeyEvent;
+import android.view.View;
+
+public class HandleView extends ImageView {
+ private static final int ORIENTATION_HORIZONTAL = 1;
+
+ private Launcher mLauncher;
+ private int mOrientation = ORIENTATION_HORIZONTAL;
+
+ public HandleView(Context context) {
+ super(context);
+ }
+
+ public HandleView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public HandleView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+
+ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HandleView, defStyle, 0);
+ mOrientation = a.getInt(R.styleable.HandleView_direction, ORIENTATION_HORIZONTAL);
+ a.recycle();
+
+ setContentDescription(context.getString(R.string.all_apps_button_label));
+ }
+
+ @Override
+ public View focusSearch(int direction) {
+ View newFocus = super.focusSearch(direction);
+ if (newFocus == null && !mLauncher.isAllAppsVisible()) {
+ final Workspace workspace = mLauncher.getWorkspace();
+ workspace.dispatchUnhandledMove(null, direction);
+ return (mOrientation == ORIENTATION_HORIZONTAL && direction == FOCUS_DOWN) ?
+ this : workspace;
+ }
+ return newFocus;
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+ if (ev.getAction() == MotionEvent.ACTION_DOWN && mLauncher.isAllAppsVisible()) {
+ return false;
+ }
+ return super.onTouchEvent(ev);
+ }
+
+ private static boolean isDirectionKey(int keyCode) {
+ return keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_LEFT ||
+ keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_UP;
+ }
+
+ void setLauncher(Launcher launcher) {
+ mLauncher = launcher;
+ }
+}
diff --git a/src/com/android/launcher2/InstallShortcutReceiver.java b/src/com/android/launcher2/InstallShortcutReceiver.java
new file mode 100644
index 0000000000..45ff24e17c
--- /dev/null
+++ b/src/com/android/launcher2/InstallShortcutReceiver.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ContentResolver;
+import android.database.Cursor;
+import android.widget.Toast;
+
+public class InstallShortcutReceiver extends BroadcastReceiver {
+ private static final String ACTION_INSTALL_SHORTCUT =
+ "com.android.launcher.action.INSTALL_SHORTCUT";
+
+ private final int[] mCoordinates = new int[2];
+
+ public void onReceive(Context context, Intent data) {
+ if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {
+ return;
+ }
+
+ int screen = Launcher.getScreen();
+
+ if (!installShortcut(context, data, screen)) {
+ // The target screen is full, let's try the other screens
+ for (int i = 0; i < Launcher.SCREEN_COUNT; i++) {
+ if (i != screen && installShortcut(context, data, i)) break;
+ }
+ }
+ }
+
+ private boolean installShortcut(Context context, Intent data, int screen) {
+ String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
+
+ if (findEmptyCell(context, mCoordinates, screen)) {
+ CellLayout.CellInfo cell = new CellLayout.CellInfo();
+ cell.cellX = mCoordinates[0];
+ cell.cellY = mCoordinates[1];
+ cell.screen = screen;
+
+ Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
+
+ if (intent.getAction() == null) {
+ intent.setAction(Intent.ACTION_VIEW);
+ }
+
+ // By default, we allow for duplicate entries (located in
+ // different places)
+ boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
+ if (duplicate || !LauncherModel.shortcutExists(context, name, intent)) {
+ Launcher.addShortcut(context, data, cell, true);
+ Toast.makeText(context, context.getString(R.string.shortcut_installed, name),
+ Toast.LENGTH_SHORT).show();
+ } else {
+ Toast.makeText(context, context.getString(R.string.shortcut_duplicate, name),
+ Toast.LENGTH_SHORT).show();
+ }
+
+ return true;
+ } else {
+ Toast.makeText(context, context.getString(R.string.out_of_space),
+ Toast.LENGTH_SHORT).show();
+ }
+
+ return false;
+ }
+
+ private static boolean findEmptyCell(Context context, int[] xy, int screen) {
+ final int xCount = Launcher.NUMBER_CELLS_X;
+ final int yCount = Launcher.NUMBER_CELLS_Y;
+
+ boolean[][] occupied = new boolean[xCount][yCount];
+
+ final ContentResolver cr = context.getContentResolver();
+ Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[] { LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
+ LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY },
+ LauncherSettings.Favorites.SCREEN + "=?",
+ new String[] { String.valueOf(screen) }, null);
+
+ final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
+ final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
+ final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
+ final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
+
+ try {
+ while (c.moveToNext()) {
+ int cellX = c.getInt(cellXIndex);
+ int cellY = c.getInt(cellYIndex);
+ int spanX = c.getInt(spanXIndex);
+ int spanY = c.getInt(spanYIndex);
+
+ for (int x = cellX; x < cellX + spanX && x < xCount; x++) {
+ for (int y = cellY; y < cellY + spanY && y < yCount; y++) {
+ occupied[x][y] = true;
+ }
+ }
+ }
+ } catch (Exception e) {
+ return false;
+ } finally {
+ c.close();
+ }
+
+ return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
+ }
+}
diff --git a/src/com/android/launcher2/ItemInfo.java b/src/com/android/launcher2/ItemInfo.java
new file mode 100644
index 0000000000..f04880ddd5
--- /dev/null
+++ b/src/com/android/launcher2/ItemInfo.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import android.content.ContentValues;
+import android.graphics.Bitmap;
+import android.util.Log;
+
+/**
+ * Represents an item in the launcher.
+ */
+class ItemInfo {
+
+ static final int NO_ID = -1;
+
+ /**
+ * The id in the settings database for this item
+ */
+ long id = NO_ID;
+
+ /**
+ * One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT},
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_USER_FOLDER}, or
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET}.
+ */
+ int itemType;
+
+ /**
+ * The id of the container that holds this item. For the desktop, this will be
+ * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. For the all applications folder it
+ * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
+ * it will be the id of the folder.
+ */
+ long container = NO_ID;
+
+ /**
+ * Iindicates the screen in which the shortcut appears.
+ */
+ int screen = -1;
+
+ /**
+ * Indicates the X position of the associated cell.
+ */
+ int cellX = -1;
+
+ /**
+ * Indicates the Y position of the associated cell.
+ */
+ int cellY = -1;
+
+ /**
+ * Indicates the X cell span.
+ */
+ int spanX = 1;
+
+ /**
+ * Indicates the Y cell span.
+ */
+ int spanY = 1;
+
+ /**
+ * Indicates whether the item is a gesture.
+ */
+ boolean isGesture = false;
+
+ ItemInfo() {
+ }
+
+ ItemInfo(ItemInfo info) {
+ id = info.id;
+ cellX = info.cellX;
+ cellY = info.cellY;
+ spanX = info.spanX;
+ spanY = info.spanY;
+ screen = info.screen;
+ itemType = info.itemType;
+ container = info.container;
+ }
+
+ /**
+ * Write the fields of this item to the DB
+ *
+ * @param values
+ */
+ void onAddToDatabase(ContentValues values) {
+ values.put(LauncherSettings.BaseLauncherColumns.ITEM_TYPE, itemType);
+ if (!isGesture) {
+ values.put(LauncherSettings.Favorites.CONTAINER, container);
+ values.put(LauncherSettings.Favorites.SCREEN, screen);
+ values.put(LauncherSettings.Favorites.CELLX, cellX);
+ values.put(LauncherSettings.Favorites.CELLY, cellY);
+ values.put(LauncherSettings.Favorites.SPANX, spanX);
+ values.put(LauncherSettings.Favorites.SPANY, spanY);
+ }
+ }
+
+ static void writeBitmap(ContentValues values, Bitmap bitmap) {
+ if (bitmap != null) {
+ // Try go guesstimate how much space the icon will take when serialized
+ // to avoid unnecessary allocations/copies during the write.
+ int size = bitmap.getWidth() * bitmap.getHeight() * 4;
+ ByteArrayOutputStream out = new ByteArrayOutputStream(size);
+ try {
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
+ out.flush();
+ out.close();
+
+ values.put(LauncherSettings.Favorites.ICON, out.toByteArray());
+ } catch (IOException e) {
+ Log.w("Favorite", "Could not write icon");
+ }
+ }
+ }
+
+ void unbind() {
+ }
+}
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java
new file mode 100644
index 0000000000..45545db55b
--- /dev/null
+++ b/src/com/android/launcher2/Launcher.java
@@ -0,0 +1,2272 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.ISearchManager;
+import android.app.SearchManager;
+import android.app.StatusBarManager;
+import android.app.WallpaperManager;
+import android.content.ActivityNotFoundException;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.Intent.ShortcutIconResource;
+import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.database.ContentObserver;
+import android.graphics.Bitmap;
+import android.graphics.Rect;
+import android.graphics.Canvas;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.ColorDrawable;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SystemProperties;
+import android.provider.LiveFolders;
+import android.text.Selection;
+import android.text.SpannableStringBuilder;
+import android.text.TextUtils;
+import android.text.method.TextKeyListener;
+import android.util.Log;
+import android.view.Display;
+import android.view.HapticFeedbackConstants;
+import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.View.OnLongClickListener;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+import android.widget.ImageView;
+import android.widget.PopupWindow;
+import android.widget.LinearLayout;
+import android.appwidget.AppWidgetManager;
+import android.appwidget.AppWidgetProviderInfo;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.io.DataOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.DataInputStream;
+
+/**
+ * Default launcher application.
+ */
+public final class Launcher extends Activity
+ implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks {
+ static final String TAG = "Launcher";
+ static final boolean LOGD = false;
+
+ static final boolean PROFILE_STARTUP = false;
+ static final boolean PROFILE_ROTATE = false;
+ static final boolean DEBUG_USER_INTERFACE = false;
+
+ private static final int WALLPAPER_SCREENS_SPAN = 2;
+
+ private static final int MENU_GROUP_ADD = 1;
+ private static final int MENU_ADD = Menu.FIRST + 1;
+ private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
+ private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
+ private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
+ private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
+
+ private static final int REQUEST_CREATE_SHORTCUT = 1;
+ private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
+ private static final int REQUEST_CREATE_APPWIDGET = 5;
+ private static final int REQUEST_PICK_APPLICATION = 6;
+ private static final int REQUEST_PICK_SHORTCUT = 7;
+ private static final int REQUEST_PICK_LIVE_FOLDER = 8;
+ private static final int REQUEST_PICK_APPWIDGET = 9;
+ private static final int REQUEST_PICK_WALLPAPER = 10;
+
+ static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
+
+ static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
+ static final String SEARCH_WIDGET = "search_widget";
+
+ static final int SCREEN_COUNT = 5;
+ static final int DEFAULT_SCREEN = 2;
+ static final int NUMBER_CELLS_X = 4;
+ static final int NUMBER_CELLS_Y = 4;
+
+ static final int DIALOG_CREATE_SHORTCUT = 1;
+ static final int DIALOG_RENAME_FOLDER = 2;
+
+ private static final String PREFERENCES = "launcher.preferences";
+
+ // Type: int
+ private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
+ // Type: boolean
+ private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
+ // Type: long
+ private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
+ // Type: int
+ private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
+ // Type: int[]
+ private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
+ // Type: boolean
+ private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
+ // Type: long
+ private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
+
+ static final int APPWIDGET_HOST_ID = 1024;
+
+ private static final Object sLock = new Object();
+ private static int sScreen = DEFAULT_SCREEN;
+
+ private final BroadcastReceiver mCloseSystemDialogsReceiver
+ = new CloseSystemDialogsIntentReceiver();
+ private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
+
+ private LayoutInflater mInflater;
+
+ private DragController mDragController;
+ private Workspace mWorkspace;
+
+ private AppWidgetManager mAppWidgetManager;
+ private LauncherAppWidgetHost mAppWidgetHost;
+
+ private CellLayout.CellInfo mAddItemCellInfo;
+ private CellLayout.CellInfo mMenuAddInfo;
+ private final int[] mCellCoordinates = new int[2];
+ private FolderInfo mFolderInfo;
+
+ private DeleteZone mDeleteZone;
+ private HandleView mHandleView;
+ private AllAppsView mAllAppsGrid;
+
+ private Bundle mSavedState;
+
+ private SpannableStringBuilder mDefaultKeySsb = null;
+
+ private boolean mIsNewIntent;
+
+ private boolean mWorkspaceLoading = true;
+
+ private boolean mPaused = true;
+ private boolean mRestoring;
+ private boolean mWaitingForResult;
+
+ private Bundle mSavedInstanceState;
+
+ private LauncherModel mModel;
+
+ private ArrayList mDesktopItems = new ArrayList();
+ private static HashMap mFolders = new HashMap();
+
+ private ImageView mPreviousView;
+ private ImageView mNextView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mModel = ((LauncherApplication)getApplication()).setLauncher(this);
+ mDragController = new DragController(this);
+ mInflater = getLayoutInflater();
+
+ mAppWidgetManager = AppWidgetManager.getInstance(this);
+ mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
+ mAppWidgetHost.startListening();
+
+ if (PROFILE_STARTUP) {
+ android.os.Debug.startMethodTracing("/sdcard/launcher");
+ }
+
+ checkForLocaleChange();
+ setWallpaperDimension();
+
+ setContentView(R.layout.launcher);
+ setupViews();
+
+ registerContentObservers();
+
+ lockAllApps();
+
+ mSavedState = savedInstanceState;
+ restoreState(mSavedState);
+
+ if (PROFILE_STARTUP) {
+ android.os.Debug.stopMethodTracing();
+ }
+
+ // We have a new AllAppsView, we need to re-bind everything, and it could have
+ // changed in our absence.
+ mModel.setAllAppsDirty();
+ mModel.setWorkspaceDirty();
+
+ if (!mRestoring) {
+ mModel.startLoader(this, true);
+ }
+
+ // For handling default keys
+ mDefaultKeySsb = new SpannableStringBuilder();
+ Selection.setSelection(mDefaultKeySsb, 0);
+
+ IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
+ registerReceiver(mCloseSystemDialogsReceiver, filter);
+ }
+
+ private void checkForLocaleChange() {
+ final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
+ readConfiguration(this, localeConfiguration);
+
+ final Configuration configuration = getResources().getConfiguration();
+
+ final String previousLocale = localeConfiguration.locale;
+ final String locale = configuration.locale.toString();
+
+ final int previousMcc = localeConfiguration.mcc;
+ final int mcc = configuration.mcc;
+
+ final int previousMnc = localeConfiguration.mnc;
+ final int mnc = configuration.mnc;
+
+ boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
+
+ if (localeChanged) {
+ localeConfiguration.locale = locale;
+ localeConfiguration.mcc = mcc;
+ localeConfiguration.mnc = mnc;
+
+ writeConfiguration(this, localeConfiguration);
+ AppInfoCache.flush();
+ }
+ }
+
+ private static class LocaleConfiguration {
+ public String locale;
+ public int mcc = -1;
+ public int mnc = -1;
+ }
+
+ private static void readConfiguration(Context context, LocaleConfiguration configuration) {
+ DataInputStream in = null;
+ try {
+ in = new DataInputStream(context.openFileInput(PREFERENCES));
+ configuration.locale = in.readUTF();
+ configuration.mcc = in.readInt();
+ configuration.mnc = in.readInt();
+ } catch (FileNotFoundException e) {
+ // Ignore
+ } catch (IOException e) {
+ // Ignore
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // Ignore
+ }
+ }
+ }
+ }
+
+ private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
+ DataOutputStream out = null;
+ try {
+ out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
+ out.writeUTF(configuration.locale);
+ out.writeInt(configuration.mcc);
+ out.writeInt(configuration.mnc);
+ out.flush();
+ } catch (FileNotFoundException e) {
+ // Ignore
+ } catch (IOException e) {
+ //noinspection ResultOfMethodCallIgnored
+ context.getFileStreamPath(PREFERENCES).delete();
+ } finally {
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) {
+ // Ignore
+ }
+ }
+ }
+ }
+
+ static int getScreen() {
+ synchronized (sLock) {
+ return sScreen;
+ }
+ }
+
+ static void setScreen(int screen) {
+ synchronized (sLock) {
+ sScreen = screen;
+ }
+ }
+
+ private void setWallpaperDimension() {
+ WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
+
+ Display display = getWindowManager().getDefaultDisplay();
+ boolean isPortrait = display.getWidth() < display.getHeight();
+
+ final int width = isPortrait ? display.getWidth() : display.getHeight();
+ final int height = isPortrait ? display.getHeight() : display.getWidth();
+ wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ mWaitingForResult = false;
+
+ // The pattern used here is that a user PICKs a specific application,
+ // which, depending on the target, might need to CREATE the actual target.
+
+ // For example, the user would PICK_SHORTCUT for "Music playlist", and we
+ // launch over to the Music app to actually CREATE_SHORTCUT.
+
+ if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
+ switch (requestCode) {
+ case REQUEST_PICK_APPLICATION:
+ completeAddApplication(this, data, mAddItemCellInfo);
+ break;
+ case REQUEST_PICK_SHORTCUT:
+ processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT);
+ break;
+ case REQUEST_CREATE_SHORTCUT:
+ completeAddShortcut(data, mAddItemCellInfo);
+ break;
+ case REQUEST_PICK_LIVE_FOLDER:
+ addLiveFolder(data);
+ break;
+ case REQUEST_CREATE_LIVE_FOLDER:
+ completeAddLiveFolder(data, mAddItemCellInfo);
+ break;
+ case REQUEST_PICK_APPWIDGET:
+ addAppWidget(data);
+ break;
+ case REQUEST_CREATE_APPWIDGET:
+ completeAddAppWidget(data, mAddItemCellInfo);
+ break;
+ case REQUEST_PICK_WALLPAPER:
+ // We just wanted the activity result here so we can clear mWaitingForResult
+ break;
+ }
+ } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
+ requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED &&
+ data != null) {
+ // Clean up the appWidgetId if we canceled
+ int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
+ if (appWidgetId != -1) {
+ mAppWidgetHost.deleteAppWidgetId(appWidgetId);
+ }
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ mPaused = false;
+
+ if (mRestoring) {
+ mWorkspaceLoading = true;
+ mModel.startLoader(this, true);
+ mRestoring = false;
+ }
+
+ // If this was a new intent (i.e., the mIsNewIntent flag got set to true by
+ // onNewIntent), then close the search dialog if needed, because it probably
+ // came from the user pressing 'home' (rather than, for example, pressing 'back').
+ if (mIsNewIntent) {
+ // Post to a handler so that this happens after the search dialog tries to open
+ // itself again.
+ mWorkspace.post(new Runnable() {
+ public void run() {
+ stopSearch();
+ }
+ });
+ }
+
+ mIsNewIntent = false;
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ dismissPreview(mPreviousView);
+ dismissPreview(mNextView);
+ mDragController.cancelDrag();
+ }
+
+ @Override
+ public Object onRetainNonConfigurationInstance() {
+ // Flag the loader to stop early before switching
+ mModel.stopLoader();
+
+ if (PROFILE_ROTATE) {
+ android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
+ }
+ return null;
+ }
+
+ private boolean acceptFilter() {
+ final InputMethodManager inputManager = (InputMethodManager)
+ getSystemService(Context.INPUT_METHOD_SERVICE);
+ return !inputManager.isFullscreenMode();
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ boolean handled = super.onKeyDown(keyCode, event);
+ if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
+ boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
+ keyCode, event);
+ if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
+ // something usable has been typed - start a search
+ // the typed text will be retrieved and cleared by
+ // showSearchDialog()
+ // If there are multiple keystrokes before the search dialog takes focus,
+ // onSearchRequested() will be called for every keystroke,
+ // but it is idempotent, so it's fine.
+ return onSearchRequested();
+ }
+ }
+
+ return handled;
+ }
+
+ private String getTypedText() {
+ return mDefaultKeySsb.toString();
+ }
+
+ private void clearTypedText() {
+ mDefaultKeySsb.clear();
+ mDefaultKeySsb.clearSpans();
+ Selection.setSelection(mDefaultKeySsb, 0);
+ }
+
+ /**
+ * Restores the previous state, if it exists.
+ *
+ * @param savedState The previous state.
+ */
+ private void restoreState(Bundle savedState) {
+ if (savedState == null) {
+ return;
+ }
+
+ final boolean allApps = savedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
+ if (allApps) {
+ showAllApps(false);
+ }
+
+ final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
+ if (currentScreen > -1) {
+ mWorkspace.setCurrentScreen(currentScreen);
+ }
+
+ final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
+ if (addScreen > -1) {
+ mAddItemCellInfo = new CellLayout.CellInfo();
+ final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
+ addItemCellInfo.valid = true;
+ addItemCellInfo.screen = addScreen;
+ addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
+ addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
+ addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
+ addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
+ addItemCellInfo.findVacantCellsFromOccupied(
+ savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
+ savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
+ savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
+ mRestoring = true;
+ }
+
+ boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
+ if (renameFolder) {
+ long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
+ mFolderInfo = mModel.getFolderById(this, mFolders, id);
+ mRestoring = true;
+ }
+ }
+
+ /**
+ * Finds all the views we need and configure them properly.
+ */
+ private void setupViews() {
+ DragController dragController = mDragController;
+
+ DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
+ dragLayer.setDragController(dragController);
+
+ mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view);
+ mAllAppsGrid.setLauncher(this);
+ mAllAppsGrid.setDragController(dragController);
+ mAllAppsGrid.setWillNotDraw(false); // We don't want a hole punched in our window.
+ // Manage focusability manually since this thing is always visible
+ mAllAppsGrid.setFocusable(false);
+
+ mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
+ final Workspace workspace = mWorkspace;
+
+ DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
+ mDeleteZone = deleteZone;
+
+ mHandleView = (HandleView) findViewById(R.id.all_apps_button);
+ mHandleView.setLauncher(this);
+ mHandleView.setOnClickListener(this);
+
+ mPreviousView = (ImageView) dragLayer.findViewById(R.id.previous_screen);
+ mNextView = (ImageView) dragLayer.findViewById(R.id.next_screen);
+
+ Drawable previous = mPreviousView.getDrawable();
+ Drawable next = mNextView.getDrawable();
+ mWorkspace.setIndicators(previous, next);
+
+ mPreviousView.setHapticFeedbackEnabled(false);
+ mPreviousView.setOnLongClickListener(this);
+ mNextView.setHapticFeedbackEnabled(false);
+ mNextView.setOnLongClickListener(this);
+
+ workspace.setOnLongClickListener(this);
+ workspace.setDragController(dragController);
+ workspace.setLauncher(this);
+
+ deleteZone.setLauncher(this);
+ deleteZone.setDragController(dragController);
+ deleteZone.setHandle(mHandleView);
+
+ dragController.setDragScoller(workspace);
+ dragController.setDragListener(deleteZone);
+ dragController.setScrollView(dragLayer);
+
+ // The order here is bottom to top.
+ dragController.addDropTarget(workspace);
+ dragController.addDropTarget(deleteZone);
+ }
+
+ @SuppressWarnings({"UnusedDeclaration"})
+ public void previousScreen(View v) {
+ if (!isAllAppsVisible()) {
+ mWorkspace.scrollLeft();
+ }
+ }
+
+ @SuppressWarnings({"UnusedDeclaration"})
+ public void nextScreen(View v) {
+ if (!isAllAppsVisible()) {
+ mWorkspace.scrollRight();
+ }
+ }
+
+ /**
+ * Creates a view representing a shortcut.
+ *
+ * @param info The data structure describing the shortcut.
+ *
+ * @return A View inflated from R.layout.application.
+ */
+ View createShortcut(ApplicationInfo info) {
+ return createShortcut(R.layout.application,
+ (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
+ }
+
+ /**
+ * Creates a view representing a shortcut inflated from the specified resource.
+ *
+ * @param layoutResId The id of the XML layout used to create the shortcut.
+ * @param parent The group the shortcut belongs to.
+ * @param info The data structure describing the shortcut.
+ *
+ * @return A View inflated from layoutResId.
+ */
+ View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
+ TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
+
+ if (info.icon == null) {
+ info.icon = AppInfoCache.getIconDrawable(getPackageManager(), info);
+ }
+ if (!info.filtered) {
+ info.icon = Utilities.createIconThumbnail(info.icon, this);
+ info.filtered = true;
+ }
+
+ favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
+ favorite.setText(info.title);
+ favorite.setTag(info);
+ favorite.setOnClickListener(this);
+
+ return favorite;
+ }
+
+ /**
+ * Add an application shortcut to the workspace.
+ *
+ * @param data The intent describing the application.
+ * @param cellInfo The position on screen where to create the shortcut.
+ */
+ void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) {
+ cellInfo.screen = mWorkspace.getCurrentScreen();
+ if (!findSingleSlot(cellInfo)) return;
+
+ final ApplicationInfo info = infoFromApplicationIntent(context, data);
+ if (info != null) {
+ mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked());
+ }
+ }
+
+ private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) {
+ ComponentName component = data.getComponent();
+ PackageManager packageManager = context.getPackageManager();
+ ActivityInfo activityInfo = null;
+ try {
+ activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
+ } catch (NameNotFoundException e) {
+ Log.e(TAG, "Couldn't find ActivityInfo for selected application", e);
+ }
+
+ if (activityInfo != null) {
+ ApplicationInfo itemInfo = new ApplicationInfo();
+
+ itemInfo.title = activityInfo.loadLabel(packageManager);
+ if (itemInfo.title == null) {
+ itemInfo.title = activityInfo.name;
+ }
+
+ itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
+ Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+ itemInfo.icon = activityInfo.loadIcon(packageManager);
+ itemInfo.container = ItemInfo.NO_ID;
+
+ return itemInfo;
+ }
+
+ return null;
+ }
+
+ /**
+ * Add a shortcut to the workspace.
+ *
+ * @param data The intent describing the shortcut.
+ * @param cellInfo The position on screen where to create the shortcut.
+ */
+ private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) {
+ cellInfo.screen = mWorkspace.getCurrentScreen();
+ if (!findSingleSlot(cellInfo)) return;
+
+ final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
+
+ if (!mRestoring) {
+ final View view = createShortcut(info);
+ mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
+ isWorkspaceLocked());
+ }
+ }
+
+
+ /**
+ * Add a widget to the workspace.
+ *
+ * @param data The intent describing the appWidgetId.
+ * @param cellInfo The position on screen where to create the widget.
+ */
+ private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) {
+ Bundle extras = data.getExtras();
+ int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
+
+ if (LOGD) Log.d(TAG, "dumping extras content=" + extras.toString());
+
+ AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
+
+ // Calculate the grid spans needed to fit this widget
+ CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
+ int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
+
+ // Try finding open space on Launcher screen
+ final int[] xy = mCellCoordinates;
+ if (!findSlot(cellInfo, xy, spans[0], spans[1])) {
+ if (appWidgetId != -1) mAppWidgetHost.deleteAppWidgetId(appWidgetId);
+ return;
+ }
+
+ // Build Launcher-specific widget info and save to database
+ LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
+ launcherInfo.spanX = spans[0];
+ launcherInfo.spanY = spans[1];
+
+ LauncherModel.addItemToDatabase(this, launcherInfo,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
+
+ if (!mRestoring) {
+ mDesktopItems.add(launcherInfo);
+
+ // Perform actual inflation because we're live
+ launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
+
+ launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
+ launcherInfo.hostView.setTag(launcherInfo);
+
+ mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
+ launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
+ }
+ }
+
+ public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
+ mDesktopItems.remove(launcherInfo);
+ launcherInfo.hostView = null;
+ }
+
+ public LauncherAppWidgetHost getAppWidgetHost() {
+ return mAppWidgetHost;
+ }
+
+ static ApplicationInfo addShortcut(Context context, Intent data,
+ CellLayout.CellInfo cellInfo, boolean notify) {
+
+ final ApplicationInfo info = infoFromShortcutIntent(context, data);
+ LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
+
+ return info;
+ }
+
+ private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) {
+ Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
+ String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
+ Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
+
+ Drawable icon = null;
+ boolean filtered = false;
+ boolean customIcon = false;
+ ShortcutIconResource iconResource = null;
+
+ if (bitmap != null) {
+ icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
+ filtered = true;
+ customIcon = true;
+ } else {
+ Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
+ if (extra != null && extra instanceof ShortcutIconResource) {
+ try {
+ iconResource = (ShortcutIconResource) extra;
+ final PackageManager packageManager = context.getPackageManager();
+ Resources resources = packageManager.getResourcesForApplication(
+ iconResource.packageName);
+ final int id = resources.getIdentifier(iconResource.resourceName, null, null);
+ icon = resources.getDrawable(id);
+ } catch (Exception e) {
+ Log.w(TAG, "Could not load shortcut icon: " + extra);
+ }
+ }
+ }
+
+ if (icon == null) {
+ icon = context.getPackageManager().getDefaultActivityIcon();
+ }
+
+ final ApplicationInfo info = new ApplicationInfo();
+ info.icon = icon;
+ info.filtered = filtered;
+ info.title = name;
+ info.intent = intent;
+ info.customIcon = customIcon;
+ info.iconResource = iconResource;
+
+ return info;
+ }
+
+ void closeSystemDialogs() {
+ getWindow().closeAllPanels();
+
+ try {
+ dismissDialog(DIALOG_CREATE_SHORTCUT);
+ // Unlock the workspace if the dialog was showing
+ } catch (Exception e) {
+ // An exception is thrown if the dialog is not visible, which is fine
+ }
+
+ try {
+ dismissDialog(DIALOG_RENAME_FOLDER);
+ // Unlock the workspace if the dialog was showing
+ } catch (Exception e) {
+ // An exception is thrown if the dialog is not visible, which is fine
+ }
+
+ // Whatever we were doing is hereby canceled.
+ mWaitingForResult = false;
+ }
+
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+
+ // Close the menu
+ if (Intent.ACTION_MAIN.equals(intent.getAction())) {
+ // also will cancel mWaitingForResult.
+ closeSystemDialogs();
+
+ // Set this flag so that onResume knows to close the search dialog if it's open,
+ // because this was a new intent (thus a press of 'home' or some such) rather than
+ // for example onResume being called when the user pressed the 'back' button.
+ mIsNewIntent = true;
+
+ boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
+ != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
+ boolean allAppsVisible = isAllAppsVisible();
+ if (!mWorkspace.isDefaultScreenShowing()) {
+ mWorkspace.moveToDefaultScreen(alreadyOnHome && !allAppsVisible);
+ }
+ closeAllApps(alreadyOnHome && allAppsVisible);
+
+ final View v = getWindow().peekDecorView();
+ if (v != null && v.getWindowToken() != null) {
+ InputMethodManager imm = (InputMethodManager)getSystemService(
+ INPUT_METHOD_SERVICE);
+ imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
+ }
+ }
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ // Do not call super here
+ mSavedInstanceState = savedInstanceState;
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
+
+ final ArrayList folders = mWorkspace.getOpenFolders();
+ if (folders.size() > 0) {
+ final int count = folders.size();
+ long[] ids = new long[count];
+ for (int i = 0; i < count; i++) {
+ final FolderInfo info = folders.get(i).getInfo();
+ ids[i] = info.id;
+ }
+ outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
+ } else {
+ super.onSaveInstanceState(outState);
+ }
+
+ // TODO should not do this if the drawer is currently closing.
+ if (isAllAppsVisible()) {
+ outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
+ }
+
+ if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
+ final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
+ final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
+
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
+ outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
+ outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
+ layout.getOccupiedCells());
+ }
+
+ if (mFolderInfo != null && mWaitingForResult) {
+ outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
+ outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ try {
+ mAppWidgetHost.stopListening();
+ } catch (NullPointerException ex) {
+ Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
+ }
+
+ TextKeyListener.getInstance().release();
+
+ mModel.stopLoader();
+
+ unbindDesktopItems();
+ AppInfoCache.unbindDrawables();
+
+ getContentResolver().unregisterContentObserver(mWidgetObserver);
+
+ dismissPreview(mPreviousView);
+ dismissPreview(mNextView);
+
+ unregisterReceiver(mCloseSystemDialogsReceiver);
+ }
+
+ @Override
+ public void startActivityForResult(Intent intent, int requestCode) {
+ if (requestCode >= 0) mWaitingForResult = true;
+ super.startActivityForResult(intent, requestCode);
+ }
+
+ @Override
+ public void startSearch(String initialQuery, boolean selectInitialQuery,
+ Bundle appSearchData, boolean globalSearch) {
+
+ closeAllApps(true);
+
+ // Slide the search widget to the top, if it's on the current screen,
+ // otherwise show the search dialog immediately.
+ Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
+ if (searchWidget == null) {
+ showSearchDialog(initialQuery, selectInitialQuery, appSearchData, globalSearch);
+ } else {
+ searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
+ // show the currently typed text in the search widget while sliding
+ searchWidget.setQuery(getTypedText());
+ }
+ }
+
+ /**
+ * Show the search dialog immediately, without changing the search widget.
+ *
+ * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean)
+ */
+ void showSearchDialog(String initialQuery, boolean selectInitialQuery,
+ Bundle appSearchData, boolean globalSearch) {
+
+ if (initialQuery == null) {
+ // Use any text typed in the launcher as the initial query
+ initialQuery = getTypedText();
+ clearTypedText();
+ }
+ if (appSearchData == null) {
+ appSearchData = new Bundle();
+ appSearchData.putString(SearchManager.SOURCE, "launcher-search");
+ }
+
+ final SearchManager searchManager =
+ (SearchManager) getSystemService(Context.SEARCH_SERVICE);
+
+ final Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
+ if (searchWidget != null) {
+ // This gets called when the user leaves the search dialog to go back to
+ // the Launcher.
+ searchManager.setOnCancelListener(new SearchManager.OnCancelListener() {
+ public void onCancel() {
+ searchManager.setOnCancelListener(null);
+ stopSearch();
+ }
+ });
+ }
+
+ searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
+ appSearchData, globalSearch);
+ }
+
+ /**
+ * Cancel search dialog if it is open.
+ */
+ void stopSearch() {
+ // Close search dialog
+ SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
+ searchManager.stopSearch();
+ // Restore search widget to its normal position
+ Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
+ if (searchWidget != null) {
+ searchWidget.stopSearch(false);
+ }
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ if (isWorkspaceLocked()) {
+ return false;
+ }
+
+ super.onCreateOptionsMenu(menu);
+ menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
+ .setIcon(android.R.drawable.ic_menu_add)
+ .setAlphabeticShortcut('A');
+ menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
+ .setIcon(android.R.drawable.ic_menu_gallery)
+ .setAlphabeticShortcut('W');
+ menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
+ .setIcon(android.R.drawable.ic_search_category_default)
+ .setAlphabeticShortcut(SearchManager.MENU_KEY);
+ menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
+ .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
+ .setAlphabeticShortcut('N');
+
+ final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
+ settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
+ Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+
+ menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
+ .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
+ .setIntent(settings);
+
+ return true;
+ }
+
+ @Override
+ public boolean onPrepareOptionsMenu(Menu menu) {
+ super.onPrepareOptionsMenu(menu);
+
+ mMenuAddInfo = mWorkspace.findAllVacantCells(null);
+ menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
+
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case MENU_ADD:
+ addItems();
+ return true;
+ case MENU_WALLPAPER_SETTINGS:
+ startWallpaper();
+ return true;
+ case MENU_SEARCH:
+ onSearchRequested();
+ return true;
+ case MENU_NOTIFICATIONS:
+ showNotifications();
+ return true;
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ /**
+ * Indicates that we want global search for this activity by setting the globalSearch
+ * argument for {@link #startSearch} to true.
+ */
+
+ @Override
+ public boolean onSearchRequested() {
+ startSearch(null, false, null, true);
+ return true;
+ }
+
+ public boolean isWorkspaceLocked() {
+ return mWorkspaceLoading || mWaitingForResult;
+ }
+
+ private void addItems() {
+ closeAllApps(true);
+ showAddDialog(mMenuAddInfo);
+ }
+
+ void addAppWidget(Intent data) {
+ // TODO: catch bad widget exception when sent
+ int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
+
+ String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
+ if (SEARCH_WIDGET.equals(customWidget)) {
+ // We don't need this any more, since this isn't a real app widget.
+ mAppWidgetHost.deleteAppWidgetId(appWidgetId);
+ // add the search widget
+ addSearch();
+ } else {
+ AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
+
+ if (appWidget.configure != null) {
+ // Launch over to configure widget, if needed
+ Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
+ intent.setComponent(appWidget.configure);
+ intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
+
+ startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
+ } else {
+ // Otherwise just add it
+ onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
+ }
+ }
+ }
+
+ void addSearch() {
+ final Widget info = Widget.makeSearch();
+ final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
+
+ final int[] xy = mCellCoordinates;
+ final int spanX = info.spanX;
+ final int spanY = info.spanY;
+
+ if (!findSlot(cellInfo, xy, spanX, spanY)) return;
+
+ LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
+
+ final View view = mInflater.inflate(info.layoutResource, null);
+ view.setTag(info);
+ Search search = (Search) view.findViewById(R.id.widget_search);
+ search.setLauncher(this);
+
+ mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
+ }
+
+ void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) {
+ // Handle case where user selected "Applications"
+ String applicationName = getResources().getString(R.string.group_applications);
+ String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
+
+ if (applicationName != null && applicationName.equals(shortcutName)) {
+ Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
+ mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
+
+ Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
+ pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
+ startActivityForResult(pickIntent, requestCodeApplication);
+ } else {
+ startActivityForResult(intent, requestCodeShortcut);
+ }
+ }
+
+ void addLiveFolder(Intent intent) {
+ // Handle case where user selected "Folder"
+ String folderName = getResources().getString(R.string.group_folder);
+ String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
+
+ if (folderName != null && folderName.equals(shortcutName)) {
+ addFolder();
+ } else {
+ startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
+ }
+ }
+
+ void addFolder() {
+ UserFolderInfo folderInfo = new UserFolderInfo();
+ folderInfo.title = getText(R.string.folder_name);
+
+ CellLayout.CellInfo cellInfo = mAddItemCellInfo;
+ cellInfo.screen = mWorkspace.getCurrentScreen();
+ if (!findSingleSlot(cellInfo)) return;
+
+ // Update the model
+ LauncherModel.addItemToDatabase(this, folderInfo,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
+ mFolders.put(folderInfo.id, folderInfo);
+
+ // Create the view
+ FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
+ (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
+ mWorkspace.addInCurrentScreen(newFolder,
+ cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked());
+ }
+
+ void removeFolder(FolderInfo folder) {
+ mFolders.remove(folder.id);
+ }
+
+ private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) {
+ cellInfo.screen = mWorkspace.getCurrentScreen();
+ if (!findSingleSlot(cellInfo)) return;
+
+ final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
+
+ if (!mRestoring) {
+ final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
+ (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
+ mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
+ isWorkspaceLocked());
+ }
+ }
+
+ static LiveFolderInfo addLiveFolder(Context context, Intent data,
+ CellLayout.CellInfo cellInfo, boolean notify) {
+
+ Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
+ String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
+
+ Drawable icon = null;
+ boolean filtered = false;
+ Intent.ShortcutIconResource iconResource = null;
+
+ Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
+ if (extra != null && extra instanceof Intent.ShortcutIconResource) {
+ try {
+ iconResource = (Intent.ShortcutIconResource) extra;
+ final PackageManager packageManager = context.getPackageManager();
+ Resources resources = packageManager.getResourcesForApplication(
+ iconResource.packageName);
+ final int id = resources.getIdentifier(iconResource.resourceName, null, null);
+ icon = resources.getDrawable(id);
+ } catch (Exception e) {
+ Log.w(TAG, "Could not load live folder icon: " + extra);
+ }
+ }
+
+ if (icon == null) {
+ icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
+ }
+
+ final LiveFolderInfo info = new LiveFolderInfo();
+ info.icon = icon;
+ info.filtered = filtered;
+ info.title = name;
+ info.iconResource = iconResource;
+ info.uri = data.getData();
+ info.baseIntent = baseIntent;
+ info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
+ LiveFolders.DISPLAY_MODE_GRID);
+
+ LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
+ mFolders.put(info.id, info);
+
+ return info;
+ }
+
+ private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
+ final int[] xy = new int[2];
+ if (findSlot(cellInfo, xy, 1, 1)) {
+ cellInfo.cellX = xy[0];
+ cellInfo.cellY = xy[1];
+ return true;
+ }
+ return false;
+ }
+
+ private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
+ if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
+ boolean[] occupied = mSavedState != null ?
+ mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
+ cellInfo = mWorkspace.findAllVacantCells(occupied);
+ if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
+ Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void showNotifications() {
+ final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
+ if (statusBar != null) {
+ statusBar.expand();
+ }
+ }
+
+ private void startWallpaper() {
+ closeAllApps(true);
+ final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
+ Intent chooser = Intent.createChooser(pickWallpaper,
+ getText(R.string.chooser_wallpaper));
+ // NOTE: Adds a configure option to the chooser if the wallpaper supports it
+ // Removed in Eclair MR1
+// WallpaperManager wm = (WallpaperManager)
+// getSystemService(Context.WALLPAPER_SERVICE);
+// WallpaperInfo wi = wm.getWallpaperInfo();
+// if (wi != null && wi.getSettingsActivity() != null) {
+// LabeledIntent li = new LabeledIntent(getPackageName(),
+// R.string.configure_wallpaper, 0);
+// li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
+// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
+// }
+ startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
+ }
+
+ /**
+ * Registers various content observers. The current implementation registers
+ * only a favorites observer to keep track of the favorites applications.
+ */
+ private void registerContentObservers() {
+ ContentResolver resolver = getContentResolver();
+ resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
+ true, mWidgetObserver);
+ }
+
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ if (event.getAction() == KeyEvent.ACTION_DOWN) {
+ switch (event.getKeyCode()) {
+ case KeyEvent.KEYCODE_HOME:
+ return true;
+ case KeyEvent.KEYCODE_VOLUME_DOWN:
+ if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
+ dumpState();
+ return true;
+ }
+ break;
+ }
+ } else if (event.getAction() == KeyEvent.ACTION_UP) {
+ switch (event.getKeyCode()) {
+ case KeyEvent.KEYCODE_HOME:
+ return true;
+ }
+ }
+
+ return super.dispatchKeyEvent(event);
+ }
+
+ @Override
+ public void onBackPressed() {
+ if (isAllAppsVisible()) {
+ closeAllApps(true);
+ } else {
+ closeFolder();
+ }
+ dismissPreview(mPreviousView);
+ dismissPreview(mNextView);
+ }
+
+ private void closeFolder() {
+ Folder folder = mWorkspace.getOpenFolder();
+ if (folder != null) {
+ closeFolder(folder);
+ }
+ }
+
+ void closeFolder(Folder folder) {
+ folder.getInfo().opened = false;
+ ViewGroup parent = (ViewGroup) folder.getParent();
+ if (parent != null) {
+ parent.removeView(folder);
+ if (folder instanceof DropTarget) {
+ // Live folders aren't DropTargets.
+ mDragController.removeDropTarget((DropTarget)folder);
+ }
+ }
+ folder.onClose();
+ }
+
+ /**
+ * Re-listen when widgets are reset.
+ */
+ private void onAppWidgetReset() {
+ mAppWidgetHost.startListening();
+ }
+
+ /**
+ * Go through the and disconnect any of the callbacks in the drawables and the views or we
+ * leak the previous Home screen on orientation change.
+ */
+ private void unbindDesktopItems() {
+ for (ItemInfo item: mDesktopItems) {
+ item.unbind();
+ }
+ }
+
+ /**
+ * Launches the intent referred by the clicked shortcut.
+ *
+ * @param v The view representing the clicked shortcut.
+ */
+ public void onClick(View v) {
+ Object tag = v.getTag();
+ if (tag instanceof ApplicationInfo) {
+ // Open shortcut
+ final Intent intent = ((ApplicationInfo) tag).intent;
+ int[] pos = new int[2];
+ v.getLocationOnScreen(pos);
+ intent.setSourceBounds(
+ new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
+ startActivitySafely(intent);
+ } else if (tag instanceof FolderInfo) {
+ handleFolderClick((FolderInfo) tag);
+ } else if (v == mHandleView) {
+ if (isAllAppsVisible()) {
+ closeAllApps(true);
+ } else {
+ showAllApps(true);
+ }
+ }
+ }
+
+ void startActivitySafely(Intent intent) {
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ try {
+ startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
+ } catch (SecurityException e) {
+ Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
+ Log.e(TAG, "Launcher does not have the permission to launch " + intent +
+ ". Make sure to create a MAIN intent-filter for the corresponding activity " +
+ "or use the exported attribute for this activity.", e);
+ }
+ }
+
+ private void handleFolderClick(FolderInfo folderInfo) {
+ if (!folderInfo.opened) {
+ // Close any open folder
+ closeFolder();
+ // Open the requested folder
+ openFolder(folderInfo);
+ } else {
+ // Find the open folder...
+ Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
+ int folderScreen;
+ if (openFolder != null) {
+ folderScreen = mWorkspace.getScreenForView(openFolder);
+ // .. and close it
+ closeFolder(openFolder);
+ if (folderScreen != mWorkspace.getCurrentScreen()) {
+ // Close any folder open on the current screen
+ closeFolder();
+ // Pull the folder onto this screen
+ openFolder(folderInfo);
+ }
+ }
+ }
+ }
+
+ /**
+ * Opens the user fodler described by the specified tag. The opening of the folder
+ * is animated relative to the specified View. If the View is null, no animation
+ * is played.
+ *
+ * @param folderInfo The FolderInfo describing the folder to open.
+ */
+ private void openFolder(FolderInfo folderInfo) {
+ Folder openFolder;
+
+ if (folderInfo instanceof UserFolderInfo) {
+ openFolder = UserFolder.fromXml(this);
+ } else if (folderInfo instanceof LiveFolderInfo) {
+ openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo);
+ } else {
+ return;
+ }
+
+ openFolder.setDragController(mDragController);
+ openFolder.setLauncher(this);
+
+ openFolder.bind(folderInfo);
+ folderInfo.opened = true;
+
+ mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
+ openFolder.onOpen();
+ }
+
+ public boolean onLongClick(View v) {
+ switch (v.getId()) {
+ case R.id.previous_screen:
+ if (!isAllAppsVisible()) {
+ mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
+ HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
+ showPreviousPreview(v);
+ }
+ return true;
+ case R.id.next_screen:
+ if (!isAllAppsVisible()) {
+ mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
+ HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
+ showNextPreview(v);
+ }
+ return true;
+ }
+
+ if (isWorkspaceLocked()) {
+ return false;
+ }
+
+ if (!(v instanceof CellLayout)) {
+ v = (View) v.getParent();
+ }
+
+ CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
+
+ // This happens when long clicking an item with the dpad/trackball
+ if (cellInfo == null) {
+ return true;
+ }
+
+ if (mWorkspace.allowLongPress()) {
+ if (cellInfo.cell == null) {
+ if (cellInfo.valid) {
+ // User long pressed on empty space
+ mWorkspace.setAllowLongPress(false);
+ showAddDialog(cellInfo);
+ }
+ } else {
+ if (!(cellInfo.cell instanceof Folder)) {
+ // User long pressed on an item
+ mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
+ HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
+ mWorkspace.startDrag(cellInfo);
+ }
+ }
+ }
+ return true;
+ }
+
+ @SuppressWarnings({"unchecked"})
+ private void dismissPreview(final View v) {
+ final PopupWindow window = (PopupWindow) v.getTag();
+ if (window != null) {
+ window.setOnDismissListener(new PopupWindow.OnDismissListener() {
+ public void onDismiss() {
+ ViewGroup group = (ViewGroup) v.getTag(R.id.workspace);
+ int count = group.getChildCount();
+ for (int i = 0; i < count; i++) {
+ ((ImageView) group.getChildAt(i)).setImageDrawable(null);
+ }
+ ArrayList bitmaps = (ArrayList) v.getTag(R.id.icon);
+ for (Bitmap bitmap : bitmaps) bitmap.recycle();
+
+ v.setTag(R.id.workspace, null);
+ v.setTag(R.id.icon, null);
+ window.setOnDismissListener(null);
+ }
+ });
+ window.dismiss();
+ }
+ v.setTag(null);
+ }
+
+ private void showPreviousPreview(View anchor) {
+ int current = mWorkspace.getCurrentScreen();
+ if (current <= 0) return;
+
+ showPreviews(anchor, 0, mWorkspace.getChildCount());
+ }
+
+ private void showNextPreview(View anchor) {
+ int current = mWorkspace.getCurrentScreen();
+ if (current >= mWorkspace.getChildCount() - 1) return;
+
+ showPreviews(anchor, 0, mWorkspace.getChildCount());
+ }
+
+ private void showPreviews(final View anchor, int start, int end) {
+ Resources resources = getResources();
+
+ Workspace workspace = mWorkspace;
+ CellLayout cell = ((CellLayout) workspace.getChildAt(start));
+
+ float max = workspace.getChildCount();
+
+ Rect r = new Rect();
+ resources.getDrawable(R.drawable.preview_background).getPadding(r);
+ int extraW = (int) ((r.left + r.right) * max);
+ int extraH = r.top + r.bottom;
+
+ int aW = cell.getWidth() - extraW;
+ float w = aW / max;
+
+ int width = cell.getWidth();
+ int height = cell.getHeight();
+ int x = cell.getLeftPadding();
+ int y = cell.getTopPadding();
+ width -= (x + cell.getRightPadding());
+ height -= (y + cell.getBottomPadding());
+
+ float scale = w / width;
+
+ int count = end - start;
+
+ final float sWidth = width * scale;
+ float sHeight = height * scale;
+
+ LinearLayout preview = new LinearLayout(this);
+
+ PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
+ ArrayList bitmaps = new ArrayList(count);
+
+ for (int i = start; i < end; i++) {
+ ImageView image = new ImageView(this);
+ cell = (CellLayout) workspace.getChildAt(i);
+
+ Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
+ Bitmap.Config.ARGB_8888);
+
+ Canvas c = new Canvas(bitmap);
+ c.scale(scale, scale);
+ c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
+ cell.dispatchDraw(c);
+
+ image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
+ image.setImageBitmap(bitmap);
+ image.setTag(i);
+ image.setOnClickListener(handler);
+ image.setOnFocusChangeListener(handler);
+ image.setFocusable(true);
+ if (i == mWorkspace.getCurrentScreen()) image.requestFocus();
+
+ preview.addView(image,
+ LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+
+ bitmaps.add(bitmap);
+ }
+
+ PopupWindow p = new PopupWindow(this);
+ p.setContentView(preview);
+ p.setWidth((int) (sWidth * count + extraW));
+ p.setHeight((int) (sHeight + extraH));
+ p.setAnimationStyle(R.style.AnimationPreview);
+ p.setOutsideTouchable(true);
+ p.setFocusable(true);
+ p.setBackgroundDrawable(new ColorDrawable(0));
+ p.showAsDropDown(anchor, 0, 0);
+
+ p.setOnDismissListener(new PopupWindow.OnDismissListener() {
+ public void onDismiss() {
+ dismissPreview(anchor);
+ }
+ });
+
+ anchor.setTag(p);
+ anchor.setTag(R.id.workspace, preview);
+ anchor.setTag(R.id.icon, bitmaps);
+ }
+
+ class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener {
+ private final View mAnchor;
+
+ public PreviewTouchHandler(View anchor) {
+ mAnchor = anchor;
+ }
+
+ public void onClick(View v) {
+ mWorkspace.snapToScreen((Integer) v.getTag());
+ v.post(this);
+ }
+
+ public void run() {
+ dismissPreview(mAnchor);
+ }
+
+ public void onFocusChange(View v, boolean hasFocus) {
+ if (hasFocus) {
+ mWorkspace.snapToScreen((Integer) v.getTag());
+ }
+ }
+ }
+
+ View getDrawerHandle() {
+ return mHandleView;
+ }
+
+ Workspace getWorkspace() {
+ return mWorkspace;
+ }
+
+ @Override
+ protected Dialog onCreateDialog(int id) {
+ switch (id) {
+ case DIALOG_CREATE_SHORTCUT:
+ return new CreateShortcut().createDialog();
+ case DIALOG_RENAME_FOLDER:
+ return new RenameFolder().createDialog();
+ }
+
+ return super.onCreateDialog(id);
+ }
+
+ @Override
+ protected void onPrepareDialog(int id, Dialog dialog) {
+ switch (id) {
+ case DIALOG_CREATE_SHORTCUT:
+ break;
+ case DIALOG_RENAME_FOLDER:
+ if (mFolderInfo != null) {
+ EditText input = (EditText) dialog.findViewById(R.id.folder_name);
+ final CharSequence text = mFolderInfo.title;
+ input.setText(text);
+ input.setSelection(0, text.length());
+ }
+ break;
+ }
+ }
+
+ void showRenameDialog(FolderInfo info) {
+ mFolderInfo = info;
+ mWaitingForResult = true;
+ showDialog(DIALOG_RENAME_FOLDER);
+ }
+
+ private void showAddDialog(CellLayout.CellInfo cellInfo) {
+ mAddItemCellInfo = cellInfo;
+ mWaitingForResult = true;
+ showDialog(DIALOG_CREATE_SHORTCUT);
+ }
+
+ private void pickShortcut(int requestCode, int title) {
+ Bundle bundle = new Bundle();
+
+ ArrayList shortcutNames = new ArrayList();
+ shortcutNames.add(getString(R.string.group_applications));
+ bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
+
+ ArrayList shortcutIcons = new ArrayList();
+ shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
+ R.drawable.ic_launcher_application));
+ bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
+
+ Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
+ pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
+ pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title));
+ pickIntent.putExtras(bundle);
+
+ startActivityForResult(pickIntent, requestCode);
+ }
+
+ private class RenameFolder {
+ private EditText mInput;
+
+ Dialog createDialog() {
+ mWaitingForResult = true;
+ final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
+ mInput = (EditText) layout.findViewById(R.id.folder_name);
+
+ AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
+ builder.setIcon(0);
+ builder.setTitle(getString(R.string.rename_folder_title));
+ builder.setCancelable(true);
+ builder.setOnCancelListener(new Dialog.OnCancelListener() {
+ public void onCancel(DialogInterface dialog) {
+ cleanup();
+ }
+ });
+ builder.setNegativeButton(getString(R.string.cancel_action),
+ new Dialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ cleanup();
+ }
+ }
+ );
+ builder.setPositiveButton(getString(R.string.rename_action),
+ new Dialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ changeFolderName();
+ }
+ }
+ );
+ builder.setView(layout);
+
+ final AlertDialog dialog = builder.create();
+ dialog.setOnShowListener(new DialogInterface.OnShowListener() {
+ public void onShow(DialogInterface dialog) {
+ mInput.requestFocus();
+ InputMethodManager inputManager = (InputMethodManager)
+ getSystemService(Context.INPUT_METHOD_SERVICE);
+ inputManager.showSoftInput(mInput, 0);
+ }
+ });
+
+ return dialog;
+ }
+
+ private void changeFolderName() {
+ final String name = mInput.getText().toString();
+ if (!TextUtils.isEmpty(name)) {
+ // Make sure we have the right folder info
+ mFolderInfo = mFolders.get(mFolderInfo.id);
+ mFolderInfo.title = name;
+ LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
+
+ if (mWorkspaceLoading) {
+ lockAllApps();
+ mModel.setWorkspaceDirty();
+ mModel.startLoader(Launcher.this, false);
+ } else {
+ final FolderIcon folderIcon = (FolderIcon)
+ mWorkspace.getViewForTag(mFolderInfo);
+ if (folderIcon != null) {
+ folderIcon.setText(name);
+ getWorkspace().requestLayout();
+ } else {
+ lockAllApps();
+ mModel.setWorkspaceDirty();
+ mWorkspaceLoading = true;
+ mModel.startLoader(Launcher.this, false);
+ }
+ }
+ }
+ cleanup();
+ }
+
+ private void cleanup() {
+ dismissDialog(DIALOG_RENAME_FOLDER);
+ mWaitingForResult = false;
+ mFolderInfo = null;
+ }
+ }
+
+ boolean isAllAppsVisible() {
+ return mAllAppsGrid.isVisible();
+ }
+
+ boolean isAllAppsOpaque() {
+ return mAllAppsGrid.isOpaque();
+ }
+
+ void showAllApps(boolean animated) {
+ mAllAppsGrid.zoom(1.0f, animated);
+ //mWorkspace.hide();
+
+ mWorkspace.startFading(false);
+
+ mAllAppsGrid.setFocusable(true);
+ mAllAppsGrid.requestFocus();
+
+ // TODO: fade these two too
+ mDeleteZone.setVisibility(View.GONE);
+ //mHandleView.setVisibility(View.GONE);
+ }
+
+ /**
+ * Things to test when changing this code.
+ * - Home from workspace
+ * - from center screen
+ * - from other screens
+ * - Home from all apps
+ * - from center screen
+ * - from other screens
+ * - Back from all apps
+ * - from center screen
+ * - from other screens
+ * - Launch app from workspace and quit
+ * - with back
+ * - with home
+ * - Launch app from all apps and quit
+ * - with back
+ * - with home
+ * - Go to a screen that's not the default, then all
+ * apps, and launch and app, and go back
+ * - with back
+ * -with home
+ * - On workspace, long press power and go back
+ * - with back
+ * - with home
+ * - On all apps, long press power and go back
+ * - with back
+ * - with home
+ * - On workspace, power off
+ * - On all apps, power off
+ * - Launch an app and turn off the screen while in that app
+ * - Go back with home key
+ * - Go back with back key TODO: make this not go to workspace
+ * - From all apps
+ * - From workspace
+ */
+ void closeAllApps(boolean animated) {
+ if (mAllAppsGrid.isVisible()) {
+ mAllAppsGrid.zoom(0.0f, animated);
+ mAllAppsGrid.setFocusable(false);
+ mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
+ mWorkspace.startFading(true);
+
+ // TODO: fade these two too
+ /*
+ mDeleteZone.setVisibility(View.VISIBLE);
+ mHandleView.setVisibility(View.VISIBLE);
+ */
+ }
+ }
+
+ void lockAllApps() {
+ // TODO
+ }
+
+ void unlockAllApps() {
+ // TODO
+ }
+
+ /**
+ * Displays the shortcut creation dialog and launches, if necessary, the
+ * appropriate activity.
+ */
+ private class CreateShortcut implements DialogInterface.OnClickListener,
+ DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
+ DialogInterface.OnShowListener {
+
+ private AddAdapter mAdapter;
+
+ Dialog createDialog() {
+ mWaitingForResult = true;
+
+ mAdapter = new AddAdapter(Launcher.this);
+
+ final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
+ builder.setTitle(getString(R.string.menu_item_add_item));
+ builder.setAdapter(mAdapter, this);
+
+ builder.setInverseBackgroundForced(true);
+
+ AlertDialog dialog = builder.create();
+ dialog.setOnCancelListener(this);
+ dialog.setOnDismissListener(this);
+ dialog.setOnShowListener(this);
+
+ return dialog;
+ }
+
+ public void onCancel(DialogInterface dialog) {
+ mWaitingForResult = false;
+ cleanup();
+ }
+
+ public void onDismiss(DialogInterface dialog) {
+ }
+
+ private void cleanup() {
+ try {
+ dismissDialog(DIALOG_CREATE_SHORTCUT);
+ } catch (Exception e) {
+ // An exception is thrown if the dialog is not visible, which is fine
+ }
+ }
+
+ /**
+ * Handle the action clicked in the "Add to home" dialog.
+ */
+ public void onClick(DialogInterface dialog, int which) {
+ Resources res = getResources();
+ cleanup();
+
+ switch (which) {
+ case AddAdapter.ITEM_SHORTCUT: {
+ // Insert extra item to handle picking application
+ pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut);
+ break;
+ }
+
+ case AddAdapter.ITEM_APPWIDGET: {
+ int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
+
+ Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
+ pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
+ // add the search widget
+ ArrayList customInfo =
+ new ArrayList();
+ AppWidgetProviderInfo info = new AppWidgetProviderInfo();
+ info.provider = new ComponentName(getPackageName(), "XXX.YYY");
+ info.label = getString(R.string.group_search);
+ info.icon = R.drawable.ic_search_widget;
+ customInfo.add(info);
+ pickIntent.putParcelableArrayListExtra(
+ AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
+ ArrayList customExtras = new ArrayList();
+ Bundle b = new Bundle();
+ b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
+ customExtras.add(b);
+ pickIntent.putParcelableArrayListExtra(
+ AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
+ // start the pick activity
+ startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
+ break;
+ }
+
+ case AddAdapter.ITEM_LIVE_FOLDER: {
+ // Insert extra item to handle inserting folder
+ Bundle bundle = new Bundle();
+
+ ArrayList shortcutNames = new ArrayList();
+ shortcutNames.add(res.getString(R.string.group_folder));
+ bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
+
+ ArrayList shortcutIcons =
+ new ArrayList();
+ shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
+ R.drawable.ic_launcher_folder));
+ bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
+
+ Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
+ pickIntent.putExtra(Intent.EXTRA_INTENT,
+ new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
+ pickIntent.putExtra(Intent.EXTRA_TITLE,
+ getText(R.string.title_select_live_folder));
+ pickIntent.putExtras(bundle);
+
+ startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
+ break;
+ }
+
+ case AddAdapter.ITEM_WALLPAPER: {
+ startWallpaper();
+ break;
+ }
+ }
+ }
+
+ public void onShow(DialogInterface dialog) {
+ }
+ }
+
+ /**
+ * Receives notifications when applications are added/removed.
+ */
+ private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ closeSystemDialogs();
+ String reason = intent.getStringExtra("reason");
+ if (!"homekey".equals(reason)) {
+ boolean animate = true;
+ if (mPaused || "lock".equals(reason)) {
+ animate = false;
+ }
+ closeAllApps(animate);
+ }
+ }
+ }
+
+ /**
+ * Receives notifications whenever the appwidgets are reset.
+ */
+ private class AppWidgetResetObserver extends ContentObserver {
+ public AppWidgetResetObserver() {
+ super(new Handler());
+ }
+
+ @Override
+ public void onChange(boolean selfChange) {
+ onAppWidgetReset();
+ }
+ }
+
+ /**
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public int getCurrentWorkspaceScreen() {
+ return mWorkspace.getCurrentScreen();
+ }
+
+ /**
+ * Refreshes the shortcuts shown on the workspace.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void startBinding() {
+ final Workspace workspace = mWorkspace;
+ int count = workspace.getChildCount();
+ for (int i = 0; i < count; i++) {
+ // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
+ ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
+ }
+
+ if (DEBUG_USER_INTERFACE) {
+ android.widget.Button finishButton = new android.widget.Button(this);
+ finishButton.setText("Finish");
+ workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
+
+ finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
+ public void onClick(View v) {
+ finish();
+ }
+ });
+ }
+ }
+
+ /**
+ * Bind the items start-end from the list.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindItems(ArrayList shortcuts, int start, int end) {
+
+ final Workspace workspace = mWorkspace;
+
+ for (int i=start; i folders) {
+ mFolders.clear();
+ mFolders.putAll(folders);
+ }
+
+ /**
+ * Add the views for a widget to the workspace.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindAppWidget(LauncherAppWidgetInfo item) {
+ final Workspace workspace = mWorkspace;
+
+ final int appWidgetId = item.appWidgetId;
+ final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
+ item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
+
+ item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
+ item.hostView.setTag(item);
+
+ workspace.addInScreen(item.hostView, item.screen, item.cellX,
+ item.cellY, item.spanX, item.spanY, false);
+
+ workspace.requestLayout();
+
+ mDesktopItems.add(item);
+ }
+
+ /**
+ * Callback saying that there aren't any more items to bind.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void finishBindingItems() {
+ if (mSavedState != null) {
+ if (!mWorkspace.hasFocus()) {
+ mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
+ }
+
+ final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
+ if (userFolders != null) {
+ for (long folderId : userFolders) {
+ final FolderInfo info = mFolders.get(folderId);
+ if (info != null) {
+ openFolder(info);
+ }
+ }
+ final Folder openFolder = mWorkspace.getOpenFolder();
+ if (openFolder != null) {
+ openFolder.requestFocus();
+ }
+ }
+
+ mSavedState = null;
+ }
+
+ if (mSavedInstanceState != null) {
+ super.onRestoreInstanceState(mSavedInstanceState);
+ mSavedInstanceState = null;
+ }
+
+ mWorkspaceLoading = false;
+ }
+
+ /**
+ * Add the icons for all apps.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindAllApplications(ArrayList apps) {
+ mAllAppsGrid.setApps(apps);
+ }
+
+ /**
+ * A package was installed.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindPackageAdded(ArrayList apps) {
+ removeDialog(DIALOG_CREATE_SHORTCUT);
+ mAllAppsGrid.addApps(apps);
+ }
+
+ /**
+ * A package was updated.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindPackageUpdated(String packageName, ArrayList apps) {
+ removeDialog(DIALOG_CREATE_SHORTCUT);
+ mWorkspace.updateShortcutsForPackage(packageName);
+ mAllAppsGrid.updateApps(packageName, apps);
+ }
+
+ /**
+ * A package was uninstalled.
+ *
+ * Implementation of the method from LauncherModel.Callbacks.
+ */
+ public void bindPackageRemoved(String packageName, ArrayList apps) {
+ removeDialog(DIALOG_CREATE_SHORTCUT);
+ mWorkspace.removeShortcutsForPackage(packageName);
+ mAllAppsGrid.removeApps(apps);
+ }
+
+ /**
+ * Prints out out state for debugging.
+ */
+ public void dumpState() {
+ Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
+ Log.d(TAG, "mSavedState=" + mSavedState);
+ Log.d(TAG, "mIsNewIntent=" + mIsNewIntent);
+ Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
+ Log.d(TAG, "mRestoring=" + mRestoring);
+ Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
+ Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
+ Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size());
+ Log.d(TAG, "mFolders.size=" + mFolders.size());
+ mModel.dumpState();
+ mAllAppsGrid.dumpState();
+ Log.d(TAG, "END launcher2 dump state");
+ }
+}
diff --git a/src/com/android/launcher2/LauncherAppWidgetHost.java b/src/com/android/launcher2/LauncherAppWidgetHost.java
new file mode 100644
index 0000000000..a5761ecc3a
--- /dev/null
+++ b/src/com/android/launcher2/LauncherAppWidgetHost.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.appwidget.AppWidgetHost;
+import android.appwidget.AppWidgetHostView;
+import android.appwidget.AppWidgetProviderInfo;
+import android.content.Context;
+
+/**
+ * Specific {@link AppWidgetHost} that creates our {@link LauncherAppWidgetHostView}
+ * which correctly captures all long-press events. This ensures that users can
+ * always pick up and move widgets.
+ */
+public class LauncherAppWidgetHost extends AppWidgetHost {
+ public LauncherAppWidgetHost(Context context, int hostId) {
+ super(context, hostId);
+ }
+
+ @Override
+ protected AppWidgetHostView onCreateView(Context context, int appWidgetId,
+ AppWidgetProviderInfo appWidget) {
+ return new LauncherAppWidgetHostView(context);
+ }
+}
diff --git a/src/com/android/launcher2/LauncherAppWidgetHostView.java b/src/com/android/launcher2/LauncherAppWidgetHostView.java
new file mode 100644
index 0000000000..d8fe49918d
--- /dev/null
+++ b/src/com/android/launcher2/LauncherAppWidgetHostView.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.appwidget.AppWidgetHostView;
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewConfiguration;
+
+/**
+ * {@inheritDoc}
+ */
+public class LauncherAppWidgetHostView extends AppWidgetHostView {
+ private boolean mHasPerformedLongPress;
+
+ private CheckForLongPress mPendingCheckForLongPress;
+
+ private LayoutInflater mInflater;
+
+ public LauncherAppWidgetHostView(Context context) {
+ super(context);
+ mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ }
+
+ @Override
+ protected View getErrorView() {
+ return mInflater.inflate(R.layout.appwidget_error, this, false);
+ }
+
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ // Consume any touch events for ourselves after longpress is triggered
+ if (mHasPerformedLongPress) {
+ mHasPerformedLongPress = false;
+ return true;
+ }
+
+ // Watch for longpress events at this level to make sure
+ // users can always pick up this widget
+ switch (ev.getAction()) {
+ case MotionEvent.ACTION_DOWN: {
+ postCheckForLongClick();
+ break;
+ }
+
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_CANCEL:
+ mHasPerformedLongPress = false;
+ if (mPendingCheckForLongPress != null) {
+ removeCallbacks(mPendingCheckForLongPress);
+ }
+ break;
+ }
+
+ // Otherwise continue letting touch events fall through to children
+ return false;
+ }
+
+ class CheckForLongPress implements Runnable {
+ private int mOriginalWindowAttachCount;
+
+ public void run() {
+ if ((mParent != null) && hasWindowFocus()
+ && mOriginalWindowAttachCount == getWindowAttachCount()
+ && !mHasPerformedLongPress) {
+ if (performLongClick()) {
+ mHasPerformedLongPress = true;
+ }
+ }
+ }
+
+ public void rememberWindowAttachCount() {
+ mOriginalWindowAttachCount = getWindowAttachCount();
+ }
+ }
+
+ private void postCheckForLongClick() {
+ mHasPerformedLongPress = false;
+
+ if (mPendingCheckForLongPress == null) {
+ mPendingCheckForLongPress = new CheckForLongPress();
+ }
+ mPendingCheckForLongPress.rememberWindowAttachCount();
+ postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());
+ }
+
+ @Override
+ public void cancelLongPress() {
+ super.cancelLongPress();
+
+ mHasPerformedLongPress = false;
+ if (mPendingCheckForLongPress != null) {
+ removeCallbacks(mPendingCheckForLongPress);
+ }
+ }
+}
diff --git a/src/com/android/launcher2/LauncherAppWidgetInfo.java b/src/com/android/launcher2/LauncherAppWidgetInfo.java
new file mode 100644
index 0000000000..25db72bed3
--- /dev/null
+++ b/src/com/android/launcher2/LauncherAppWidgetInfo.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.appwidget.AppWidgetHostView;
+import android.content.ContentValues;
+
+/**
+ * Represents a widget, which just contains an identifier.
+ */
+class LauncherAppWidgetInfo extends ItemInfo {
+
+ /**
+ * Identifier for this widget when talking with {@link AppWidgetManager} for updates.
+ */
+ int appWidgetId;
+
+ /**
+ * View that holds this widget after it's been created. This view isn't created
+ * until Launcher knows it's needed.
+ */
+ AppWidgetHostView hostView = null;
+
+ LauncherAppWidgetInfo(int appWidgetId) {
+ itemType = LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
+ this.appWidgetId = appWidgetId;
+ }
+
+ @Override
+ void onAddToDatabase(ContentValues values) {
+ super.onAddToDatabase(values);
+ values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
+ }
+
+ @Override
+ public String toString() {
+ return Integer.toString(appWidgetId);
+ }
+
+
+ @Override
+ void unbind() {
+ super.unbind();
+ hostView = null;
+ }
+}
diff --git a/src/com/android/launcher2/LauncherApplication.java b/src/com/android/launcher2/LauncherApplication.java
new file mode 100644
index 0000000000..9b63524332
--- /dev/null
+++ b/src/com/android/launcher2/LauncherApplication.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.app.Application;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.ContentObserver;
+import android.os.Handler;
+import dalvik.system.VMRuntime;
+
+public class LauncherApplication extends Application {
+ public final LauncherModel mModel;
+
+ public LauncherApplication() {
+ mModel = new LauncherModel(this);
+ }
+
+ @Override
+ public void onCreate() {
+ VMRuntime.getRuntime().setMinimumHeapSize(4 * 1024 * 1024);
+
+ super.onCreate();
+
+ // Register intent receivers
+ IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
+ filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+ filter.addDataScheme("package");
+ registerReceiver(mModel, filter);
+
+ // Register for changes to the favorites
+ ContentResolver resolver = getContentResolver();
+ resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true,
+ mFavoritesObserver);
+ }
+
+ /**
+ * There's no guarantee that this function is ever called.
+ */
+ @Override
+ public void onTerminate() {
+ super.onTerminate();
+
+ unregisterReceiver(mModel);
+
+ ContentResolver resolver = getContentResolver();
+ resolver.unregisterContentObserver(mFavoritesObserver);
+ }
+
+ /**
+ * Receives notifications whenever the user favorites have changed.
+ */
+ private final ContentObserver mFavoritesObserver = new ContentObserver(new Handler()) {
+ @Override
+ public void onChange(boolean selfChange) {
+ // TODO: lockAllApps();
+ mModel.setWorkspaceDirty();
+ mModel.startLoader(LauncherApplication.this, false);
+ }
+ };
+
+ LauncherModel setLauncher(Launcher launcher) {
+ mModel.initialize(launcher);
+ return mModel;
+ }
+}
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
new file mode 100644
index 0000000000..97fa554c2f
--- /dev/null
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -0,0 +1,1239 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Intent;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.res.Resources;
+import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.util.Log;
+import android.os.Process;
+import android.os.SystemClock;
+
+import java.lang.ref.WeakReference;
+import java.net.URISyntaxException;
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * Maintains in-memory state of the Launcher. It is expected that there should be only one
+ * LauncherModel object held in a static. Also provide APIs for updating the database state
+ * for the Launcher.
+ */
+public class LauncherModel extends BroadcastReceiver {
+ static final boolean DEBUG_LOADERS = false;
+ static final String TAG = "Launcher.Model";
+
+ private final LauncherApplication mApp;
+ private final Object mLock = new Object();
+ private DeferredHandler mHandler = new DeferredHandler();
+ private Loader mLoader = new Loader();
+
+ private boolean mBeforeFirstLoad = true;
+ private WeakReference mCallbacks;
+
+ private AllAppsList mAllAppsList = new AllAppsList();
+
+ public interface Callbacks {
+ public int getCurrentWorkspaceScreen();
+ public void startBinding();
+ public void bindItems(ArrayList shortcuts, int start, int end);
+ public void bindFolders(HashMap folders);
+ public void finishBindingItems();
+ public void bindAppWidget(LauncherAppWidgetInfo info);
+ public void bindAllApplications(ArrayList apps);
+ public void bindPackageAdded(ArrayList apps);
+ public void bindPackageUpdated(String packageName, ArrayList apps);
+ public void bindPackageRemoved(String packageName, ArrayList apps);
+ }
+
+ LauncherModel(LauncherApplication app) {
+ mApp = app;
+ }
+
+ /**
+ * Adds an item to the DB if it was not created previously, or move it to a new
+ *
+ */
+ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
+ int screen, int cellX, int cellY) {
+ if (item.container == ItemInfo.NO_ID) {
+ // From all apps
+ addItemToDatabase(context, item, container, screen, cellX, cellY, false);
+ } else {
+ // From somewhere else
+ moveItemInDatabase(context, item, container, screen, cellX, cellY);
+ }
+ }
+
+ /**
+ * Move an item in the DB to a new
+ */
+ static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
+ int cellX, int cellY) {
+ item.container = container;
+ item.screen = screen;
+ item.cellX = cellX;
+ item.cellY = cellY;
+
+ final ContentValues values = new ContentValues();
+ final ContentResolver cr = context.getContentResolver();
+
+ values.put(LauncherSettings.Favorites.CONTAINER, item.container);
+ values.put(LauncherSettings.Favorites.CELLX, item.cellX);
+ values.put(LauncherSettings.Favorites.CELLY, item.cellY);
+ values.put(LauncherSettings.Favorites.SCREEN, item.screen);
+
+ cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
+ }
+
+ /**
+ * Returns true if the shortcuts already exists in the database.
+ * we identify a shortcut by its title and intent.
+ */
+ static boolean shortcutExists(Context context, String title, Intent intent) {
+ final ContentResolver cr = context.getContentResolver();
+ Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[] { "title", "intent" }, "title=? and intent=?",
+ new String[] { title, intent.toUri(0) }, null);
+ boolean result = false;
+ try {
+ result = c.moveToFirst();
+ } finally {
+ c.close();
+ }
+ return result;
+ }
+
+ /**
+ * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
+ */
+ FolderInfo getFolderById(Context context, HashMap folderList, long id) {
+ final ContentResolver cr = context.getContentResolver();
+ Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
+ "_id=? and (itemType=? or itemType=?)",
+ new String[] { String.valueOf(id),
+ String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
+ String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
+
+ try {
+ if (c.moveToFirst()) {
+ final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
+ final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
+ final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
+ final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
+ final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
+ final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
+
+ FolderInfo folderInfo = null;
+ switch (c.getInt(itemTypeIndex)) {
+ case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
+ folderInfo = findOrMakeUserFolder(folderList, id);
+ break;
+ case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
+ folderInfo = findOrMakeLiveFolder(folderList, id);
+ break;
+ }
+
+ folderInfo.title = c.getString(titleIndex);
+ folderInfo.id = id;
+ folderInfo.container = c.getInt(containerIndex);
+ folderInfo.screen = c.getInt(screenIndex);
+ folderInfo.cellX = c.getInt(cellXIndex);
+ folderInfo.cellY = c.getInt(cellYIndex);
+
+ return folderInfo;
+ }
+ } finally {
+ c.close();
+ }
+
+ return null;
+ }
+
+ /**
+ * Add an item to the database in a specified container. Sets the container, screen, cellX and
+ * cellY fields of the item. Also assigns an ID to the item.
+ */
+ static void addItemToDatabase(Context context, ItemInfo item, long container,
+ int screen, int cellX, int cellY, boolean notify) {
+ item.container = container;
+ item.screen = screen;
+ item.cellX = cellX;
+ item.cellY = cellY;
+
+ final ContentValues values = new ContentValues();
+ final ContentResolver cr = context.getContentResolver();
+
+ item.onAddToDatabase(values);
+
+ Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
+ LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
+
+ if (result != null) {
+ item.id = Integer.parseInt(result.getPathSegments().get(1));
+ }
+ }
+
+ /**
+ * Update an item to the database in a specified container.
+ */
+ static void updateItemInDatabase(Context context, ItemInfo item) {
+ final ContentValues values = new ContentValues();
+ final ContentResolver cr = context.getContentResolver();
+
+ item.onAddToDatabase(values);
+
+ cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
+ }
+
+ /**
+ * Removes the specified item from the database
+ * @param context
+ * @param item
+ */
+ static void deleteItemFromDatabase(Context context, ItemInfo item) {
+ final ContentResolver cr = context.getContentResolver();
+
+ cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
+ }
+
+ /**
+ * Remove the contents of the specified folder from the database
+ */
+ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
+ final ContentResolver cr = context.getContentResolver();
+
+ cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
+ cr.delete(LauncherSettings.Favorites.CONTENT_URI,
+ LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
+ }
+
+ /**
+ * Set this as the current Launcher activity object for the loader.
+ */
+ public void initialize(Callbacks callbacks) {
+ synchronized (mLock) {
+ mCallbacks = new WeakReference(callbacks);
+ }
+ }
+
+ public void startLoader(Context context, boolean isLaunching) {
+ mLoader.startLoader(context, isLaunching);
+ }
+
+ public void stopLoader() {
+ mLoader.stopLoader();
+ }
+
+ /**
+ * We pick up most of the changes to all apps.
+ */
+ public void setAllAppsDirty() {
+ mLoader.setAllAppsDirty();
+ }
+
+ public void setWorkspaceDirty() {
+ mLoader.setWorkspaceDirty();
+ }
+
+ /**
+ * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
+ * ACTION_PACKAGE_CHANGED.
+ */
+ public void onReceive(Context context, Intent intent) {
+ // Use the app as the context.
+ context = mApp;
+
+ final String packageName = intent.getData().getSchemeSpecificPart();
+
+ ArrayList added = null;
+ ArrayList removed = null;
+ ArrayList modified = null;
+
+ synchronized (mLock) {
+ if (mBeforeFirstLoad) {
+ // If we haven't even loaded yet, don't bother, since we'll just pick
+ // up the changes.
+ return;
+ }
+
+ final String action = intent.getAction();
+ final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
+
+ if (packageName == null || packageName.length() == 0) {
+ // they sent us a bad intent
+ return;
+ }
+
+ if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
+ mAllAppsList.updatePackage(context, packageName);
+ } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
+ if (!replacing) {
+ mAllAppsList.removePackage(packageName);
+ }
+ // else, we are replacing the package, so a PACKAGE_ADDED will be sent
+ // later, we will update the package at this time
+ } else {
+ if (!replacing) {
+ mAllAppsList.addPackage(context, packageName);
+ } else {
+ mAllAppsList.updatePackage(context, packageName);
+ }
+ }
+
+ if (mAllAppsList.added.size() > 0) {
+ added = mAllAppsList.added;
+ mAllAppsList.added = new ArrayList();
+ }
+ if (mAllAppsList.removed.size() > 0) {
+ removed = mAllAppsList.removed;
+ mAllAppsList.removed = new ArrayList();
+ for (ApplicationInfo info: removed) {
+ AppInfoCache.remove(info.intent.getComponent());
+ }
+ }
+ if (mAllAppsList.modified.size() > 0) {
+ modified = mAllAppsList.modified;
+ mAllAppsList.modified = new ArrayList();
+ }
+
+ final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
+ if (callbacks == null) {
+ Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
+ return;
+ }
+
+ if (added != null) {
+ final ArrayList addedFinal = added;
+ mHandler.post(new Runnable() {
+ public void run() {
+ callbacks.bindPackageAdded(addedFinal);
+ }
+ });
+ }
+ if (modified != null) {
+ final ArrayList modifiedFinal = modified;
+ mHandler.post(new Runnable() {
+ public void run() {
+ callbacks.bindPackageUpdated(packageName, modifiedFinal);
+ }
+ });
+ }
+ if (removed != null) {
+ final ArrayList removedFinal = removed;
+ mHandler.post(new Runnable() {
+ public void run() {
+ callbacks.bindPackageRemoved(packageName, removedFinal);
+ }
+ });
+ }
+ }
+ }
+
+ public class Loader {
+ private static final int ITEMS_CHUNK = 6;
+
+ private LoaderThread mLoaderThread;
+
+ private int mLastWorkspaceSeq = 0;
+ private int mWorkspaceSeq = 1;
+
+ private int mLastAllAppsSeq = 0;
+ private int mAllAppsSeq = 1;
+
+ final ArrayList mItems = new ArrayList();
+ final ArrayList mAppWidgets = new ArrayList();
+ final HashMap mFolders = new HashMap();
+
+ /**
+ * Call this from the ui thread so the handler is initialized on the correct thread.
+ */
+ public Loader() {
+ }
+
+ public void startLoader(Context context, boolean isLaunching) {
+ synchronized (mLock) {
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "startLoader isLaunching=" + isLaunching);
+ }
+ // Don't bother to start the thread if we know it's not going to do anything
+ if (mCallbacks.get() != null) {
+ LoaderThread oldThread = mLoaderThread;
+ if (oldThread != null) {
+ if (oldThread.isLaunching()) {
+ // don't downgrade isLaunching if we're already running
+ isLaunching = true;
+ }
+ oldThread.stopLocked();
+ }
+ mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
+ mLoaderThread.start();
+ }
+ }
+ }
+
+ public void stopLoader() {
+ synchronized (mLock) {
+ if (mLoaderThread != null) {
+ mLoaderThread.stopLocked();
+ }
+ }
+ }
+
+ public void setWorkspaceDirty() {
+ synchronized (mLock) {
+ mWorkspaceSeq++;
+ }
+ }
+
+ public void setAllAppsDirty() {
+ synchronized (mLock) {
+ mAllAppsSeq++;
+ }
+ }
+
+ /**
+ * Runnable for the thread that loads the contents of the launcher:
+ * - workspace icons
+ * - widgets
+ * - all apps icons
+ */
+ private class LoaderThread extends Thread {
+ private Context mContext;
+ private Thread mWaitThread;
+ private boolean mIsLaunching;
+ private boolean mStopped;
+ private boolean mWorkspaceDoneBinding;
+
+ LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
+ mContext = context;
+ mWaitThread = waitThread;
+ mIsLaunching = isLaunching;
+ }
+
+ boolean isLaunching() {
+ return mIsLaunching;
+ }
+
+ /**
+ * If another LoaderThread was supplied, we need to wait for that to finish before
+ * we start our processing. This keeps the ordering of the setting and clearing
+ * of the dirty flags correct by making sure we don't start processing stuff until
+ * they've had a chance to re-set them. We do this waiting the worker thread, not
+ * the ui thread to avoid ANRs.
+ */
+ private void waitForOtherThread() {
+ if (mWaitThread != null) {
+ boolean done = false;
+ while (!done) {
+ try {
+ mWaitThread.join();
+ done = true;
+ } catch (InterruptedException ex) {
+ // Ignore
+ }
+ }
+ mWaitThread = null;
+ }
+ }
+
+ public void run() {
+ waitForOtherThread();
+
+ // Elevate priority when Home launches for the first time to avoid
+ // starving at boot time. Staring at a blank home is not cool.
+ synchronized (mLock) {
+ android.os.Process.setThreadPriority(mIsLaunching
+ ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
+ }
+
+ // Load the workspace only if it's dirty.
+ int workspaceSeq;
+ boolean workspaceDirty;
+ synchronized (mLock) {
+ workspaceSeq = mWorkspaceSeq;
+ workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
+ }
+ if (workspaceDirty) {
+ loadWorkspace();
+ }
+ synchronized (mLock) {
+ // If we're not stopped, and nobody has incremented mWorkspaceSeq.
+ if (mStopped) {
+ return;
+ }
+ if (workspaceSeq == mWorkspaceSeq) {
+ mLastWorkspaceSeq = mWorkspaceSeq;
+ }
+ }
+
+ // Bind the workspace
+ bindWorkspace();
+
+ // Wait until the either we're stopped or the other threads are done.
+ // This way we don't start loading all apps until the workspace has settled
+ // down.
+ synchronized (LoaderThread.this) {
+ mHandler.postIdle(new Runnable() {
+ public void run() {
+ synchronized (LoaderThread.this) {
+ mWorkspaceDoneBinding = true;
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "done with workspace");
+ }
+ LoaderThread.this.notify();
+ }
+ }
+ });
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "waiting to be done with workspace");
+ }
+ while (!mStopped && !mWorkspaceDoneBinding) {
+ try {
+ this.wait();
+ } catch (InterruptedException ex) {
+ // Ignore
+ }
+ }
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "done waiting to be done with workspace");
+ }
+ }
+
+ // Load all apps if they're dirty
+ int allAppsSeq;
+ boolean allAppsDirty;
+ synchronized (mLock) {
+ allAppsSeq = mAllAppsSeq;
+ allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
+ }
+ }
+ if (allAppsDirty) {
+ loadAllApps();
+ }
+ synchronized (mLock) {
+ // If we're not stopped, and nobody has incremented mAllAppsSeq.
+ if (mStopped) {
+ return;
+ }
+ if (allAppsSeq == mAllAppsSeq) {
+ mLastAllAppsSeq = mAllAppsSeq;
+ }
+ }
+
+ // Bind all apps
+ if (allAppsDirty) {
+ bindAllApps();
+ }
+
+ // Clear out this reference, otherwise we end up holding it until all of the
+ // callback runnables are done.
+ mContext = null;
+
+ synchronized (mLock) {
+ // Setting the reference is atomic, but we can't do it inside the other critical
+ // sections.
+ mLoaderThread = null;
+ }
+ }
+
+ public void stopLocked() {
+ synchronized (LoaderThread.this) {
+ mStopped = true;
+ this.notify();
+ }
+ }
+
+ /**
+ * Gets the callbacks object. If we've been stopped, or if the launcher object
+ * has somehow been garbage collected, return null instead.
+ */
+ Callbacks tryGetCallbacks() {
+ synchronized (mLock) {
+ if (mStopped) {
+ return null;
+ }
+
+ final Callbacks callbacks = mCallbacks.get();
+ if (callbacks == null) {
+ Log.w(TAG, "no mCallbacks");
+ return null;
+ }
+
+ return callbacks;
+ }
+ }
+
+ private void loadWorkspace() {
+ long t = SystemClock.uptimeMillis();
+
+ final Context context = mContext;
+ final ContentResolver contentResolver = context.getContentResolver();
+ final PackageManager manager = context.getPackageManager();
+
+ /* TODO
+ if (mLocaleChanged) {
+ updateShortcutLabels(contentResolver, manager);
+ }
+ */
+
+ mItems.clear();
+ mAppWidgets.clear();
+ mFolders.clear();
+
+ final Cursor c = contentResolver.query(
+ LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
+
+ try {
+ final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+ final int intentIndex = c.getColumnIndexOrThrow
+ (LauncherSettings.Favorites.INTENT);
+ final int titleIndex = c.getColumnIndexOrThrow
+ (LauncherSettings.Favorites.TITLE);
+ final int iconTypeIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.ICON_TYPE);
+ final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
+ final int iconPackageIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.ICON_PACKAGE);
+ final int iconResourceIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.ICON_RESOURCE);
+ final int containerIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.CONTAINER);
+ final int itemTypeIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.ITEM_TYPE);
+ final int appWidgetIdIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.APPWIDGET_ID);
+ final int screenIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.SCREEN);
+ final int cellXIndex = c.getColumnIndexOrThrow
+ (LauncherSettings.Favorites.CELLX);
+ final int cellYIndex = c.getColumnIndexOrThrow
+ (LauncherSettings.Favorites.CELLY);
+ final int spanXIndex = c.getColumnIndexOrThrow
+ (LauncherSettings.Favorites.SPANX);
+ final int spanYIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.SPANY);
+ final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
+ final int displayModeIndex = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.DISPLAY_MODE);
+
+ ApplicationInfo info;
+ String intentDescription;
+ Widget widgetInfo;
+ LauncherAppWidgetInfo appWidgetInfo;
+ int container;
+ long id;
+ Intent intent;
+
+ while (!mStopped && c.moveToNext()) {
+ try {
+ int itemType = c.getInt(itemTypeIndex);
+
+ switch (itemType) {
+ case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
+ case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
+ intentDescription = c.getString(intentIndex);
+ try {
+ intent = Intent.parseUri(intentDescription, 0);
+ } catch (URISyntaxException e) {
+ continue;
+ }
+
+ if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
+ info = getApplicationInfo(manager, intent, context);
+ } else {
+ info = getApplicationInfoShortcut(c, context, iconTypeIndex,
+ iconPackageIndex, iconResourceIndex, iconIndex);
+ }
+
+ if (info == null) {
+ info = new ApplicationInfo();
+ info.icon = manager.getDefaultActivityIcon();
+ }
+
+ if (info != null) {
+ if (itemType
+ != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
+ info.title = c.getString(titleIndex);
+ }
+ info.intent = intent;
+
+ info.id = c.getLong(idIndex);
+ container = c.getInt(containerIndex);
+ info.container = container;
+ info.screen = c.getInt(screenIndex);
+ info.cellX = c.getInt(cellXIndex);
+ info.cellY = c.getInt(cellYIndex);
+
+ switch (container) {
+ case LauncherSettings.Favorites.CONTAINER_DESKTOP:
+ mItems.add(info);
+ break;
+ default:
+ // Item is in a user folder
+ UserFolderInfo folderInfo =
+ findOrMakeUserFolder(mFolders, container);
+ folderInfo.add(info);
+ break;
+ }
+ }
+ break;
+
+ case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
+ id = c.getLong(idIndex);
+ UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
+
+ folderInfo.title = c.getString(titleIndex);
+
+ folderInfo.id = id;
+ container = c.getInt(containerIndex);
+ folderInfo.container = container;
+ folderInfo.screen = c.getInt(screenIndex);
+ folderInfo.cellX = c.getInt(cellXIndex);
+ folderInfo.cellY = c.getInt(cellYIndex);
+
+ switch (container) {
+ case LauncherSettings.Favorites.CONTAINER_DESKTOP:
+ mItems.add(folderInfo);
+ break;
+ }
+
+ mFolders.put(folderInfo.id, folderInfo);
+ break;
+
+ case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
+
+ id = c.getLong(idIndex);
+ LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
+
+ intentDescription = c.getString(intentIndex);
+ intent = null;
+ if (intentDescription != null) {
+ try {
+ intent = Intent.parseUri(intentDescription, 0);
+ } catch (URISyntaxException e) {
+ // Ignore, a live folder might not have a base intent
+ }
+ }
+
+ liveFolderInfo.title = c.getString(titleIndex);
+ liveFolderInfo.id = id;
+ container = c.getInt(containerIndex);
+ liveFolderInfo.container = container;
+ liveFolderInfo.screen = c.getInt(screenIndex);
+ liveFolderInfo.cellX = c.getInt(cellXIndex);
+ liveFolderInfo.cellY = c.getInt(cellYIndex);
+ liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
+ liveFolderInfo.baseIntent = intent;
+ liveFolderInfo.displayMode = c.getInt(displayModeIndex);
+
+ loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
+ iconResourceIndex, liveFolderInfo);
+
+ switch (container) {
+ case LauncherSettings.Favorites.CONTAINER_DESKTOP:
+ mItems.add(liveFolderInfo);
+ break;
+ }
+ mFolders.put(liveFolderInfo.id, liveFolderInfo);
+ break;
+
+ case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
+ widgetInfo = Widget.makeSearch();
+
+ container = c.getInt(containerIndex);
+ if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
+ Log.e(TAG, "Widget found where container "
+ + "!= CONTAINER_DESKTOP ignoring!");
+ continue;
+ }
+
+ widgetInfo.id = c.getLong(idIndex);
+ widgetInfo.screen = c.getInt(screenIndex);
+ widgetInfo.container = container;
+ widgetInfo.cellX = c.getInt(cellXIndex);
+ widgetInfo.cellY = c.getInt(cellYIndex);
+
+ mItems.add(widgetInfo);
+ break;
+
+ case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
+ // Read all Launcher-specific widget details
+ int appWidgetId = c.getInt(appWidgetIdIndex);
+ appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
+ appWidgetInfo.id = c.getLong(idIndex);
+ appWidgetInfo.screen = c.getInt(screenIndex);
+ appWidgetInfo.cellX = c.getInt(cellXIndex);
+ appWidgetInfo.cellY = c.getInt(cellYIndex);
+ appWidgetInfo.spanX = c.getInt(spanXIndex);
+ appWidgetInfo.spanY = c.getInt(spanYIndex);
+
+ container = c.getInt(containerIndex);
+ if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
+ Log.e(TAG, "Widget found where container "
+ + "!= CONTAINER_DESKTOP -- ignoring!");
+ continue;
+ }
+ appWidgetInfo.container = c.getInt(containerIndex);
+
+ mAppWidgets.add(appWidgetInfo);
+ break;
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "Desktop items loading interrupted:", e);
+ }
+ }
+ } finally {
+ c.close();
+ }
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
+ }
+ }
+
+ /**
+ * Read everything out of our database.
+ */
+ private void bindWorkspace() {
+ final long t = SystemClock.uptimeMillis();
+
+ // Don't use these two variables in any of the callback runnables.
+ // Otherwise we hold a reference to them.
+ Callbacks callbacks = mCallbacks.get();
+ if (callbacks == null) {
+ // This launcher has exited and nobody bothered to tell us. Just bail.
+ Log.w(TAG, "LoaderThread running with no launcher");
+ return;
+ }
+
+ int N;
+ // Tell the workspace that we're about to start firing items at it
+ mHandler.post(new Runnable() {
+ public void run() {
+ Callbacks callbacks = tryGetCallbacks();
+ if (callbacks != null) {
+ callbacks.startBinding();
+ }
+ }
+ });
+ // Add the items to the workspace.
+ N = mItems.size();
+ for (int i=0; i apps = packageManager.queryIntentActivities(mainIntent, 0);
+
+ synchronized (mLock) {
+ mBeforeFirstLoad = false;
+
+ mAllAppsList.clear();
+ if (apps != null) {
+ long t = SystemClock.uptimeMillis();
+
+ int N = apps.size();
+ Utilities.BubbleText bubble = new Utilities.BubbleText(context);
+ for (int i=0; i results
+ = (ArrayList)mAllAppsList.data.clone();
+ // We're adding this now, so clear out this so we don't re-send them.
+ mAllAppsList.added = new ArrayList();
+ mHandler.post(new Runnable() {
+ public void run() {
+ final long t = SystemClock.uptimeMillis();
+ final int count = results.size();
+
+ Callbacks callbacks = tryGetCallbacks();
+ if (callbacks != null) {
+ callbacks.bindAllApplications(results);
+ }
+
+ if (DEBUG_LOADERS) {
+ Log.d(TAG, "bound app " + count + " icons in "
+ + (SystemClock.uptimeMillis()-t) + "ms");
+ }
+ }
+ });
+ }
+ }
+
+ public void dumpState() {
+ Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
+ Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
+ Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
+ Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
+ Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
+ }
+ }
+
+ public void dumpState() {
+ Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
+ Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
+ Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
+ Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
+ Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
+ if (mLoaderThread != null) {
+ mLoaderThread.dumpState();
+ } else {
+ Log.d(TAG, "mLoader.mLoaderThread=null");
+ }
+ }
+ }
+
+ /**
+ * Make an ApplicationInfo object for an application.
+ */
+ private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
+ Context context) {
+ final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
+
+ if (resolveInfo == null) {
+ return null;
+ }
+
+ final ApplicationInfo info = new ApplicationInfo();
+ final ActivityInfo activityInfo = resolveInfo.activityInfo;
+ info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
+ if (info.title == null || info.title.length() == 0) {
+ info.title = activityInfo.loadLabel(manager);
+ }
+ if (info.title == null) {
+ info.title = "";
+ }
+ info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
+ return info;
+ }
+
+ /**
+ * Make an ApplicationInfo object for a sortcut
+ */
+ private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
+ int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
+
+ final ApplicationInfo info = new ApplicationInfo();
+ info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
+
+ int iconType = c.getInt(iconTypeIndex);
+ switch (iconType) {
+ case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
+ String packageName = c.getString(iconPackageIndex);
+ String resourceName = c.getString(iconResourceIndex);
+ PackageManager packageManager = context.getPackageManager();
+ try {
+ Resources resources = packageManager.getResourcesForApplication(packageName);
+ final int id = resources.getIdentifier(resourceName, null, null);
+ info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
+ } catch (Exception e) {
+ info.icon = packageManager.getDefaultActivityIcon();
+ }
+ info.iconResource = new Intent.ShortcutIconResource();
+ info.iconResource.packageName = packageName;
+ info.iconResource.resourceName = resourceName;
+ info.customIcon = false;
+ break;
+ case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
+ byte[] data = c.getBlob(iconIndex);
+ try {
+ Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
+ info.icon = new FastBitmapDrawable(
+ Utilities.createBitmapThumbnail(bitmap, context));
+ } catch (Exception e) {
+ packageManager = context.getPackageManager();
+ info.icon = packageManager.getDefaultActivityIcon();
+ }
+ info.filtered = true;
+ info.customIcon = true;
+ break;
+ default:
+ info.icon = context.getPackageManager().getDefaultActivityIcon();
+ info.customIcon = false;
+ break;
+ }
+ return info;
+ }
+
+ private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
+ int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
+
+ int iconType = c.getInt(iconTypeIndex);
+ switch (iconType) {
+ case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
+ String packageName = c.getString(iconPackageIndex);
+ String resourceName = c.getString(iconResourceIndex);
+ PackageManager packageManager = context.getPackageManager();
+ try {
+ Resources resources = packageManager.getResourcesForApplication(packageName);
+ final int id = resources.getIdentifier(resourceName, null, null);
+ liveFolderInfo.icon = resources.getDrawable(id);
+ } catch (Exception e) {
+ liveFolderInfo.icon =
+ context.getResources().getDrawable(R.drawable.ic_launcher_folder);
+ }
+ liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
+ liveFolderInfo.iconResource.packageName = packageName;
+ liveFolderInfo.iconResource.resourceName = resourceName;
+ break;
+ default:
+ liveFolderInfo.icon =
+ context.getResources().getDrawable(R.drawable.ic_launcher_folder);
+ }
+ }
+
+ /**
+ * Return an existing UserFolderInfo object if we have encountered this ID previously,
+ * or make a new one.
+ */
+ private static UserFolderInfo findOrMakeUserFolder(HashMap folders, long id) {
+ // See if a placeholder was created for us already
+ FolderInfo folderInfo = folders.get(id);
+ if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
+ // No placeholder -- create a new instance
+ folderInfo = new UserFolderInfo();
+ folders.put(id, folderInfo);
+ }
+ return (UserFolderInfo) folderInfo;
+ }
+
+ /**
+ * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
+ * new one.
+ */
+ private static LiveFolderInfo findOrMakeLiveFolder(HashMap folders, long id) {
+ // See if a placeholder was created for us already
+ FolderInfo folderInfo = folders.get(id);
+ if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
+ // No placeholder -- create a new instance
+ folderInfo = new LiveFolderInfo();
+ folders.put(id, folderInfo);
+ }
+ return (LiveFolderInfo) folderInfo;
+ }
+
+ private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
+ final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
+ LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
+ null, null, null);
+
+ final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+ final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
+ final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
+ final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
+
+ // boolean changed = false;
+
+ try {
+ while (c.moveToNext()) {
+ try {
+ if (c.getInt(itemTypeIndex) !=
+ LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
+ continue;
+ }
+
+ final String intentUri = c.getString(intentIndex);
+ if (intentUri != null) {
+ final Intent shortcut = Intent.parseUri(intentUri, 0);
+ if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
+ final ComponentName name = shortcut.getComponent();
+ if (name != null) {
+ final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
+ final String title = c.getString(titleIndex);
+ String label = getLabel(manager, activityInfo);
+
+ if (title == null || !title.equals(label)) {
+ final ContentValues values = new ContentValues();
+ values.put(LauncherSettings.Favorites.TITLE, label);
+
+ resolver.update(
+ LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
+ values, "_id=?",
+ new String[] { String.valueOf(c.getLong(idIndex)) });
+
+ // changed = true;
+ }
+ }
+ }
+ }
+ } catch (URISyntaxException e) {
+ // Ignore
+ } catch (PackageManager.NameNotFoundException e) {
+ // Ignore
+ }
+ }
+ } finally {
+ c.close();
+ }
+
+ // if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
+ }
+
+ private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
+ String label = activityInfo.loadLabel(manager).toString();
+ if (label == null) {
+ label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
+ if (label == null) {
+ label = activityInfo.name;
+ }
+ }
+ return label;
+ }
+
+ private static final Collator sCollator = Collator.getInstance();
+ public static final Comparator APP_NAME_COMPARATOR
+ = new Comparator() {
+ public final int compare(ApplicationInfo a, ApplicationInfo b) {
+ return sCollator.compare(a.title.toString(), b.title.toString());
+ }
+ };
+
+ public void dumpState() {
+ Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
+ Log.d(TAG, "mCallbacks=" + mCallbacks);
+ ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
+ ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
+ ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
+ ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
+ mLoader.dumpState();
+ }
+}
diff --git a/src/com/android/launcher2/LauncherProvider.java b/src/com/android/launcher2/LauncherProvider.java
new file mode 100644
index 0000000000..c3ceefdd32
--- /dev/null
+++ b/src/com/android/launcher2/LauncherProvider.java
@@ -0,0 +1,808 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.appwidget.AppWidgetHost;
+import android.appwidget.AppWidgetManager;
+import android.content.ContentProvider;
+import android.content.Context;
+import android.content.ContentValues;
+import android.content.Intent;
+import android.content.ComponentName;
+import android.content.ContentUris;
+import android.content.ContentResolver;
+import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
+import android.content.res.TypedArray;
+import android.content.pm.PackageManager;
+import android.content.pm.ActivityInfo;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteQueryBuilder;
+import android.database.Cursor;
+import android.database.SQLException;
+import android.util.Log;
+import android.util.Xml;
+import android.util.AttributeSet;
+import android.net.Uri;
+import android.text.TextUtils;
+import android.os.*;
+import android.provider.Settings;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParser;
+import com.android.internal.util.XmlUtils;
+import com.android.launcher2.LauncherSettings.Favorites;
+
+public class LauncherProvider extends ContentProvider {
+ private static final String TAG = "Launcher.LauncherProvider";
+ private static final boolean LOGD = false;
+
+ private static final String DATABASE_NAME = "launcher.db";
+
+ private static final int DATABASE_VERSION = 6;
+
+ static final String AUTHORITY = "com.android.launcher2.settings";
+
+ static final String EXTRA_BIND_SOURCES = "com.android.launcher2.settings.bindsources";
+ static final String EXTRA_BIND_TARGETS = "com.android.launcher2.settings.bindtargets";
+
+ static final String TABLE_FAVORITES = "favorites";
+ static final String PARAMETER_NOTIFY = "notify";
+
+ /**
+ * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
+ * {@link AppWidgetHost#deleteHost()} is called during database creation.
+ * Use this to recall {@link AppWidgetHost#startListening()} if needed.
+ */
+ static final Uri CONTENT_APPWIDGET_RESET_URI =
+ Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
+
+ private SQLiteOpenHelper mOpenHelper;
+
+ @Override
+ public boolean onCreate() {
+ mOpenHelper = new DatabaseHelper(getContext());
+ return true;
+ }
+
+ @Override
+ public String getType(Uri uri) {
+ SqlArguments args = new SqlArguments(uri, null, null);
+ if (TextUtils.isEmpty(args.where)) {
+ return "vnd.android.cursor.dir/" + args.table;
+ } else {
+ return "vnd.android.cursor.item/" + args.table;
+ }
+ }
+
+ @Override
+ public Cursor query(Uri uri, String[] projection, String selection,
+ String[] selectionArgs, String sortOrder) {
+
+ SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
+ SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
+ qb.setTables(args.table);
+
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
+ result.setNotificationUri(getContext().getContentResolver(), uri);
+
+ return result;
+ }
+
+ @Override
+ public Uri insert(Uri uri, ContentValues initialValues) {
+ SqlArguments args = new SqlArguments(uri);
+
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ final long rowId = db.insert(args.table, null, initialValues);
+ if (rowId <= 0) return null;
+
+ uri = ContentUris.withAppendedId(uri, rowId);
+ sendNotify(uri);
+
+ return uri;
+ }
+
+ @Override
+ public int bulkInsert(Uri uri, ContentValues[] values) {
+ SqlArguments args = new SqlArguments(uri);
+
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ db.beginTransaction();
+ try {
+ int numValues = values.length;
+ for (int i = 0; i < numValues; i++) {
+ if (db.insert(args.table, null, values[i]) < 0) return 0;
+ }
+ db.setTransactionSuccessful();
+ } finally {
+ db.endTransaction();
+ }
+
+ sendNotify(uri);
+ return values.length;
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
+
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ int count = db.delete(args.table, args.where, args.args);
+ if (count > 0) sendNotify(uri);
+
+ return count;
+ }
+
+ @Override
+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
+
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ int count = db.update(args.table, values, args.where, args.args);
+ if (count > 0) sendNotify(uri);
+
+ return count;
+ }
+
+ private void sendNotify(Uri uri) {
+ String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
+ if (notify == null || "true".equals(notify)) {
+ getContext().getContentResolver().notifyChange(uri, null);
+ }
+ }
+
+ private static class DatabaseHelper extends SQLiteOpenHelper {
+ private static final String TAG_FAVORITES = "favorites";
+ private static final String TAG_FAVORITE = "favorite";
+ private static final String TAG_CLOCK = "clock";
+ private static final String TAG_SEARCH = "search";
+ private static final String TAG_APPWIDGET = "appwidget";
+ private static final String TAG_SHORTCUT = "shortcut";
+
+ private final Context mContext;
+ private final AppWidgetHost mAppWidgetHost;
+
+ DatabaseHelper(Context context) {
+ super(context, DATABASE_NAME, null, DATABASE_VERSION);
+ mContext = context;
+ mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
+ }
+
+ /**
+ * Send notification that we've deleted the {@link AppWidgetHost},
+ * probably as part of the initial database creation. The receiver may
+ * want to re-call {@link AppWidgetHost#startListening()} to ensure
+ * callbacks are correctly set.
+ */
+ private void sendAppWidgetResetNotify() {
+ final ContentResolver resolver = mContext.getContentResolver();
+ resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
+ }
+
+ @Override
+ public void onCreate(SQLiteDatabase db) {
+ if (LOGD) Log.d(TAG, "creating new launcher database");
+
+ db.execSQL("CREATE TABLE favorites (" +
+ "_id INTEGER PRIMARY KEY," +
+ "title TEXT," +
+ "intent TEXT," +
+ "container INTEGER," +
+ "screen INTEGER," +
+ "cellX INTEGER," +
+ "cellY INTEGER," +
+ "spanX INTEGER," +
+ "spanY INTEGER," +
+ "itemType INTEGER," +
+ "appWidgetId INTEGER NOT NULL DEFAULT -1," +
+ "isShortcut INTEGER," +
+ "iconType INTEGER," +
+ "iconPackage TEXT," +
+ "iconResource TEXT," +
+ "icon BLOB," +
+ "uri TEXT," +
+ "displayMode INTEGER" +
+ ");");
+
+ // Database was just created, so wipe any previous widgets
+ if (mAppWidgetHost != null) {
+ mAppWidgetHost.deleteHost();
+ sendAppWidgetResetNotify();
+ }
+
+ if (!convertDatabase(db)) {
+ // Populate favorites table with initial favorites
+ loadFavorites(db);
+ }
+ }
+
+ private boolean convertDatabase(SQLiteDatabase db) {
+ if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
+ boolean converted = false;
+
+ final Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
+ "/old_favorites?notify=true");
+ final ContentResolver resolver = mContext.getContentResolver();
+ Cursor cursor = null;
+
+ try {
+ cursor = resolver.query(uri, null, null, null, null);
+ } catch (Exception e) {
+ // Ignore
+ }
+
+ // We already have a favorites database in the old provider
+ if (cursor != null && cursor.getCount() > 0) {
+ try {
+ converted = copyFromCursor(db, cursor) > 0;
+ } finally {
+ cursor.close();
+ }
+
+ if (converted) {
+ resolver.delete(uri, null, null);
+ }
+ }
+
+ if (converted) {
+ // Convert widgets from this import into widgets
+ if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
+ convertWidgets(db);
+ }
+
+ return converted;
+ }
+
+ private int copyFromCursor(SQLiteDatabase db, Cursor c) {
+ final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+ final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
+ final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
+ final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
+ final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
+ final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
+ final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
+ final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
+ final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
+ final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
+ final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
+ final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
+ final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
+ final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
+
+ ContentValues[] rows = new ContentValues[c.getCount()];
+ int i = 0;
+ while (c.moveToNext()) {
+ ContentValues values = new ContentValues(c.getColumnCount());
+ values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
+ values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
+ values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
+ values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
+ values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
+ values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
+ values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
+ values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
+ values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
+ values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
+ values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
+ values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
+ values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
+ values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
+ values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
+ rows[i++] = values;
+ }
+
+ db.beginTransaction();
+ int total = 0;
+ try {
+ int numValues = rows.length;
+ for (i = 0; i < numValues; i++) {
+ if (db.insert(TABLE_FAVORITES, null, rows[i]) < 0) {
+ return 0;
+ } else {
+ total++;
+ }
+ }
+ db.setTransactionSuccessful();
+ } finally {
+ db.endTransaction();
+ }
+
+ return total;
+ }
+
+ @Override
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+ if (LOGD) Log.d(TAG, "onUpgrade triggered");
+
+ int version = oldVersion;
+ if (version < 3) {
+ // upgrade 1,2 -> 3 added appWidgetId column
+ db.beginTransaction();
+ try {
+ // Insert new column for holding appWidgetIds
+ db.execSQL("ALTER TABLE favorites " +
+ "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
+ db.setTransactionSuccessful();
+ version = 3;
+ } catch (SQLException ex) {
+ // Old version remains, which means we wipe old data
+ Log.e(TAG, ex.getMessage(), ex);
+ } finally {
+ db.endTransaction();
+ }
+
+ // Convert existing widgets only if table upgrade was successful
+ if (version == 3) {
+ convertWidgets(db);
+ }
+ }
+
+ if (version < 4) {
+ version = 4;
+ }
+
+ if (version < 5) {
+ // We went from 3 to 5 screens. Move everything 1 to the right
+ db.beginTransaction();
+ try {
+ db.execSQL("UPDATE favorites SET screen=(screen + 1);");
+ db.setTransactionSuccessful();
+ version = 5;
+ } catch (SQLException ex) {
+ // Old version remains, which means we wipe old data
+ Log.e(TAG, ex.getMessage(), ex);
+ } finally {
+ db.endTransaction();
+ }
+ }
+
+ if (version < 6) {
+ if (updateContactsShortcuts(db)) {
+ version = 6;
+ }
+ }
+
+ if (version != DATABASE_VERSION) {
+ Log.w(TAG, "Destroying all old data.");
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
+ onCreate(db);
+ }
+ }
+
+ private boolean updateContactsShortcuts(SQLiteDatabase db) {
+ Cursor c = null;
+ final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
+ new int[] { Favorites.ITEM_TYPE_SHORTCUT });
+
+ db.beginTransaction();
+ try {
+ // Select and iterate through each matching widget
+ c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.INTENT },
+ selectWhere, null, null, null, null);
+
+ if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
+
+ final ContentValues values = new ContentValues();
+ final int idIndex = c.getColumnIndex(Favorites._ID);
+ final int intentIndex = c.getColumnIndex(Favorites.INTENT);
+
+ while (c != null && c.moveToNext()) {
+ long favoriteId = c.getLong(idIndex);
+ final String intentUri = c.getString(intentIndex);
+ if (intentUri != null) {
+ try {
+ Intent intent = Intent.parseUri(intentUri, 0);
+ android.util.Log.d("Home", intent.toString());
+ final Uri uri = intent.getData();
+ final String data = uri.toString();
+ if (Intent.ACTION_VIEW.equals(intent.getAction()) &&
+ (data.startsWith("content://contacts/people/") ||
+ data.startsWith("content://com.android.contacts/contacts/lookup/"))) {
+
+ intent = new Intent("com.android.contacts.action.QUICK_CONTACT");
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
+ Intent.FLAG_ACTIVITY_CLEAR_TOP |
+ Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+
+ intent.setData(uri);
+ intent.putExtra("mode", 3);
+ intent.putExtra("exclude_mimes", (String[]) null);
+
+ values.clear();
+ values.put(LauncherSettings.Favorites.INTENT, intent.toUri(0));
+
+ String updateWhere = Favorites._ID + "=" + favoriteId;
+ db.update(TABLE_FAVORITES, values, updateWhere, null);
+ }
+ } catch (RuntimeException ex) {
+ Log.e(TAG, "Problem upgrading shortcut", ex);
+ } catch (URISyntaxException e) {
+ Log.e(TAG, "Problem upgrading shortcut", e);
+ }
+ }
+ }
+
+ db.setTransactionSuccessful();
+ } catch (SQLException ex) {
+ Log.w(TAG, "Problem while upgrading contacts", ex);
+ return false;
+ } finally {
+ db.endTransaction();
+ if (c != null) {
+ c.close();
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Upgrade existing clock and photo frame widgets into their new widget
+ * equivalents. This method allocates appWidgetIds, and then hands off to
+ * LauncherAppWidgetBinder to finish the actual binding.
+ */
+ private void convertWidgets(SQLiteDatabase db) {
+ final int[] bindSources = new int[] {
+ Favorites.ITEM_TYPE_WIDGET_CLOCK,
+ Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
+ };
+
+ final ArrayList bindTargets = new ArrayList();
+ bindTargets.add(new ComponentName("com.android.alarmclock",
+ "com.android.alarmclock.AnalogAppWidgetProvider"));
+ bindTargets.add(new ComponentName("com.android.camera",
+ "com.android.camera.PhotoAppWidgetProvider"));
+
+ final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
+
+ Cursor c = null;
+ boolean allocatedAppWidgets = false;
+
+ db.beginTransaction();
+ try {
+ // Select and iterate through each matching widget
+ c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID },
+ selectWhere, null, null, null, null);
+
+ if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
+
+ final ContentValues values = new ContentValues();
+ while (c != null && c.moveToNext()) {
+ long favoriteId = c.getLong(0);
+
+ // Allocate and update database with new appWidgetId
+ try {
+ int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
+
+ if (LOGD) {
+ Log.d(TAG, "allocated appWidgetId=" + appWidgetId
+ + " for favoriteId=" + favoriteId);
+ }
+
+ values.clear();
+ values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
+
+ // Original widgets might not have valid spans when upgrading
+ values.put(LauncherSettings.Favorites.SPANX, 2);
+ values.put(LauncherSettings.Favorites.SPANY, 2);
+
+ String updateWhere = Favorites._ID + "=" + favoriteId;
+ db.update(TABLE_FAVORITES, values, updateWhere, null);
+
+ allocatedAppWidgets = true;
+ } catch (RuntimeException ex) {
+ Log.e(TAG, "Problem allocating appWidgetId", ex);
+ }
+ }
+
+ db.setTransactionSuccessful();
+ } catch (SQLException ex) {
+ Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
+ } finally {
+ db.endTransaction();
+ if (c != null) {
+ c.close();
+ }
+ }
+
+ // If any appWidgetIds allocated, then launch over to binder
+ if (allocatedAppWidgets) {
+ launchAppWidgetBinder(bindSources, bindTargets);
+ }
+ }
+
+ /**
+ * Launch the widget binder that walks through the Launcher database,
+ * binding any matching widgets to the corresponding targets. We can't
+ * bind ourselves because our parent process can't obtain the
+ * BIND_APPWIDGET permission.
+ */
+ private void launchAppWidgetBinder(int[] bindSources, ArrayList bindTargets) {
+ final Intent intent = new Intent();
+ intent.setComponent(new ComponentName("com.android.settings",
+ "com.android.settings.LauncherAppWidgetBinder"));
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ final Bundle extras = new Bundle();
+ extras.putIntArray(EXTRA_BIND_SOURCES, bindSources);
+ extras.putParcelableArrayList(EXTRA_BIND_TARGETS, bindTargets);
+ intent.putExtras(extras);
+
+ mContext.startActivity(intent);
+ }
+
+ /**
+ * Loads the default set of favorite packages from an xml file.
+ *
+ * @param db The database to write the values into
+ */
+ private int loadFavorites(SQLiteDatabase db) {
+ Intent intent = new Intent(Intent.ACTION_MAIN, null);
+ intent.addCategory(Intent.CATEGORY_LAUNCHER);
+ ContentValues values = new ContentValues();
+
+ PackageManager packageManager = mContext.getPackageManager();
+ int i = 0;
+ try {
+ XmlResourceParser parser = mContext.getResources().getXml(R.xml.default_workspace);
+ AttributeSet attrs = Xml.asAttributeSet(parser);
+ XmlUtils.beginDocument(parser, TAG_FAVORITES);
+
+ final int depth = parser.getDepth();
+
+ int type;
+ while (((type = parser.next()) != XmlPullParser.END_TAG ||
+ parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
+
+ if (type != XmlPullParser.START_TAG) {
+ continue;
+ }
+
+ boolean added = false;
+ final String name = parser.getName();
+
+ TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
+
+ values.clear();
+ values.put(LauncherSettings.Favorites.CONTAINER,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP);
+ values.put(LauncherSettings.Favorites.SCREEN,
+ a.getString(R.styleable.Favorite_screen));
+ values.put(LauncherSettings.Favorites.CELLX,
+ a.getString(R.styleable.Favorite_x));
+ values.put(LauncherSettings.Favorites.CELLY,
+ a.getString(R.styleable.Favorite_y));
+
+ if (TAG_FAVORITE.equals(name)) {
+ added = addAppShortcut(db, values, a, packageManager, intent);
+ } else if (TAG_SEARCH.equals(name)) {
+ added = addSearchWidget(db, values);
+ } else if (TAG_CLOCK.equals(name)) {
+ added = addClockWidget(db, values);
+ } else if (TAG_APPWIDGET.equals(name)) {
+ added = addAppWidget(db, values, a);
+ } else if (TAG_SHORTCUT.equals(name)) {
+ added = addUriShortcut(db, values, a);
+ }
+
+ if (added) i++;
+
+ a.recycle();
+ }
+ } catch (XmlPullParserException e) {
+ Log.w(TAG, "Got exception parsing favorites.", e);
+ } catch (IOException e) {
+ Log.w(TAG, "Got exception parsing favorites.", e);
+ }
+
+ return i;
+ }
+
+ private boolean addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
+ PackageManager packageManager, Intent intent) {
+
+ ActivityInfo info;
+ String packageName = a.getString(R.styleable.Favorite_packageName);
+ String className = a.getString(R.styleable.Favorite_className);
+ try {
+ ComponentName cn = new ComponentName(packageName, className);
+ info = packageManager.getActivityInfo(cn, 0);
+ intent.setComponent(cn);
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+ values.put(Favorites.INTENT, intent.toUri(0));
+ values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
+ values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
+ values.put(Favorites.SPANX, 1);
+ values.put(Favorites.SPANY, 1);
+ db.insert(TABLE_FAVORITES, null, values);
+ } catch (PackageManager.NameNotFoundException e) {
+ Log.w(TAG, "Unable to add favorite: " + packageName +
+ "/" + className, e);
+ return false;
+ }
+ return true;
+ }
+
+ private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
+ // Add a search box
+ values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_WIDGET_SEARCH);
+ values.put(Favorites.SPANX, 4);
+ values.put(Favorites.SPANY, 1);
+ db.insert(TABLE_FAVORITES, null, values);
+
+ return true;
+ }
+
+ private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
+ final int[] bindSources = new int[] {
+ Favorites.ITEM_TYPE_WIDGET_CLOCK,
+ };
+
+ final ArrayList bindTargets = new ArrayList();
+ bindTargets.add(new ComponentName("com.android.alarmclock",
+ "com.android.alarmclock.AnalogAppWidgetProvider"));
+
+ boolean allocatedAppWidgets = false;
+
+ // Try binding to an analog clock widget
+ try {
+ int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
+
+ values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_WIDGET_CLOCK);
+ values.put(Favorites.SPANX, 2);
+ values.put(Favorites.SPANY, 2);
+ values.put(Favorites.APPWIDGET_ID, appWidgetId);
+ db.insert(TABLE_FAVORITES, null, values);
+
+ allocatedAppWidgets = true;
+ } catch (RuntimeException ex) {
+ Log.e(TAG, "Problem allocating appWidgetId", ex);
+ }
+
+ // If any appWidgetIds allocated, then launch over to binder
+ if (allocatedAppWidgets) {
+ launchAppWidgetBinder(bindSources, bindTargets);
+ }
+
+ return allocatedAppWidgets;
+ }
+
+ private boolean addAppWidget(SQLiteDatabase db, ContentValues values, TypedArray a) {
+ String packageName = a.getString(R.styleable.Favorite_packageName);
+ String className = a.getString(R.styleable.Favorite_className);
+
+ if (packageName == null || className == null) {
+ return false;
+ }
+
+ ComponentName cn = new ComponentName(packageName, className);
+
+ boolean allocatedAppWidgets = false;
+ final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
+
+ try {
+ int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
+
+ values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
+ values.put(Favorites.SPANX, a.getString(R.styleable.Favorite_spanX));
+ values.put(Favorites.SPANY, a.getString(R.styleable.Favorite_spanY));
+ values.put(Favorites.APPWIDGET_ID, appWidgetId);
+ db.insert(TABLE_FAVORITES, null, values);
+
+ allocatedAppWidgets = true;
+
+ appWidgetManager.bindAppWidgetId(appWidgetId, cn);
+ } catch (RuntimeException ex) {
+ Log.e(TAG, "Problem allocating appWidgetId", ex);
+ }
+
+ return allocatedAppWidgets;
+ }
+
+ private boolean addUriShortcut(SQLiteDatabase db, ContentValues values,
+ TypedArray a) {
+ Resources r = mContext.getResources();
+
+ final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
+ final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
+
+ Intent intent;
+ String uri = null;
+ try {
+ uri = a.getString(R.styleable.Favorite_uri);
+ intent = Intent.parseUri(uri, 0);
+ } catch (URISyntaxException e) {
+ Log.w(TAG, "Shortcut has malformed uri: " + uri);
+ return false; // Oh well
+ }
+
+ if (iconResId == 0 || titleResId == 0) {
+ Log.w(TAG, "Shortcut is missing title or icon resource ID");
+ return false;
+ }
+
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ values.put(Favorites.INTENT, intent.toUri(0));
+ values.put(Favorites.TITLE, r.getString(titleResId));
+ values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
+ values.put(Favorites.SPANX, 1);
+ values.put(Favorites.SPANY, 1);
+ values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
+ values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
+ values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
+
+ db.insert(TABLE_FAVORITES, null, values);
+
+ return true;
+ }
+ }
+
+ /**
+ * Build a query string that will match any row where the column matches
+ * anything in the values list.
+ */
+ static String buildOrWhereString(String column, int[] values) {
+ StringBuilder selectWhere = new StringBuilder();
+ for (int i = values.length - 1; i >= 0; i--) {
+ selectWhere.append(column).append("=").append(values[i]);
+ if (i > 0) {
+ selectWhere.append(" OR ");
+ }
+ }
+ return selectWhere.toString();
+ }
+
+ static class SqlArguments {
+ public final String table;
+ public final String where;
+ public final String[] args;
+
+ SqlArguments(Uri url, String where, String[] args) {
+ if (url.getPathSegments().size() == 1) {
+ this.table = url.getPathSegments().get(0);
+ this.where = where;
+ this.args = args;
+ } else if (url.getPathSegments().size() != 2) {
+ throw new IllegalArgumentException("Invalid URI: " + url);
+ } else if (!TextUtils.isEmpty(where)) {
+ throw new UnsupportedOperationException("WHERE clause not supported: " + url);
+ } else {
+ this.table = url.getPathSegments().get(0);
+ this.where = "_id=" + ContentUris.parseId(url);
+ this.args = null;
+ }
+ }
+
+ SqlArguments(Uri url) {
+ if (url.getPathSegments().size() == 1) {
+ table = url.getPathSegments().get(0);
+ where = null;
+ args = null;
+ } else {
+ throw new IllegalArgumentException("Invalid URI: " + url);
+ }
+ }
+ }
+}
diff --git a/src/com/android/launcher2/LauncherSettings.java b/src/com/android/launcher2/LauncherSettings.java
new file mode 100644
index 0000000000..a438d47cbc
--- /dev/null
+++ b/src/com/android/launcher2/LauncherSettings.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.provider.BaseColumns;
+import android.net.Uri;
+
+/**
+ * Settings related utilities.
+ */
+class LauncherSettings {
+ static interface BaseLauncherColumns extends BaseColumns {
+ /**
+ * Descriptive name of the gesture that can be displayed to the user.
+ * Type: TEXT
+ */
+ static final String TITLE = "title";
+
+ /**
+ * The Intent URL of the gesture, describing what it points to. This
+ * value is given to {@link android.content.Intent#parseUri(String, int)} to create
+ * an Intent that can be launched.
+ * Type: TEXT
+ */
+ static final String INTENT = "intent";
+
+ /**
+ * The type of the gesture
+ *
+ * Type: INTEGER
+ */
+ static final String ITEM_TYPE = "itemType";
+
+ /**
+ * The gesture is an application
+ */
+ static final int ITEM_TYPE_APPLICATION = 0;
+
+ /**
+ * The gesture is an application created shortcut
+ */
+ static final int ITEM_TYPE_SHORTCUT = 1;
+
+ /**
+ * The icon type.
+ * Type: INTEGER
+ */
+ static final String ICON_TYPE = "iconType";
+
+ /**
+ * The icon is a resource identified by a package name and an integer id.
+ */
+ static final int ICON_TYPE_RESOURCE = 0;
+
+ /**
+ * The icon is a bitmap.
+ */
+ static final int ICON_TYPE_BITMAP = 1;
+
+ /**
+ * The icon package name, if icon type is ICON_TYPE_RESOURCE.
+ * Type: TEXT
+ */
+ static final String ICON_PACKAGE = "iconPackage";
+
+ /**
+ * The icon resource id, if icon type is ICON_TYPE_RESOURCE.
+ * Type: TEXT
+ */
+ static final String ICON_RESOURCE = "iconResource";
+
+ /**
+ * The custom icon bitmap, if icon type is ICON_TYPE_BITMAP.
+ * Type: BLOB
+ */
+ static final String ICON = "icon";
+ }
+
+ /**
+ * Favorites. When changing these values, be sure to update
+ * {@link com.android.settings.LauncherAppWidgetBinder} as needed.
+ */
+ static final class Favorites implements BaseLauncherColumns {
+ /**
+ * The content:// style URL for this table
+ */
+ static final Uri CONTENT_URI = Uri.parse("content://" +
+ LauncherProvider.AUTHORITY + "/" + LauncherProvider.TABLE_FAVORITES +
+ "?" + LauncherProvider.PARAMETER_NOTIFY + "=true");
+
+ /**
+ * The content:// style URL for this table. When this Uri is used, no notification is
+ * sent if the content changes.
+ */
+ static final Uri CONTENT_URI_NO_NOTIFICATION = Uri.parse("content://" +
+ LauncherProvider.AUTHORITY + "/" + LauncherProvider.TABLE_FAVORITES +
+ "?" + LauncherProvider.PARAMETER_NOTIFY + "=false");
+
+ /**
+ * The content:// style URL for a given row, identified by its id.
+ *
+ * @param id The row id.
+ * @param notify True to send a notification is the content changes.
+ *
+ * @return The unique content URL for the specified row.
+ */
+ static Uri getContentUri(long id, boolean notify) {
+ return Uri.parse("content://" + LauncherProvider.AUTHORITY +
+ "/" + LauncherProvider.TABLE_FAVORITES + "/" + id + "?" +
+ LauncherProvider.PARAMETER_NOTIFY + "=" + notify);
+ }
+
+ /**
+ * The container holding the favorite
+ * Type: INTEGER
+ */
+ static final String CONTAINER = "container";
+
+ /**
+ * The icon is a resource identified by a package name and an integer id.
+ */
+ static final int CONTAINER_DESKTOP = -100;
+
+ /**
+ * The screen holding the favorite (if container is CONTAINER_DESKTOP)
+ * Type: INTEGER
+ */
+ static final String SCREEN = "screen";
+
+ /**
+ * The X coordinate of the cell holding the favorite
+ * (if container is CONTAINER_DESKTOP or CONTAINER_DOCK)
+ * Type: INTEGER
+ */
+ static final String CELLX = "cellX";
+
+ /**
+ * The Y coordinate of the cell holding the favorite
+ * (if container is CONTAINER_DESKTOP)
+ * Type: INTEGER
+ */
+ static final String CELLY = "cellY";
+
+ /**
+ * The X span of the cell holding the favorite
+ * Type: INTEGER
+ */
+ static final String SPANX = "spanX";
+
+ /**
+ * The Y span of the cell holding the favorite
+ * Type: INTEGER
+ */
+ static final String SPANY = "spanY";
+
+ /**
+ * The favorite is a user created folder
+ */
+ static final int ITEM_TYPE_USER_FOLDER = 2;
+
+ /**
+ * The favorite is a live folder
+ */
+ static final int ITEM_TYPE_LIVE_FOLDER = 3;
+
+ /**
+ * The favorite is a widget
+ */
+ static final int ITEM_TYPE_APPWIDGET = 4;
+
+ /**
+ * The favorite is a clock
+ */
+ static final int ITEM_TYPE_WIDGET_CLOCK = 1000;
+
+ /**
+ * The favorite is a search widget
+ */
+ static final int ITEM_TYPE_WIDGET_SEARCH = 1001;
+
+ /**
+ * The favorite is a photo frame
+ */
+ static final int ITEM_TYPE_WIDGET_PHOTO_FRAME = 1002;
+
+ /**
+ * The appWidgetId of the widget
+ *
+ * Type: INTEGER
+ */
+ static final String APPWIDGET_ID = "appWidgetId";
+
+ /**
+ * Indicates whether this favorite is an application-created shortcut or not.
+ * If the value is 0, the favorite is not an application-created shortcut, if the
+ * value is 1, it is an application-created shortcut.
+ * Type: INTEGER
+ */
+ @Deprecated
+ static final String IS_SHORTCUT = "isShortcut";
+
+ /**
+ * The URI associated with the favorite. It is used, for instance, by
+ * live folders to find the content provider.
+ * Type: TEXT
+ */
+ static final String URI = "uri";
+
+ /**
+ * The display mode if the item is a live folder.
+ * Type: INTEGER
+ *
+ * @see android.provider.LiveFolders#DISPLAY_MODE_GRID
+ * @see android.provider.LiveFolders#DISPLAY_MODE_LIST
+ */
+ static final String DISPLAY_MODE = "displayMode";
+ }
+}
diff --git a/src/com/android/launcher2/LiveFolder.java b/src/com/android/launcher2/LiveFolder.java
new file mode 100644
index 0000000000..ecd9bdf9c6
--- /dev/null
+++ b/src/com/android/launcher2/LiveFolder.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.AdapterView;
+import android.net.Uri;
+import android.provider.LiveFolders;
+import android.os.AsyncTask;
+import android.database.Cursor;
+
+import java.lang.ref.WeakReference;
+
+public class LiveFolder extends Folder {
+ private AsyncTask mLoadingTask;
+
+ public LiveFolder(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ static LiveFolder fromXml(Context context, FolderInfo folderInfo) {
+ final int layout = isDisplayModeList(folderInfo) ?
+ R.layout.live_folder_list : R.layout.live_folder_grid;
+ return (LiveFolder) LayoutInflater.from(context).inflate(layout, null);
+ }
+
+ private static boolean isDisplayModeList(FolderInfo folderInfo) {
+ return ((LiveFolderInfo) folderInfo).displayMode ==
+ LiveFolders.DISPLAY_MODE_LIST;
+ }
+
+ @Override
+ public void onItemClick(AdapterView parent, View v, int position, long id) {
+ LiveFolderAdapter.ViewHolder holder = (LiveFolderAdapter.ViewHolder) v.getTag();
+
+ if (holder.useBaseIntent) {
+ final Intent baseIntent = ((LiveFolderInfo) mInfo).baseIntent;
+ if (baseIntent != null) {
+ final Intent intent = new Intent(baseIntent);
+ Uri uri = baseIntent.getData();
+ uri = uri.buildUpon().appendPath(Long.toString(holder.id)).build();
+ intent.setData(uri);
+ mLauncher.startActivitySafely(intent);
+ }
+ } else if (holder.intent != null) {
+ mLauncher.startActivitySafely(holder.intent);
+ }
+ }
+
+ @Override
+ public boolean onItemLongClick(AdapterView> parent, View view, int position, long id) {
+ return false;
+ }
+
+ void bind(FolderInfo info) {
+ super.bind(info);
+ if (mLoadingTask != null && mLoadingTask.getStatus() == AsyncTask.Status.RUNNING) {
+ mLoadingTask.cancel(true);
+ }
+ mLoadingTask = new FolderLoadingTask(this).execute((LiveFolderInfo) info);
+ }
+
+ @Override
+ void onOpen() {
+ super.onOpen();
+ requestFocus();
+ }
+
+ @Override
+ void onClose() {
+ super.onClose();
+ if (mLoadingTask != null && mLoadingTask.getStatus() == AsyncTask.Status.RUNNING) {
+ mLoadingTask.cancel(true);
+ }
+
+ // The adapter can be null if onClose() is called before FolderLoadingTask
+ // is done querying the provider
+ final LiveFolderAdapter adapter = (LiveFolderAdapter) mContent.getAdapter();
+ if (adapter != null) {
+ adapter.cleanup();
+ }
+ }
+
+ static class FolderLoadingTask extends AsyncTask {
+ private final WeakReference mFolder;
+ private LiveFolderInfo mInfo;
+
+ FolderLoadingTask(LiveFolder folder) {
+ mFolder = new WeakReference(folder);
+ }
+
+ protected Cursor doInBackground(LiveFolderInfo... params) {
+ final LiveFolder folder = mFolder.get();
+ if (folder != null) {
+ mInfo = params[0];
+ return LiveFolderAdapter.query(folder.mLauncher, mInfo);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Cursor cursor) {
+ if (!isCancelled()) {
+ if (cursor != null) {
+ final LiveFolder folder = mFolder.get();
+ if (folder != null) {
+ final Launcher launcher = folder.mLauncher;
+ folder.setContentAdapter(new LiveFolderAdapter(launcher, mInfo, cursor));
+ }
+ }
+ } else if (cursor != null) {
+ cursor.close();
+ }
+ }
+ }
+}
diff --git a/src/com/android/launcher2/LiveFolderAdapter.java b/src/com/android/launcher2/LiveFolderAdapter.java
new file mode 100644
index 0000000000..b0e9eff1f1
--- /dev/null
+++ b/src/com/android/launcher2/LiveFolderAdapter.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.widget.CursorAdapter;
+import android.widget.TextView;
+import android.widget.ImageView;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.content.pm.PackageManager;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.LayoutInflater;
+import android.database.Cursor;
+import android.provider.LiveFolders;
+import android.graphics.drawable.Drawable;
+import android.graphics.BitmapFactory;
+import android.graphics.Bitmap;
+
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.lang.ref.SoftReference;
+
+class LiveFolderAdapter extends CursorAdapter {
+ private boolean mIsList;
+ private LayoutInflater mInflater;
+
+ private final HashMap mIcons = new HashMap();
+ private final HashMap> mCustomIcons =
+ new HashMap>();
+ private final Launcher mLauncher;
+
+ LiveFolderAdapter(Launcher launcher, LiveFolderInfo info, Cursor cursor) {
+ super(launcher, cursor, true);
+ mIsList = info.displayMode == LiveFolders.DISPLAY_MODE_LIST;
+ mInflater = LayoutInflater.from(launcher);
+ mLauncher = launcher;
+
+ mLauncher.startManagingCursor(getCursor());
+ }
+
+ static Cursor query(Context context, LiveFolderInfo info) {
+ return context.getContentResolver().query(info.uri, null, null,
+ null, LiveFolders.NAME + " ASC");
+ }
+
+ public View newView(Context context, Cursor cursor, ViewGroup parent) {
+ View view;
+ final ViewHolder holder = new ViewHolder();
+
+ if (!mIsList) {
+ view = mInflater.inflate(R.layout.application_boxed, parent, false);
+ } else {
+ view = mInflater.inflate(R.layout.application_list, parent, false);
+ holder.description = (TextView) view.findViewById(R.id.description);
+ holder.icon = (ImageView) view.findViewById(R.id.icon);
+ }
+
+ holder.name = (TextView) view.findViewById(R.id.name);
+
+ holder.idIndex = cursor.getColumnIndexOrThrow(LiveFolders._ID);
+ holder.nameIndex = cursor.getColumnIndexOrThrow(LiveFolders.NAME);
+ holder.descriptionIndex = cursor.getColumnIndex(LiveFolders.DESCRIPTION);
+ holder.intentIndex = cursor.getColumnIndex(LiveFolders.INTENT);
+ holder.iconBitmapIndex = cursor.getColumnIndex(LiveFolders.ICON_BITMAP);
+ holder.iconResourceIndex = cursor.getColumnIndex(LiveFolders.ICON_RESOURCE);
+ holder.iconPackageIndex = cursor.getColumnIndex(LiveFolders.ICON_PACKAGE);
+
+ view.setTag(holder);
+
+ return view;
+ }
+
+ public void bindView(View view, Context context, Cursor cursor) {
+ final ViewHolder holder = (ViewHolder) view.getTag();
+
+ holder.id = cursor.getLong(holder.idIndex);
+ final Drawable icon = loadIcon(context, cursor, holder);
+
+ holder.name.setText(cursor.getString(holder.nameIndex));
+
+ if (!mIsList) {
+ holder.name.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null);
+ } else {
+ final boolean hasIcon = icon != null;
+ holder.icon.setVisibility(hasIcon ? View.VISIBLE : View.GONE);
+ if (hasIcon) holder.icon.setImageDrawable(icon);
+
+ if (holder.descriptionIndex != -1) {
+ final String description = cursor.getString(holder.descriptionIndex);
+ if (description != null) {
+ holder.description.setText(description);
+ holder.description.setVisibility(View.VISIBLE);
+ } else {
+ holder.description.setVisibility(View.GONE);
+ }
+ } else {
+ holder.description.setVisibility(View.GONE);
+ }
+ }
+
+ if (holder.intentIndex != -1) {
+ try {
+ holder.intent = Intent.parseUri(cursor.getString(holder.intentIndex), 0);
+ } catch (URISyntaxException e) {
+ // Ignore
+ }
+ } else {
+ holder.useBaseIntent = true;
+ }
+ }
+
+ private Drawable loadIcon(Context context, Cursor cursor, ViewHolder holder) {
+ Drawable icon = null;
+ byte[] data = null;
+
+ if (holder.iconBitmapIndex != -1) {
+ data = cursor.getBlob(holder.iconBitmapIndex);
+ }
+
+ if (data != null) {
+ final SoftReference reference = mCustomIcons.get(holder.id);
+ if (reference != null) {
+ icon = reference.get();
+ }
+
+ if (icon == null) {
+ final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
+ icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, mContext));
+ mCustomIcons.put(holder.id, new SoftReference(icon));
+ }
+ } else if (holder.iconResourceIndex != -1 && holder.iconPackageIndex != -1) {
+ final String resource = cursor.getString(holder.iconResourceIndex);
+ icon = mIcons.get(resource);
+ if (icon == null) {
+ try {
+ final PackageManager packageManager = context.getPackageManager();
+ Resources resources = packageManager.getResourcesForApplication(
+ cursor.getString(holder.iconPackageIndex));
+ final int id = resources.getIdentifier(resource,
+ null, null);
+ icon = Utilities.createIconThumbnail(resources.getDrawable(id), mContext);
+ mIcons.put(resource, icon);
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+ }
+
+ return icon;
+ }
+
+ void cleanup() {
+ for (Drawable icon : mIcons.values()) {
+ icon.setCallback(null);
+ }
+ mIcons.clear();
+
+ for (SoftReference icon : mCustomIcons.values()) {
+ final Drawable drawable = icon.get();
+ if (drawable != null) {
+ drawable.setCallback(null);
+ }
+ }
+ mCustomIcons.clear();
+
+ final Cursor cursor = getCursor();
+ if (cursor != null) {
+ try {
+ cursor.close();
+ } finally {
+ mLauncher.stopManagingCursor(cursor);
+ }
+ }
+ }
+
+ static class ViewHolder {
+ TextView name;
+ TextView description;
+ ImageView icon;
+
+ Intent intent;
+ long id;
+ boolean useBaseIntent;
+
+ int idIndex;
+ int nameIndex;
+ int descriptionIndex = -1;
+ int intentIndex = -1;
+ int iconBitmapIndex = -1;
+ int iconResourceIndex = -1;
+ int iconPackageIndex = -1;
+ }
+}
diff --git a/src/com/android/launcher2/LiveFolderIcon.java b/src/com/android/launcher2/LiveFolderIcon.java
new file mode 100644
index 0000000000..55f100cced
--- /dev/null
+++ b/src/com/android/launcher2/LiveFolderIcon.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.util.AttributeSet;
+import android.view.ViewGroup;
+import android.view.LayoutInflater;
+import android.graphics.drawable.Drawable;
+
+public class LiveFolderIcon extends FolderIcon {
+ public LiveFolderIcon(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public LiveFolderIcon(Context context) {
+ super(context);
+ }
+
+ static LiveFolderIcon fromXml(int resId, Launcher launcher, ViewGroup group,
+ LiveFolderInfo folderInfo) {
+
+ LiveFolderIcon icon = (LiveFolderIcon)
+ LayoutInflater.from(launcher).inflate(resId, group, false);
+
+ final Resources resources = launcher.getResources();
+ Drawable d = folderInfo.icon;
+ if (d == null) {
+ d = Utilities.createIconThumbnail(resources.getDrawable(R.drawable.ic_launcher_folder),
+ launcher);
+ folderInfo.filtered = true;
+ }
+ icon.setCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
+ icon.setText(folderInfo.title);
+ icon.setTag(folderInfo);
+ icon.setOnClickListener(launcher);
+
+ return icon;
+ }
+
+ @Override
+ public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ return false;
+ }
+
+ @Override
+ public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ @Override
+ public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ @Override
+ public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ @Override
+ public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+}
diff --git a/src/com/android/launcher2/LiveFolderInfo.java b/src/com/android/launcher2/LiveFolderInfo.java
new file mode 100644
index 0000000000..5b1217c153
--- /dev/null
+++ b/src/com/android/launcher2/LiveFolderInfo.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.ContentValues;
+import android.content.Intent;
+import android.graphics.drawable.Drawable;
+import android.net.Uri;
+
+class LiveFolderInfo extends FolderInfo {
+
+ /**
+ * The base intent, if it exists.
+ */
+ Intent baseIntent;
+
+ /**
+ * The live folder's content uri.
+ */
+ Uri uri;
+
+ /**
+ * The live folder's display type.
+ */
+ int displayMode;
+
+ /**
+ * The live folder icon.
+ */
+ Drawable icon;
+
+ /**
+ * When set to true, indicates that the icon has been resized.
+ */
+ boolean filtered;
+
+ /**
+ * Reference to the live folder icon as an application's resource.
+ */
+ Intent.ShortcutIconResource iconResource;
+
+ LiveFolderInfo() {
+ itemType = LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER;
+ }
+
+ @Override
+ void onAddToDatabase(ContentValues values) {
+ super.onAddToDatabase(values);
+ values.put(LauncherSettings.Favorites.TITLE, title.toString());
+ values.put(LauncherSettings.Favorites.URI, uri.toString());
+ if (baseIntent != null) {
+ values.put(LauncherSettings.Favorites.INTENT, baseIntent.toUri(0));
+ }
+ values.put(LauncherSettings.Favorites.ICON_TYPE, LauncherSettings.Favorites.ICON_TYPE_RESOURCE);
+ values.put(LauncherSettings.Favorites.DISPLAY_MODE, displayMode);
+ if (iconResource != null) {
+ values.put(LauncherSettings.Favorites.ICON_PACKAGE, iconResource.packageName);
+ values.put(LauncherSettings.Favorites.ICON_RESOURCE, iconResource.resourceName);
+ }
+ }
+}
diff --git a/src/com/android/launcher2/Search.java b/src/com/android/launcher2/Search.java
new file mode 100644
index 0000000000..283042d19b
--- /dev/null
+++ b/src/com/android/launcher2/Search.java
@@ -0,0 +1,380 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.app.Activity;
+import android.content.ActivityNotFoundException;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.res.Configuration;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.View.OnKeyListener;
+import android.view.View.OnLongClickListener;
+import android.view.animation.AccelerateDecelerateInterpolator;
+import android.view.animation.Animation;
+import android.view.animation.Interpolator;
+import android.view.animation.Transformation;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.ImageButton;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+public class Search extends LinearLayout
+ implements OnClickListener, OnKeyListener, OnLongClickListener {
+
+ // Speed at which the widget slides up/down, in pixels/ms.
+ private static final float ANIMATION_VELOCITY = 1.0f;
+
+ /** The distance in dips between the optical top of the widget and the top if its bounds */
+ private static final float WIDGET_TOP_OFFSET = 9;
+
+
+ private final String TAG = "Launcher.SearchWidget";
+
+ private Launcher mLauncher;
+
+ private TextView mSearchText;
+ private ImageButton mVoiceButton;
+
+ /** The animation that morphs the search widget to the search dialog. */
+ private Animation mMorphAnimation;
+
+ /** The animation that morphs the search widget back to its normal position. */
+ private Animation mUnmorphAnimation;
+
+ // These four are passed to Launcher.startSearch() when the search widget
+ // has finished morphing. They are instance variables to make it possible to update
+ // them while the widget is morphing.
+ private String mInitialQuery;
+ private boolean mSelectInitialQuery;
+ private Bundle mAppSearchData;
+ private boolean mGlobalSearch;
+
+ // For voice searching
+ private Intent mVoiceSearchIntent;
+
+ private int mWidgetTopOffset;
+
+ /**
+ * Used to inflate the Workspace from XML.
+ *
+ * @param context The application's context.
+ * @param attrs The attributes set containing the Workspace's customization values.
+ */
+ public Search(Context context, AttributeSet attrs) {
+ super(context, attrs);
+
+ final float scale = context.getResources().getDisplayMetrics().density;
+ mWidgetTopOffset = Math.round(WIDGET_TOP_OFFSET * scale);
+
+ Interpolator interpolator = new AccelerateDecelerateInterpolator();
+
+ mMorphAnimation = new ToParentOriginAnimation();
+ // no need to apply transformation before the animation starts,
+ // since the gadget is already in its normal place.
+ mMorphAnimation.setFillBefore(false);
+ // stay in the top position after the animation finishes
+ mMorphAnimation.setFillAfter(true);
+ mMorphAnimation.setInterpolator(interpolator);
+ mMorphAnimation.setAnimationListener(new Animation.AnimationListener() {
+ // The amount of time before the animation ends to show the search dialog.
+ private static final long TIME_BEFORE_ANIMATION_END = 80;
+
+ // The runnable which we'll pass to our handler to show the search dialog.
+ private final Runnable mShowSearchDialogRunnable = new Runnable() {
+ public void run() {
+ showSearchDialog();
+ }
+ };
+
+ public void onAnimationEnd(Animation animation) { }
+ public void onAnimationRepeat(Animation animation) { }
+ public void onAnimationStart(Animation animation) {
+ // Make the search dialog show up ideally *just* as the animation reaches
+ // the top, to aid the illusion that the widget becomes the search dialog.
+ // Otherwise, there is a short delay when the widget reaches the top before
+ // the search dialog shows. We do this roughly 80ms before the animation ends.
+ getHandler().postDelayed(
+ mShowSearchDialogRunnable,
+ Math.max(mMorphAnimation.getDuration() - TIME_BEFORE_ANIMATION_END, 0));
+ }
+ });
+
+ mUnmorphAnimation = new FromParentOriginAnimation();
+ // stay in the top position until the animation starts
+ mUnmorphAnimation.setFillBefore(true);
+ // no need to apply transformation after the animation finishes,
+ // since the gadget is now back in its normal place.
+ mUnmorphAnimation.setFillAfter(false);
+ mUnmorphAnimation.setInterpolator(interpolator);
+ mUnmorphAnimation.setAnimationListener(new Animation.AnimationListener(){
+ public void onAnimationEnd(Animation animation) {
+ clearAnimation();
+ }
+ public void onAnimationRepeat(Animation animation) { }
+ public void onAnimationStart(Animation animation) { }
+ });
+
+ mVoiceSearchIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
+ mVoiceSearchIntent.putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL,
+ android.speech.RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
+ }
+
+ /**
+ * Implements OnClickListener.
+ */
+ public void onClick(View v) {
+ if (v == mVoiceButton) {
+ startVoiceSearch();
+ } else {
+ mLauncher.onSearchRequested();
+ }
+ }
+
+ private void startVoiceSearch() {
+ try {
+ getContext().startActivity(mVoiceSearchIntent);
+ } catch (ActivityNotFoundException ex) {
+ // Should not happen, since we check the availability of
+ // voice search before showing the button. But just in case...
+ Log.w(TAG, "Could not find voice search activity");
+ }
+ }
+
+ /**
+ * Sets the query text. The query field is not editable, instead we forward
+ * the key events to the launcher, which keeps track of the text,
+ * calls setQuery() to show it, and gives it to the search dialog.
+ */
+ public void setQuery(String query) {
+ mSearchText.setText(query, TextView.BufferType.NORMAL);
+ }
+
+ /**
+ * Morph the search gadget to the search dialog.
+ * See {@link Activity#startSearch()} for the arguments.
+ */
+ public void startSearch(String initialQuery, boolean selectInitialQuery,
+ Bundle appSearchData, boolean globalSearch) {
+ mInitialQuery = initialQuery;
+ mSelectInitialQuery = selectInitialQuery;
+ mAppSearchData = appSearchData;
+ mGlobalSearch = globalSearch;
+
+ if (isAtTop()) {
+ showSearchDialog();
+ } else {
+ // Call up the keyboard before we actually call the search dialog so that it
+ // (hopefully) animates in at about the same time as the widget animation, and
+ // so that it becomes available as soon as possible. Only do this if a hard
+ // keyboard is not currently available.
+ if (getContext().getResources().getConfiguration().hardKeyboardHidden ==
+ Configuration.HARDKEYBOARDHIDDEN_YES) {
+ InputMethodManager inputManager = (InputMethodManager)
+ getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ inputManager.showSoftInputUnchecked(0, null);
+ }
+
+ // Start the animation, unless it has already started.
+ if (getAnimation() != mMorphAnimation) {
+ mMorphAnimation.setDuration(getAnimationDuration());
+ startAnimation(mMorphAnimation);
+ }
+ }
+ }
+
+ /**
+ * Shows the system search dialog immediately, without any animation.
+ */
+ private void showSearchDialog() {
+ mLauncher.showSearchDialog(
+ mInitialQuery, mSelectInitialQuery, mAppSearchData, mGlobalSearch);
+ }
+
+ /**
+ * Restore the search gadget to its normal position.
+ *
+ * @param animate Whether to animate the movement of the gadget.
+ */
+ public void stopSearch(boolean animate) {
+ setQuery("");
+
+ // Only restore if we are not already restored.
+ if (getAnimation() == mMorphAnimation) {
+ if (animate && !isAtTop()) {
+ mUnmorphAnimation.setDuration(getAnimationDuration());
+ startAnimation(mUnmorphAnimation);
+ } else {
+ clearAnimation();
+ }
+ }
+ }
+
+ private boolean isAtTop() {
+ return getWidgetTop() == 0;
+ }
+
+ private int getAnimationDuration() {
+ return (int) (getWidgetTop() / ANIMATION_VELOCITY);
+ }
+
+ /**
+ * Modify clearAnimation() to invalidate the parent. This works around
+ * an issue where the region where the end of the animation placed the view
+ * was not redrawn after clearing the animation.
+ */
+ @Override
+ public void clearAnimation() {
+ Animation animation = getAnimation();
+ if (animation != null) {
+ super.clearAnimation();
+ if (animation.hasEnded()
+ && animation.getFillAfter()
+ && animation.willChangeBounds()) {
+ View parent = (View) getParent();
+ if (parent != null) parent.invalidate();
+ } else {
+ invalidate();
+ }
+ }
+ }
+
+ public boolean onKey(View v, int keyCode, KeyEvent event) {
+ if (!event.isSystem() &&
+ (keyCode != KeyEvent.KEYCODE_DPAD_UP) &&
+ (keyCode != KeyEvent.KEYCODE_DPAD_DOWN) &&
+ (keyCode != KeyEvent.KEYCODE_DPAD_LEFT) &&
+ (keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) &&
+ (keyCode != KeyEvent.KEYCODE_DPAD_CENTER)) {
+ // Forward key events to Launcher, which will forward text
+ // to search dialog
+ switch (event.getAction()) {
+ case KeyEvent.ACTION_DOWN:
+ return mLauncher.onKeyDown(keyCode, event);
+ case KeyEvent.ACTION_MULTIPLE:
+ return mLauncher.onKeyMultiple(keyCode, event.getRepeatCount(), event);
+ case KeyEvent.ACTION_UP:
+ return mLauncher.onKeyUp(keyCode, event);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Implements OnLongClickListener to pass long clicks on child views
+ * to the widget. This makes it possible to pick up the widget by long
+ * clicking on the text field or a button.
+ */
+ public boolean onLongClick(View v) {
+ return performLongClick();
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+
+ mSearchText = (TextView) findViewById(R.id.search_src_text);
+ mVoiceButton = (ImageButton) findViewById(R.id.search_voice_btn);
+
+ mSearchText.setOnKeyListener(this);
+
+ mSearchText.setOnClickListener(this);
+ mVoiceButton.setOnClickListener(this);
+ setOnClickListener(this);
+
+ mSearchText.setOnLongClickListener(this);
+ mVoiceButton.setOnLongClickListener(this);
+
+ // Set the placeholder text to be the Google logo within the search widget.
+ Drawable googlePlaceholder =
+ getContext().getResources().getDrawable(R.drawable.placeholder_google);
+ mSearchText.setCompoundDrawablesWithIntrinsicBounds(googlePlaceholder, null, null, null);
+
+ configureVoiceSearchButton();
+ }
+
+ @Override
+ public void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ }
+
+ /**
+ * If appropriate & available, configure voice search
+ *
+ * Note: Because the home screen search widget is always web search, we only check for
+ * getVoiceSearchLaunchWebSearch() modes. We don't support the alternate form of app-specific
+ * voice search.
+ */
+ private void configureVoiceSearchButton() {
+ // Enable the voice search button if there is an activity that can handle it
+ PackageManager pm = getContext().getPackageManager();
+ ResolveInfo ri = pm.resolveActivity(mVoiceSearchIntent,
+ PackageManager.MATCH_DEFAULT_ONLY);
+ boolean voiceSearchVisible = ri != null;
+
+ // finally, set visible state of voice search button, as appropriate
+ mVoiceButton.setVisibility(voiceSearchVisible ? View.VISIBLE : View.GONE);
+ }
+
+ /**
+ * Sets the {@link Launcher} that this gadget will call on to display the search dialog.
+ */
+ public void setLauncher(Launcher launcher) {
+ mLauncher = launcher;
+ }
+
+ /**
+ * Moves the view to the top left corner of its parent.
+ */
+ private class ToParentOriginAnimation extends Animation {
+ @Override
+ protected void applyTransformation(float interpolatedTime, Transformation t) {
+ float dx = -getLeft() * interpolatedTime;
+ float dy = -getWidgetTop() * interpolatedTime;
+ t.getMatrix().setTranslate(dx, dy);
+ }
+ }
+
+ /**
+ * Moves the view from the top left corner of its parent.
+ */
+ private class FromParentOriginAnimation extends Animation {
+ @Override
+ protected void applyTransformation(float interpolatedTime, Transformation t) {
+ float dx = -getLeft() * (1.0f - interpolatedTime);
+ float dy = -getWidgetTop() * (1.0f - interpolatedTime);
+ t.getMatrix().setTranslate(dx, dy);
+ }
+ }
+
+ /**
+ * The widget is centered vertically within it's 4x1 slot. This is accomplished by nesting
+ * the actual widget inside another view. For animation purposes, we care about the top of the
+ * actual widget rather than it's container. This method return the top of the actual widget.
+ */
+ private int getWidgetTop() {
+ return getTop() + getChildAt(0).getTop() + mWidgetTopOffset;
+ }
+}
diff --git a/src/com/android/launcher2/SymmetricalLinearTween.java b/src/com/android/launcher2/SymmetricalLinearTween.java
new file mode 100644
index 0000000000..2e0ed8f031
--- /dev/null
+++ b/src/com/android/launcher2/SymmetricalLinearTween.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.os.Handler;
+import android.os.Message;
+import android.os.SystemClock;
+import android.util.Log;
+
+/**
+ * Provides an animation between 0.0f and 1.0f over a given duration.
+ */
+class SymmetricalLinearTween {
+
+ private static final int FPS = 30;
+ private static final int FRAME_TIME = 1000 / FPS;
+
+ Handler mHandler;
+ int mDuration;
+ TweenCallback mCallback;
+
+ boolean mRunning;
+ long mBase;
+ boolean mDirection;
+ float mValue;
+
+ /**
+ * @param duration milliseconds duration
+ * @param callback callbacks
+ */
+ public SymmetricalLinearTween(boolean initial, int duration, TweenCallback callback) {
+ mValue = initial ? 1.0f : 0.0f;
+ mDirection = initial;
+ mDuration = duration;
+ mCallback = callback;
+ mHandler = new Handler();
+ }
+
+ /**
+ * Starts the tweening.
+ *
+ * @param direction If direction is true, the value goes towards 1.0f. If direction
+ * is false, the value goes towards 0.0f.
+ */
+ public void start(boolean direction) {
+ start(direction, SystemClock.uptimeMillis());
+ }
+
+ /**
+ * Starts the tweening.
+ *
+ * @param direction If direction is true, the value goes towards 1.0f. If direction
+ * is false, the value goes towards 0.0f.
+ * @param baseTime The time to use as zero for this animation, in the
+ * {@link SystemClock.uptimeMillis} time base. This allows you to
+ * synchronize multiple animations.
+ */
+ public void start(boolean direction, long baseTime) {
+ if (direction != mDirection) {
+ if (!mRunning) {
+ mBase = baseTime;
+ mRunning = true;
+ mCallback.onTweenStarted();
+ long next = SystemClock.uptimeMillis() + FRAME_TIME;
+ mHandler.postAtTime(mTick, next);
+ } else {
+ // reverse direction
+ long now = SystemClock.uptimeMillis();
+ long diff = now - mBase;
+ mBase = now + diff - mDuration;
+ }
+ mDirection = direction;
+ }
+ }
+
+ Runnable mTick = new Runnable() {
+ public void run() {
+ long base = mBase;
+ long now = SystemClock.uptimeMillis();
+ long diff = now-base;
+ int duration = mDuration;
+ float val = diff/(float)duration;
+ if (!mDirection) {
+ val = 1.0f - val;
+ }
+ if (val > 1.0f) {
+ val = 1.0f;
+ } else if (val < 0.0f) {
+ val = 0.0f;
+ }
+ float old = mValue;
+ mValue = val;
+ mCallback.onTweenValueChanged(val, old);
+ int frame = (int)(diff / FRAME_TIME);
+ long next = base + ((frame+1)*FRAME_TIME);
+ if (diff < duration) {
+ mHandler.postAtTime(this, next);
+ }
+ if (diff >= duration) {
+ mCallback.onTweenFinished();
+ mRunning = false;
+ }
+ }
+ };
+}
+
diff --git a/src/com/android/launcher2/TweenCallback.java b/src/com/android/launcher2/TweenCallback.java
new file mode 100644
index 0000000000..380a21774d
--- /dev/null
+++ b/src/com/android/launcher2/TweenCallback.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+interface TweenCallback {
+ void onTweenValueChanged(float value, float oldValue);
+ void onTweenStarted();
+ void onTweenFinished();
+}
+
diff --git a/src/com/android/launcher2/UninstallShortcutReceiver.java b/src/com/android/launcher2/UninstallShortcutReceiver.java
new file mode 100644
index 0000000000..e65c6a039a
--- /dev/null
+++ b/src/com/android/launcher2/UninstallShortcutReceiver.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ContentResolver;
+import android.database.Cursor;
+import android.net.Uri;
+import android.widget.Toast;
+
+import java.net.URISyntaxException;
+
+public class UninstallShortcutReceiver extends BroadcastReceiver {
+ private static final String ACTION_UNINSTALL_SHORTCUT =
+ "com.android.launcher.action.UNINSTALL_SHORTCUT";
+
+ public void onReceive(Context context, Intent data) {
+ if (!ACTION_UNINSTALL_SHORTCUT.equals(data.getAction())) {
+ return;
+ }
+
+ Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
+ String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
+ boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
+
+ if (intent != null && name != null) {
+ final ContentResolver cr = context.getContentResolver();
+ Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.INTENT },
+ LauncherSettings.Favorites.TITLE + "=?", new String[] { name }, null);
+
+ final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
+ final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+
+ boolean changed = false;
+
+ try {
+ while (c.moveToNext()) {
+ try {
+ if (intent.filterEquals(Intent.parseUri(c.getString(intentIndex), 0))) {
+ final long id = c.getLong(idIndex);
+ final Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
+ cr.delete(uri, null, null);
+ changed = true;
+ if (!duplicate) {
+ break;
+ }
+ }
+ } catch (URISyntaxException e) {
+ // Ignore
+ }
+ }
+ } finally {
+ c.close();
+ }
+
+ if (changed) {
+ cr.notifyChange(LauncherSettings.Favorites.CONTENT_URI, null);
+ Toast.makeText(context, context.getString(R.string.shortcut_uninstalled, name),
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+}
diff --git a/src/com/android/launcher2/UserFolder.java b/src/com/android/launcher2/UserFolder.java
new file mode 100644
index 0000000000..16fe6160ce
--- /dev/null
+++ b/src/com/android/launcher2/UserFolder.java
@@ -0,0 +1,93 @@
+package com.android.launcher2;
+
+import android.content.Context;
+import android.graphics.Rect;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.ArrayAdapter;
+
+/**
+ * Folder which contains applications or shortcuts chosen by the user.
+ *
+ */
+public class UserFolder extends Folder implements DropTarget {
+ private static final String TAG = "Launcher.UserFolder";
+
+ public UserFolder(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ /**
+ * Creates a new UserFolder, inflated from R.layout.user_folder.
+ *
+ * @param context The application's context.
+ *
+ * @return A new UserFolder.
+ */
+ static UserFolder fromXml(Context context) {
+ return (UserFolder) LayoutInflater.from(context).inflate(R.layout.user_folder, null);
+ }
+
+ public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ final ItemInfo item = (ItemInfo) dragInfo;
+ final int itemType = item.itemType;
+ return (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
+ itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT)
+ && item.container != mInfo.id;
+ }
+
+ public Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo, Rect recycle) {
+ return null;
+ }
+
+ public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ ApplicationInfo item = (ApplicationInfo) dragInfo;
+ if (item.container == NO_ID) {
+ // Came from all apps -- make a copy
+ item = new ApplicationInfo((ApplicationInfo)item);
+ }
+ //noinspection unchecked
+ ((ArrayAdapter) mContent.getAdapter()).add((ApplicationInfo) dragInfo);
+ LauncherModel.addOrMoveItemInDatabase(mLauncher, item, mInfo.id, 0, 0, 0);
+ }
+
+ public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ @Override
+ public void onDropCompleted(View target, boolean success) {
+ if (success) {
+ //noinspection unchecked
+ ArrayAdapter adapter =
+ (ArrayAdapter) mContent.getAdapter();
+ adapter.remove(mDragItem);
+ }
+ }
+
+ void bind(FolderInfo info) {
+ super.bind(info);
+ setContentAdapter(new ApplicationsAdapter(mContext, ((UserFolderInfo) info).contents));
+ }
+
+ // When the folder opens, we need to refresh the GridView's selection by
+ // forcing a layout
+ @Override
+ void onOpen() {
+ super.onOpen();
+ requestFocus();
+ }
+}
diff --git a/src/com/android/launcher2/UserFolderInfo.java b/src/com/android/launcher2/UserFolderInfo.java
new file mode 100644
index 0000000000..75b19eec66
--- /dev/null
+++ b/src/com/android/launcher2/UserFolderInfo.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.ContentValues;
+
+import java.util.ArrayList;
+
+/**
+ * Represents a folder containing shortcuts or apps.
+ */
+class UserFolderInfo extends FolderInfo {
+ /**
+ * The apps and shortcuts
+ */
+ ArrayList contents = new ArrayList();
+
+ UserFolderInfo() {
+ itemType = LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER;
+ }
+
+ /**
+ * Add an app or shortcut
+ *
+ * @param item
+ */
+ public void add(ApplicationInfo item) {
+ contents.add(item);
+ }
+
+ /**
+ * Remove an app or shortcut. Does not change the DB.
+ *
+ * @param item
+ */
+ public void remove(ApplicationInfo item) {
+ contents.remove(item);
+ }
+
+ @Override
+ void onAddToDatabase(ContentValues values) {
+ super.onAddToDatabase(values);
+ values.put(LauncherSettings.Favorites.TITLE, title.toString());
+ }
+}
diff --git a/src/com/android/launcher2/Utilities.java b/src/com/android/launcher2/Utilities.java
new file mode 100644
index 0000000000..55cb509bcd
--- /dev/null
+++ b/src/com/android/launcher2/Utilities.java
@@ -0,0 +1,484 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.PaintDrawable;
+import android.graphics.Bitmap;
+import android.graphics.BlurMaskFilter;
+import android.graphics.Canvas;
+import android.graphics.MaskFilter;
+import android.graphics.Paint;
+import android.graphics.PaintFlagsDrawFilter;
+import android.graphics.PixelFormat;
+import android.graphics.PorterDuff;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.TableMaskFilter;
+import android.graphics.Typeface;
+import android.text.Layout.Alignment;
+import android.text.StaticLayout;
+import android.text.TextPaint;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.content.res.Resources;
+import android.content.Context;
+
+/**
+ * Various utilities shared amongst the Launcher's classes.
+ */
+final class Utilities {
+ private static final String TAG = "Launcher.Utilities";
+
+ private static final boolean TEXT_BURN = false;
+
+ private static int sIconWidth = -1;
+ private static int sIconHeight = -1;
+ private static int sIconTextureWidth = -1;
+ private static int sIconTextureHeight = -1;
+
+ private static final Paint sPaint = new Paint();
+ private static final Paint sBlurPaint = new Paint();
+ private static final Paint sGlowColorPressedPaint = new Paint();
+ private static final Paint sGlowColorFocusedPaint = new Paint();
+ private static final Paint sEmptyPaint = new Paint();
+ private static final Rect sBounds = new Rect();
+ private static final Rect sOldBounds = new Rect();
+ private static final Canvas sCanvas = new Canvas();
+
+ static {
+ sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
+ Paint.FILTER_BITMAP_FLAG));
+ }
+
+ static Bitmap centerToFit(Bitmap bitmap, int width, int height, Context context) {
+ final int bitmapWidth = bitmap.getWidth();
+ final int bitmapHeight = bitmap.getHeight();
+
+ if (bitmapWidth < width || bitmapHeight < height) {
+ int color = context.getResources().getColor(R.color.window_background);
+
+ Bitmap centered = Bitmap.createBitmap(bitmapWidth < width ? width : bitmapWidth,
+ bitmapHeight < height ? height : bitmapHeight, Bitmap.Config.RGB_565);
+ centered.setDensity(bitmap.getDensity());
+ Canvas canvas = new Canvas(centered);
+ canvas.drawColor(color);
+ canvas.drawBitmap(bitmap, (width - bitmapWidth) / 2.0f, (height - bitmapHeight) / 2.0f,
+ null);
+
+ bitmap = centered;
+ }
+
+ return bitmap;
+ }
+
+ /**
+ * Returns a Drawable representing the thumbnail of the specified Drawable.
+ * The size of the thumbnail is defined by the dimension
+ * android.R.dimen.launcher_application_icon_size.
+ *
+ * @param icon The icon to get a thumbnail of.
+ * @param context The application's context.
+ *
+ * @return A thumbnail for the specified icon or the icon itself if the
+ * thumbnail could not be created.
+ */
+ static Drawable createIconThumbnail(Drawable icon, Context context) {
+ synchronized (sCanvas) { // we share the statics :-(
+ if (sIconWidth == -1) {
+ initStatics(context);
+ }
+
+ int width = sIconWidth;
+ int height = sIconHeight;
+
+ if (icon instanceof PaintDrawable) {
+ PaintDrawable painter = (PaintDrawable) icon;
+ painter.setIntrinsicWidth(width);
+ painter.setIntrinsicHeight(height);
+ } else if (icon instanceof BitmapDrawable) {
+ // Ensure the bitmap has a density.
+ BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
+ Bitmap bitmap = bitmapDrawable.getBitmap();
+ if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
+ bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
+ }
+ }
+ int iconWidth = icon.getIntrinsicWidth();
+ int iconHeight = icon.getIntrinsicHeight();
+
+ if (iconWidth > 0 && iconHeight > 0) {
+ if (width < iconWidth || height < iconHeight) {
+ final float ratio = (float) iconWidth / iconHeight;
+
+ if (iconWidth > iconHeight) {
+ height = (int) (width / ratio);
+ } else if (iconHeight > iconWidth) {
+ width = (int) (height * ratio);
+ }
+
+ final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ?
+ Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
+ final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
+ final Canvas canvas = sCanvas;
+ canvas.setBitmap(thumb);
+ // Copy the old bounds to restore them later
+ // If we were to do oldBounds = icon.getBounds(),
+ // the call to setBounds() that follows would
+ // change the same instance and we would lose the
+ // old bounds
+ sOldBounds.set(icon.getBounds());
+ final int x = (sIconWidth - width) / 2;
+ final int y = (sIconHeight - height) / 2;
+ icon.setBounds(x, y, x + width, y + height);
+ icon.draw(canvas);
+ icon.setBounds(sOldBounds);
+ icon = new FastBitmapDrawable(thumb);
+ } else if (iconWidth < width && iconHeight < height) {
+ final Bitmap.Config c = Bitmap.Config.ARGB_8888;
+ final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
+ final Canvas canvas = sCanvas;
+ canvas.setBitmap(thumb);
+ sOldBounds.set(icon.getBounds());
+ final int x = (width - iconWidth) / 2;
+ final int y = (height - iconHeight) / 2;
+ icon.setBounds(x, y, x + iconWidth, y + iconHeight);
+ icon.draw(canvas);
+ icon.setBounds(sOldBounds);
+ icon = new FastBitmapDrawable(thumb);
+ }
+ }
+
+ return icon;
+ }
+ }
+
+ static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
+ static int sColorIndex = 0;
+
+ /**
+ * Returns a bitmap suitable for the all apps view. The bitmap will be a power
+ * of two sized ARGB_8888 bitmap that can be used as a gl texture.
+ */
+ static Bitmap createAllAppsBitmap(Drawable icon, Context context) {
+ synchronized (sCanvas) { // we share the statics :-(
+ if (sIconWidth == -1) {
+ initStatics(context);
+ }
+
+ int width = sIconWidth;
+ int height = sIconHeight;
+
+ if (icon instanceof PaintDrawable) {
+ PaintDrawable painter = (PaintDrawable) icon;
+ painter.setIntrinsicWidth(width);
+ painter.setIntrinsicHeight(height);
+ } else if (icon instanceof BitmapDrawable) {
+ // Ensure the bitmap has a density.
+ BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
+ Bitmap bitmap = bitmapDrawable.getBitmap();
+ if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
+ bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
+ }
+ }
+ int sourceWidth = icon.getIntrinsicWidth();
+ int sourceHeight = icon.getIntrinsicHeight();
+
+ if (sourceWidth > 0 && sourceWidth > 0) {
+ // There are intrinsic sizes.
+ if (width < sourceWidth || height < sourceHeight) {
+ // It's too big, scale it down.
+ final float ratio = (float) sourceWidth / sourceHeight;
+ if (sourceWidth > sourceHeight) {
+ height = (int) (width / ratio);
+ } else if (sourceHeight > sourceWidth) {
+ width = (int) (height * ratio);
+ }
+ } else if (sourceWidth < width && sourceHeight < height) {
+ // It's small, use the size they gave us.
+ width = sourceWidth;
+ height = sourceHeight;
+ }
+ }
+
+ // no intrinsic size --> use default size
+ int textureWidth = sIconTextureWidth;
+ int textureHeight = sIconTextureHeight;
+
+ final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
+ Bitmap.Config.ARGB_8888);
+ final Canvas canvas = sCanvas;
+ canvas.setBitmap(bitmap);
+
+ final int left = (textureWidth-width) / 2;
+ final int top = (textureHeight-height) / 2;
+
+ if (false) {
+ // draw a big box for the icon for debugging
+ canvas.drawColor(sColors[sColorIndex]);
+ if (++sColorIndex >= sColors.length) sColorIndex = 0;
+ Paint debugPaint = new Paint();
+ debugPaint.setColor(0xffcccc00);
+ canvas.drawRect(left, top, left+width, top+height, debugPaint);
+ }
+
+ sOldBounds.set(icon.getBounds());
+ icon.setBounds(left, top, left+width, top+height);
+ icon.draw(canvas);
+ icon.setBounds(sOldBounds);
+
+ return bitmap;
+ }
+ }
+
+ static void drawSelectedAllAppsBitmap(Canvas dest, int destWidth, int destHeight,
+ boolean pressed, Bitmap src) {
+ synchronized (sCanvas) { // we share the statics :-(
+ if (sIconWidth == -1) {
+ // We can't have gotten to here without src being initialized, which
+ // comes from this file already. So just assert.
+ //initStatics(context);
+ throw new RuntimeException("Assertion failed: Utilities not initialized");
+ }
+
+ dest.drawColor(0, PorterDuff.Mode.CLEAR);
+
+ int[] xy = new int[2];
+ Bitmap mask = src.extractAlpha(sBlurPaint, xy);
+
+ float px = (destWidth - src.getWidth()) / 2;
+ float py = (destHeight - src.getHeight()) / 2;
+ dest.drawBitmap(mask, px + xy[0], py + xy[1],
+ pressed ? sGlowColorPressedPaint : sGlowColorFocusedPaint);
+
+ mask.recycle();
+ }
+ }
+
+ /**
+ * Returns a Bitmap representing the thumbnail of the specified Bitmap.
+ * The size of the thumbnail is defined by the dimension
+ * android.R.dimen.launcher_application_icon_size.
+ *
+ * @param bitmap The bitmap to get a thumbnail of.
+ * @param context The application's context.
+ *
+ * @return A thumbnail for the specified bitmap or the bitmap itself if the
+ * thumbnail could not be created.
+ */
+ static Bitmap createBitmapThumbnail(Bitmap bitmap, Context context) {
+ synchronized (sCanvas) { // we share the statics :-(
+ if (sIconWidth == -1) {
+ initStatics(context);
+ }
+
+ int width = sIconWidth;
+ int height = sIconHeight;
+
+ final int bitmapWidth = bitmap.getWidth();
+ final int bitmapHeight = bitmap.getHeight();
+
+ if (width > 0 && height > 0) {
+ if (width < bitmapWidth || height < bitmapHeight) {
+ final float ratio = (float) bitmapWidth / bitmapHeight;
+
+ if (bitmapWidth > bitmapHeight) {
+ height = (int) (width / ratio);
+ } else if (bitmapHeight > bitmapWidth) {
+ width = (int) (height * ratio);
+ }
+
+ final Bitmap.Config c = (width == sIconWidth && height == sIconHeight) ?
+ bitmap.getConfig() : Bitmap.Config.ARGB_8888;
+ final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
+ final Canvas canvas = sCanvas;
+ final Paint paint = sPaint;
+ canvas.setBitmap(thumb);
+ paint.setDither(false);
+ paint.setFilterBitmap(true);
+ sBounds.set((sIconWidth - width) / 2, (sIconHeight - height) / 2, width, height);
+ sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);
+ canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);
+ return thumb;
+ } else if (bitmapWidth < width || bitmapHeight < height) {
+ final Bitmap.Config c = Bitmap.Config.ARGB_8888;
+ final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
+ final Canvas canvas = sCanvas;
+ final Paint paint = sPaint;
+ canvas.setBitmap(thumb);
+ paint.setDither(false);
+ paint.setFilterBitmap(true);
+ canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2,
+ (sIconHeight - bitmapHeight) / 2, paint);
+ return thumb;
+ }
+ }
+
+ return bitmap;
+ }
+ }
+
+ private static void initStatics(Context context) {
+ final Resources resources = context.getResources();
+ final DisplayMetrics metrics = resources.getDisplayMetrics();
+ final float density = metrics.density;
+
+ sIconWidth = sIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);
+ sIconTextureWidth = sIconTextureHeight = roundToPow2(sIconWidth);
+
+ sBlurPaint.setMaskFilter(new BlurMaskFilter(5 * density, BlurMaskFilter.Blur.NORMAL));
+ sGlowColorPressedPaint.setColor(0xffffc300);
+ sGlowColorPressedPaint.setMaskFilter(TableMaskFilter.CreateClipTable(0, 30));
+ sGlowColorFocusedPaint.setColor(0xffff8e00);
+ sGlowColorFocusedPaint.setMaskFilter(TableMaskFilter.CreateClipTable(0, 30));
+ }
+
+ static class BubbleText {
+ private static final int MAX_LINES = 2;
+ private TextPaint mTextPaint;
+
+ private float mBubblePadding;
+ private RectF mBubbleRect = new RectF();
+
+ private float mTextWidth;
+ private int mLeading;
+ private int mFirstLineY;
+ private int mLineHeight;
+
+ private int mBitmapWidth;
+ private int mBitmapHeight;
+
+ BubbleText(Context context) {
+ final Resources resources = context.getResources();
+
+ final float scale = resources.getDisplayMetrics().density;
+
+ final float paddingLeft = 5.0f * scale;
+ final float paddingRight = 5.0f * scale;
+ final float cellWidth = resources.getDimension(R.dimen.workspace_cell_width);
+ final float bubbleWidth = cellWidth - paddingLeft - paddingRight;
+ mBubblePadding = 3.0f * scale;
+
+ RectF bubbleRect = mBubbleRect;
+ bubbleRect.left = 0;
+ bubbleRect.top = 0;
+ bubbleRect.right = (int)(bubbleWidth+0.5f);
+
+ mTextWidth = bubbleWidth - mBubblePadding - mBubblePadding;
+
+ Paint rectPaint = new Paint();
+ rectPaint.setColor(0xff000000);
+ rectPaint.setAntiAlias(true);
+
+ TextPaint textPaint = mTextPaint = new TextPaint();
+ textPaint.setTypeface(Typeface.DEFAULT);
+ textPaint.setTextSize(13*scale);
+ textPaint.setColor(0xffffffff);
+ textPaint.setAntiAlias(true);
+ if (TEXT_BURN) {
+ textPaint.setShadowLayer(8, 0, 0, 0xff000000);
+ }
+
+ float ascent = -textPaint.ascent();
+ float descent = textPaint.descent();
+ float leading = 0.0f;//(ascent+descent) * 0.1f;
+ mLeading = (int)(leading + 0.5f);
+ mFirstLineY = (int)(leading + ascent + 0.5f);
+ mLineHeight = (int)(leading + ascent + descent + 0.5f);
+
+ mBitmapWidth = roundToPow2((int)(mBubbleRect.width() + 0.5f));
+ mBitmapHeight = roundToPow2((int)((MAX_LINES * mLineHeight) + leading + 0.5f));
+
+ mBubbleRect.offsetTo((mBitmapWidth-mBubbleRect.width())/2, 0);
+
+ if (false) {
+ Log.d(TAG, "mBitmapWidth=" + mBitmapWidth + " mBitmapHeight="
+ + mBitmapHeight + " w=" + ((int)(mBubbleRect.width() + 0.5f))
+ + " h=" + ((int)((MAX_LINES * mLineHeight) + leading + 0.5f)));
+ }
+ }
+
+ /** You own the bitmap after this and you must call recycle on it. */
+ Bitmap createTextBitmap(String text) {
+ Bitmap b = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
+ Canvas c = new Canvas(b);
+
+ StaticLayout layout = new StaticLayout(text, mTextPaint, (int)mTextWidth,
+ Alignment.ALIGN_CENTER, 1, 0, true);
+ int lineCount = layout.getLineCount();
+ if (lineCount > MAX_LINES) {
+ lineCount = MAX_LINES;
+ }
+ //if (!TEXT_BURN && lineCount > 0) {
+ //RectF bubbleRect = mBubbleRect;
+ //bubbleRect.bottom = height(lineCount);
+ //c.drawRoundRect(bubbleRect, mCornerRadius, mCornerRadius, mRectPaint);
+ //}
+ for (int i=0; i>= 1;
+ int mask = 0x8000000;
+ while (mask != 0 && (n & mask) == 0) {
+ mask >>= 1;
+ }
+ while (mask != 0) {
+ n |= mask;
+ mask >>= 1;
+ }
+ n += 1;
+ if (n != orig) {
+ n <<= 1;
+ }
+ return n;
+ }
+}
diff --git a/src/com/android/launcher2/WallpaperChooser.java b/src/com/android/launcher2/WallpaperChooser.java
new file mode 100644
index 0000000000..8045059e78
--- /dev/null
+++ b/src/com/android/launcher2/WallpaperChooser.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.app.Activity;
+import android.app.WallpaperManager;
+import android.content.res.Resources;
+import android.graphics.BitmapFactory;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.os.AsyncTask;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.Window;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.BaseAdapter;
+import android.widget.Gallery;
+import android.widget.ImageView;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class WallpaperChooser extends Activity implements AdapterView.OnItemSelectedListener,
+ OnClickListener {
+ private static final String TAG = "Launcher.WallpaperChooser";
+
+ private Gallery mGallery;
+ private ImageView mImageView;
+ private boolean mIsWallpaperSet;
+
+ private Bitmap mBitmap;
+
+ private ArrayList mThumbs;
+ private ArrayList mImages;
+ private WallpaperLoader mLoader;
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
+
+ findWallpapers();
+
+ setContentView(R.layout.wallpaper_chooser);
+
+ mGallery = (Gallery) findViewById(R.id.gallery);
+ mGallery.setAdapter(new ImageAdapter(this));
+ mGallery.setOnItemSelectedListener(this);
+ mGallery.setCallbackDuringFling(false);
+
+ findViewById(R.id.set).setOnClickListener(this);
+
+ mImageView = (ImageView) findViewById(R.id.wallpaper);
+ }
+
+ private void findWallpapers() {
+ mThumbs = new ArrayList(24);
+ mImages = new ArrayList(24);
+
+ final Resources resources = getResources();
+ final String packageName = getApplication().getPackageName();
+
+ addWallpapers(resources, packageName, R.array.wallpapers);
+ addWallpapers(resources, packageName, R.array.extra_wallpapers);
+ }
+
+ private void addWallpapers(Resources resources, String packageName, int list) {
+ final String[] extras = resources.getStringArray(list);
+ for (String extra : extras) {
+ int res = resources.getIdentifier(extra, "drawable", packageName);
+ if (res != 0) {
+ final int thumbRes = resources.getIdentifier(extra + "_small",
+ "drawable", packageName);
+
+ if (thumbRes != 0) {
+ mThumbs.add(thumbRes);
+ mImages.add(res);
+ }
+ }
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ mIsWallpaperSet = false;
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+
+ if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
+ mLoader.cancel(true);
+ mLoader = null;
+ }
+ }
+
+ public void onItemSelected(AdapterView parent, View v, int position, long id) {
+ if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
+ mLoader.cancel();
+ }
+ mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
+ }
+
+ /*
+ * When using touch if you tap an image it triggers both the onItemClick and
+ * the onTouchEvent causing the wallpaper to be set twice. Ensure we only
+ * set the wallpaper once.
+ */
+ private void selectWallpaper(int position) {
+ if (mIsWallpaperSet) {
+ return;
+ }
+
+ mIsWallpaperSet = true;
+ try {
+ WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
+ wpm.setResource(mImages.get(position));
+ setResult(RESULT_OK);
+ finish();
+ } catch (IOException e) {
+ Log.e(TAG, "Failed to set wallpaper: " + e);
+ }
+ }
+
+ public void onNothingSelected(AdapterView parent) {
+ }
+
+ private class ImageAdapter extends BaseAdapter {
+ private LayoutInflater mLayoutInflater;
+
+ ImageAdapter(WallpaperChooser context) {
+ mLayoutInflater = context.getLayoutInflater();
+ }
+
+ public int getCount() {
+ return mThumbs.size();
+ }
+
+ public Object getItem(int position) {
+ return position;
+ }
+
+ public long getItemId(int position) {
+ return position;
+ }
+
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ImageView image;
+
+ if (convertView == null) {
+ image = (ImageView) mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
+ } else {
+ image = (ImageView) convertView;
+ }
+
+ int thumbRes = mThumbs.get(position);
+ image.setImageResource(thumbRes);
+ Drawable thumbDrawable = image.getDrawable();
+ if (thumbDrawable != null) {
+ thumbDrawable.setDither(true);
+ } else {
+ Log.e(TAG, "Error decoding thumbnail resId=" + thumbRes + " for wallpaper #"
+ + position);
+ }
+ return image;
+ }
+ }
+
+ public void onClick(View v) {
+ selectWallpaper(mGallery.getSelectedItemPosition());
+ }
+
+ class WallpaperLoader extends AsyncTask {
+ BitmapFactory.Options mOptions;
+
+ WallpaperLoader() {
+ mOptions = new BitmapFactory.Options();
+ mOptions.inDither = false;
+ mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
+ }
+
+ protected Bitmap doInBackground(Integer... params) {
+ if (isCancelled()) return null;
+ try {
+ return BitmapFactory.decodeResource(getResources(),
+ mImages.get(params[0]), mOptions);
+ } catch (OutOfMemoryError e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected void onPostExecute(Bitmap b) {
+ if (b == null) return;
+
+ if (!isCancelled() && !mOptions.mCancel) {
+ // Help the GC
+ if (mBitmap != null) {
+ mBitmap.recycle();
+ }
+
+ final ImageView view = mImageView;
+ view.setImageBitmap(b);
+
+ mBitmap = b;
+
+ final Drawable drawable = view.getDrawable();
+ drawable.setFilterBitmap(true);
+ drawable.setDither(true);
+
+ view.postInvalidate();
+
+ mLoader = null;
+ } else {
+ b.recycle();
+ }
+ }
+
+ void cancel() {
+ mOptions.requestCancelDecode();
+ super.cancel(true);
+ }
+ }
+}
diff --git a/src/com/android/launcher2/Widget.java b/src/com/android/launcher2/Widget.java
new file mode 100644
index 0000000000..348acee7cb
--- /dev/null
+++ b/src/com/android/launcher2/Widget.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.content.ContentValues;
+import android.graphics.Bitmap;
+
+/**
+ * Represents one instance of a Launcher widget, such as search.
+ */
+class Widget extends ItemInfo {
+ int layoutResource;
+
+ static Widget makeSearch() {
+ Widget w = new Widget();
+ w.itemType = LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH;
+ w.spanX = 4;
+ w.spanY = 1;
+ w.layoutResource = R.layout.widget_search;
+ return w;
+ }
+}
diff --git a/src/com/android/launcher2/Workspace.java b/src/com/android/launcher2/Workspace.java
new file mode 100644
index 0000000000..374f0bf56d
--- /dev/null
+++ b/src/com/android/launcher2/Workspace.java
@@ -0,0 +1,1475 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 com.android.launcher2;
+
+import android.app.WallpaperManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ComponentName;
+import android.content.res.TypedArray;
+import android.content.pm.PackageManager;
+import android.graphics.Canvas;
+import android.graphics.RectF;
+import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
+import android.os.Parcelable;
+import android.os.Parcel;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.ViewConfiguration;
+import android.view.ViewGroup;
+import android.view.ViewParent;
+import android.widget.Scroller;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+
+/**
+ * The workspace is a wide area with a wallpaper and a finite number of screens. Each
+ * screen contains a number of icons, folders or widgets the user can interact with.
+ * A workspace is meant to be used with a fixed width only.
+ */
+public class Workspace extends ViewGroup implements DropTarget, DragSource, DragScroller {
+ @SuppressWarnings({"UnusedDeclaration"})
+ private static final String TAG = "Launcher.Workspace";
+ private static final int INVALID_SCREEN = -1;
+
+ /**
+ * The velocity at which a fling gesture will cause us to snap to the next screen
+ */
+ private static final int SNAP_VELOCITY = 1000;
+
+ private final WallpaperManager mWallpaperManager;
+
+ private int mDefaultScreen;
+
+ private boolean mFirstLayout = true;
+
+ private int mCurrentScreen;
+ private int mNextScreen = INVALID_SCREEN;
+ private Scroller mScroller;
+ private VelocityTracker mVelocityTracker;
+
+ /**
+ * CellInfo for the cell that is currently being dragged
+ */
+ private CellLayout.CellInfo mDragInfo;
+
+ /**
+ * Target drop area calculated during last acceptDrop call.
+ */
+ private int[] mTargetCell = null;
+
+ private float mLastMotionX;
+ private float mLastMotionY;
+
+ private final static int TOUCH_STATE_REST = 0;
+ private final static int TOUCH_STATE_SCROLLING = 1;
+
+ private int mTouchState = TOUCH_STATE_REST;
+
+ private OnLongClickListener mLongClickListener;
+
+ private Launcher mLauncher;
+ private DragController mDragController;
+
+ /**
+ * Cache of vacant cells, used during drag events and invalidated as needed.
+ */
+ private CellLayout.CellInfo mVacantCache = null;
+
+ private int[] mTempCell = new int[2];
+ private int[] mTempEstimate = new int[2];
+
+ private boolean mAllowLongPress = true;
+
+ private int mTouchSlop;
+ private int mMaximumVelocity;
+
+ final Rect mDrawerBounds = new Rect();
+ final Rect mClipBounds = new Rect();
+ int mDrawerContentHeight;
+ int mDrawerContentWidth;
+
+ private Drawable mPreviousIndicator;
+ private Drawable mNextIndicator;
+
+ private boolean mFading = true;
+
+ /**
+ * Used to inflate the Workspace from XML.
+ *
+ * @param context The application's context.
+ * @param attrs The attribtues set containing the Workspace's customization values.
+ */
+ public Workspace(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ /**
+ * Used to inflate the Workspace from XML.
+ *
+ * @param context The application's context.
+ * @param attrs The attribtues set containing the Workspace's customization values.
+ * @param defStyle Unused.
+ */
+ public Workspace(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+
+ mWallpaperManager = WallpaperManager.getInstance(context);
+
+ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Workspace, defStyle, 0);
+ mDefaultScreen = a.getInt(R.styleable.Workspace_defaultScreen, 1);
+ a.recycle();
+
+ setHapticFeedbackEnabled(false);
+ initWorkspace();
+ }
+
+ /**
+ * Initializes various states for this workspace.
+ */
+ private void initWorkspace() {
+ mScroller = new Scroller(getContext());
+ mCurrentScreen = mDefaultScreen;
+ Launcher.setScreen(mCurrentScreen);
+
+ final ViewConfiguration configuration = ViewConfiguration.get(getContext());
+ mTouchSlop = configuration.getScaledTouchSlop();
+ mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
+ }
+
+ @Override
+ public void addView(View child, int index, LayoutParams params) {
+ if (!(child instanceof CellLayout)) {
+ throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
+ }
+ super.addView(child, index, params);
+ }
+
+ @Override
+ public void addView(View child) {
+ if (!(child instanceof CellLayout)) {
+ throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
+ }
+ super.addView(child);
+ }
+
+ @Override
+ public void addView(View child, int index) {
+ if (!(child instanceof CellLayout)) {
+ throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
+ }
+ super.addView(child, index);
+ }
+
+ @Override
+ public void addView(View child, int width, int height) {
+ if (!(child instanceof CellLayout)) {
+ throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
+ }
+ super.addView(child, width, height);
+ }
+
+ @Override
+ public void addView(View child, LayoutParams params) {
+ if (!(child instanceof CellLayout)) {
+ throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
+ }
+ super.addView(child, params);
+ }
+
+ /**
+ * @return The open folder on the current screen, or null if there is none
+ */
+ Folder getOpenFolder() {
+ CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
+ int count = currentScreen.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View child = currentScreen.getChildAt(i);
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
+ if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
+ return (Folder) child;
+ }
+ }
+ return null;
+ }
+
+ ArrayList getOpenFolders() {
+ final int screens = getChildCount();
+ ArrayList folders = new ArrayList(screens);
+
+ for (int screen = 0; screen < screens; screen++) {
+ CellLayout currentScreen = (CellLayout) getChildAt(screen);
+ int count = currentScreen.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View child = currentScreen.getChildAt(i);
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
+ if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
+ folders.add((Folder) child);
+ break;
+ }
+ }
+ }
+
+ return folders;
+ }
+
+ boolean isDefaultScreenShowing() {
+ return mCurrentScreen == mDefaultScreen;
+ }
+
+ /**
+ * Returns the index of the currently displayed screen.
+ *
+ * @return The index of the currently displayed screen.
+ */
+ int getCurrentScreen() {
+ return mCurrentScreen;
+ }
+
+ /**
+ * Returns how many screens there are.
+ */
+ int getScreenCount() {
+ return getChildCount();
+ }
+
+ /**
+ * Computes a bounding rectangle for a range of cells
+ *
+ * @param cellX X coordinate of upper left corner expressed as a cell position
+ * @param cellY Y coordinate of upper left corner expressed as a cell position
+ * @param cellHSpan Width in cells
+ * @param cellVSpan Height in cells
+ * @param rect Rectnagle into which to put the results
+ */
+ public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF rect) {
+ ((CellLayout)getChildAt(mCurrentScreen)).cellToRect(cellX, cellY,
+ cellHSpan, cellVSpan, rect);
+ }
+
+ /**
+ * Sets the current screen.
+ *
+ * @param currentScreen
+ */
+ void setCurrentScreen(int currentScreen) {
+ clearVacantCache();
+ mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
+ scrollTo(mCurrentScreen * getWidth(), 0);
+ invalidate();
+ }
+
+ /**
+ * Adds the specified child in the current screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param x The X position of the child in the screen's grid.
+ * @param y The Y position of the child in the screen's grid.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ */
+ void addInCurrentScreen(View child, int x, int y, int spanX, int spanY) {
+ addInScreen(child, mCurrentScreen, x, y, spanX, spanY, false);
+ }
+
+ /**
+ * Adds the specified child in the current screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param x The X position of the child in the screen's grid.
+ * @param y The Y position of the child in the screen's grid.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ * @param insert When true, the child is inserted at the beginning of the children list.
+ */
+ void addInCurrentScreen(View child, int x, int y, int spanX, int spanY, boolean insert) {
+ addInScreen(child, mCurrentScreen, x, y, spanX, spanY, insert);
+ }
+
+ /**
+ * Adds the specified child in the specified screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param screen The screen in which to add the child.
+ * @param x The X position of the child in the screen's grid.
+ * @param y The Y position of the child in the screen's grid.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ */
+ void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
+ addInScreen(child, screen, x, y, spanX, spanY, false);
+ }
+
+ /**
+ * Adds the specified child in the specified screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param screen The screen in which to add the child.
+ * @param x The X position of the child in the screen's grid.
+ * @param y The Y position of the child in the screen's grid.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ * @param insert When true, the child is inserted at the beginning of the children list.
+ */
+ void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
+ if (screen < 0 || screen >= getChildCount()) {
+ throw new IllegalStateException("The screen must be >= 0 and < " + getChildCount());
+ }
+
+ clearVacantCache();
+
+ final CellLayout group = (CellLayout) getChildAt(screen);
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
+ if (lp == null) {
+ lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
+ } else {
+ lp.cellX = x;
+ lp.cellY = y;
+ lp.cellHSpan = spanX;
+ lp.cellVSpan = spanY;
+ }
+ group.addView(child, insert ? 0 : -1, lp);
+ if (!(child instanceof Folder)) {
+ child.setHapticFeedbackEnabled(false);
+ child.setOnLongClickListener(mLongClickListener);
+ }
+ if (child instanceof DropTarget) {
+ mDragController.addDropTarget((DropTarget)child);
+ }
+ }
+
+ void addWidget(View view, Widget widget) {
+ addInScreen(view, widget.screen, widget.cellX, widget.cellY, widget.spanX,
+ widget.spanY, false);
+ }
+
+ void addWidget(View view, Widget widget, boolean insert) {
+ addInScreen(view, widget.screen, widget.cellX, widget.cellY, widget.spanX,
+ widget.spanY, insert);
+ }
+
+ CellLayout.CellInfo findAllVacantCells(boolean[] occupied) {
+ CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
+ if (group != null) {
+ return group.findAllVacantCells(occupied, null);
+ }
+ return null;
+ }
+
+ private void clearVacantCache() {
+ if (mVacantCache != null) {
+ mVacantCache.clearVacantCells();
+ mVacantCache = null;
+ }
+ }
+
+ /**
+ * Returns the coordinate of a vacant cell for the current screen.
+ */
+ boolean getVacantCell(int[] vacant, int spanX, int spanY) {
+ CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
+ if (group != null) {
+ return group.getVacantCell(vacant, spanX, spanY);
+ }
+ return false;
+ }
+
+ /**
+ * Adds the specified child in the current screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ */
+ void fitInCurrentScreen(View child, int spanX, int spanY) {
+ fitInScreen(child, mCurrentScreen, spanX, spanY);
+ }
+
+ /**
+ * Adds the specified child in the specified screen. The position and dimension of
+ * the child are defined by x, y, spanX and spanY.
+ *
+ * @param child The child to add in one of the workspace's screens.
+ * @param screen The screen in which to add the child.
+ * @param spanX The number of cells spanned horizontally by the child.
+ * @param spanY The number of cells spanned vertically by the child.
+ */
+ void fitInScreen(View child, int screen, int spanX, int spanY) {
+ if (screen < 0 || screen >= getChildCount()) {
+ throw new IllegalStateException("The screen must be >= 0 and < " + getChildCount());
+ }
+
+ final CellLayout group = (CellLayout) getChildAt(screen);
+ boolean vacant = group.getVacantCell(mTempCell, spanX, spanY);
+ if (vacant) {
+ group.addView(child,
+ new CellLayout.LayoutParams(mTempCell[0], mTempCell[1], spanX, spanY));
+ child.setHapticFeedbackEnabled(false);
+ child.setOnLongClickListener(mLongClickListener);
+ if (child instanceof DropTarget) {
+ mDragController.addDropTarget((DropTarget)child);
+ }
+ }
+ }
+
+ /**
+ * Registers the specified listener on each screen contained in this workspace.
+ *
+ * @param l The listener used to respond to long clicks.
+ */
+ @Override
+ public void setOnLongClickListener(OnLongClickListener l) {
+ mLongClickListener = l;
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ getChildAt(i).setOnLongClickListener(l);
+ }
+ }
+
+ private void updateWallpaperOffset() {
+ updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
+ }
+
+ private void updateWallpaperOffset(int scrollRange) {
+ mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
+ mWallpaperManager.setWallpaperOffsets(getWindowToken(), mScrollX / (float) scrollRange, 0);
+ }
+
+ @Override
+ public void computeScroll() {
+ if (mScroller.computeScrollOffset()) {
+ mScrollX = mScroller.getCurrX();
+ mScrollY = mScroller.getCurrY();
+ updateWallpaperOffset();
+ postInvalidate();
+ } else if (mNextScreen != INVALID_SCREEN) {
+ mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));
+ mPreviousIndicator.setLevel(mCurrentScreen);
+ mNextIndicator.setLevel(mCurrentScreen);
+ Launcher.setScreen(mCurrentScreen);
+ mNextScreen = INVALID_SCREEN;
+ clearChildrenCache();
+ }
+ }
+
+ public void startFading(boolean dest) {
+ mFading = dest;
+ invalidate();
+ }
+
+ @Override
+ protected void dispatchDraw(Canvas canvas) {
+ /*
+ final boolean allAppsOpaque = mLauncher.isAllAppsOpaque();
+ if (mFading == allAppsOpaque) {
+ invalidate();
+ } else {
+ mFading = !allAppsOpaque;
+ }
+ if (allAppsOpaque) {
+ // If the launcher is up, draw black.
+ canvas.drawARGB(0xff, 0, 0, 0);
+ return;
+ }
+ */
+
+ boolean restore = false;
+ int restoreCount = 0;
+
+ // For the fade. If view gets setAlpha(), use that instead.
+ float scale = mScale;
+ if (scale < 0.999f) {
+ int sx = mScrollX;
+
+ int alpha = (scale < 0.5f) ? (int)(255 * 2 * scale) : 255;
+
+ restoreCount = canvas.saveLayerAlpha(sx, 0, sx+getWidth(), getHeight(), alpha,
+ Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
+ restore = true;
+
+ if (scale < 0.999f) {
+ int w = getWidth();
+ w += 2 * mCurrentScreen * w;
+ int dx = w/2;
+ int h = getHeight();
+ int dy = (h/2) - (h/4);
+ canvas.translate(dx, dy);
+ canvas.scale(scale, scale);
+ canvas.translate(-dx, -dy);
+ }
+ }
+
+ // ViewGroup.dispatchDraw() supports many features we don't need:
+ // clip to padding, layout animation, animation listener, disappearing
+ // children, etc. The following implementation attempts to fast-track
+ // the drawing dispatch by drawing only what we know needs to be drawn.
+
+ boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN
+ && scale > 0.999f;
+ // If we are not scrolling or flinging, draw only the current screen
+ if (fastDraw) {
+ drawChild(canvas, getChildAt(mCurrentScreen), getDrawingTime());
+ } else {
+ final long drawingTime = getDrawingTime();
+ // If we are flinging, draw only the current screen and the target screen
+ if (mNextScreen >= 0 && mNextScreen < getChildCount() &&
+ Math.abs(mCurrentScreen - mNextScreen) == 1) {
+ drawChild(canvas, getChildAt(mCurrentScreen), drawingTime);
+ drawChild(canvas, getChildAt(mNextScreen), drawingTime);
+ } else {
+ // If we are scrolling, draw all of our children
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ drawChild(canvas, getChildAt(i), drawingTime);
+ }
+ }
+ }
+
+ if (restore) {
+ canvas.restoreToCount(restoreCount);
+ }
+ }
+
+ private float mScale = 1.0f;
+ public void setScale(float scale) {
+ mScale = scale;
+ invalidate();
+ }
+
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ mDragController.setWindowToken(getWindowToken());
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+
+ final int width = MeasureSpec.getSize(widthMeasureSpec);
+ final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
+ if (widthMode != MeasureSpec.EXACTLY) {
+ throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
+ }
+
+ final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
+ if (heightMode != MeasureSpec.EXACTLY) {
+ throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
+ }
+
+ // The children are given the same width and height as the workspace
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
+ }
+
+
+ if (mFirstLayout) {
+ setHorizontalScrollBarEnabled(false);
+ scrollTo(mCurrentScreen * width, 0);
+ setHorizontalScrollBarEnabled(true);
+ updateWallpaperOffset(width * (getChildCount() - 1));
+ mFirstLayout = false;
+ }
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+ int childLeft = 0;
+
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ final View child = getChildAt(i);
+ if (child.getVisibility() != View.GONE) {
+ final int childWidth = child.getMeasuredWidth();
+ child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
+ childLeft += childWidth;
+ }
+ }
+ }
+
+ @Override
+ public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
+ int screen = indexOfChild(child);
+ if (screen != mCurrentScreen || !mScroller.isFinished()) {
+ if (!mLauncher.isWorkspaceLocked()) {
+ snapToScreen(screen);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
+ if (!mLauncher.isAllAppsVisible()) {
+ final Folder openFolder = getOpenFolder();
+ if (openFolder != null) {
+ return openFolder.requestFocus(direction, previouslyFocusedRect);
+ } else {
+ int focusableScreen;
+ if (mNextScreen != INVALID_SCREEN) {
+ focusableScreen = mNextScreen;
+ } else {
+ focusableScreen = mCurrentScreen;
+ }
+ getChildAt(focusableScreen).requestFocus(direction, previouslyFocusedRect);
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public boolean dispatchUnhandledMove(View focused, int direction) {
+ if (direction == View.FOCUS_LEFT) {
+ if (getCurrentScreen() > 0) {
+ snapToScreen(getCurrentScreen() - 1);
+ return true;
+ }
+ } else if (direction == View.FOCUS_RIGHT) {
+ if (getCurrentScreen() < getChildCount() - 1) {
+ snapToScreen(getCurrentScreen() + 1);
+ return true;
+ }
+ }
+ return super.dispatchUnhandledMove(focused, direction);
+ }
+
+ @Override
+ public void addFocusables(ArrayList views, int direction, int focusableMode) {
+ if (!mLauncher.isAllAppsVisible()) {
+ final Folder openFolder = getOpenFolder();
+ if (openFolder == null) {
+ getChildAt(mCurrentScreen).addFocusables(views, direction);
+ if (direction == View.FOCUS_LEFT) {
+ if (mCurrentScreen > 0) {
+ getChildAt(mCurrentScreen - 1).addFocusables(views, direction);
+ }
+ } else if (direction == View.FOCUS_RIGHT){
+ if (mCurrentScreen < getChildCount() - 1) {
+ getChildAt(mCurrentScreen + 1).addFocusables(views, direction);
+ }
+ }
+ } else {
+ openFolder.addFocusables(views, direction);
+ }
+ }
+ }
+
+ @Override
+ public boolean dispatchTouchEvent(MotionEvent ev) {
+ if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+ if (mLauncher.isWorkspaceLocked() || mLauncher.isAllAppsVisible()) {
+ return false;
+ }
+ }
+ return super.dispatchTouchEvent(ev);
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ final boolean workspaceLocked = mLauncher.isWorkspaceLocked();
+ final boolean allAppsVisible = mLauncher.isAllAppsVisible();
+ if (workspaceLocked || allAppsVisible) {
+ return false; // We don't want the events. Let them fall through to the all apps view.
+ }
+
+ /*
+ * This method JUST determines whether we want to intercept the motion.
+ * If we return true, onTouchEvent will be called and we do the actual
+ * scrolling there.
+ */
+
+ /*
+ * Shortcut the most recurring case: the user is in the dragging
+ * state and he is moving his finger. We want to intercept this
+ * motion.
+ */
+ final int action = ev.getAction();
+ if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
+ return true;
+ }
+
+ final float x = ev.getX();
+ final float y = ev.getY();
+
+ switch (action) {
+ case MotionEvent.ACTION_MOVE:
+ /*
+ * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
+ * whether the user has moved far enough from his original down touch.
+ */
+
+ /*
+ * Locally do absolute value. mLastMotionX is set to the y value
+ * of the down event.
+ */
+ final int xDiff = (int) Math.abs(x - mLastMotionX);
+ final int yDiff = (int) Math.abs(y - mLastMotionY);
+
+ final int touchSlop = mTouchSlop;
+ boolean xMoved = xDiff > touchSlop;
+ boolean yMoved = yDiff > touchSlop;
+
+ if (xMoved || yMoved) {
+
+ if (xMoved) {
+ // Scroll if the user moved far enough along the X axis
+ mTouchState = TOUCH_STATE_SCROLLING;
+ enableChildrenCache(mCurrentScreen - 1, mCurrentScreen + 1);
+ }
+ // Either way, cancel any pending longpress
+ if (mAllowLongPress) {
+ mAllowLongPress = false;
+ // Try canceling the long press. It could also have been scheduled
+ // by a distant descendant, so use the mAllowLongPress flag to block
+ // everything
+ final View currentScreen = getChildAt(mCurrentScreen);
+ currentScreen.cancelLongPress();
+ }
+ }
+ break;
+
+ case MotionEvent.ACTION_DOWN:
+ // Remember location of down touch
+ mLastMotionX = x;
+ mLastMotionY = y;
+ mAllowLongPress = true;
+
+ /*
+ * If being flinged and user touches the screen, initiate drag;
+ * otherwise don't. mScroller.isFinished should be false when
+ * being flinged.
+ */
+ mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
+ break;
+
+ case MotionEvent.ACTION_CANCEL:
+ case MotionEvent.ACTION_UP:
+
+ if (mTouchState != TOUCH_STATE_SCROLLING) {
+
+ final CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen);
+ if (!currentScreen.lastDownOnOccupiedCell()) {
+ // Send a tap to the wallpaper if the last down was on empty space
+ mWallpaperManager.sendWallpaperCommand(getWindowToken(),
+ "android.wallpaper.tap", (int) ev.getX(), (int) ev.getY(), 0, null);
+ }
+ }
+
+ // Release the drag
+ clearChildrenCache();
+ mTouchState = TOUCH_STATE_REST;
+ mAllowLongPress = false;
+
+ break;
+ }
+
+ /*
+ * The only time we want to intercept motion events is if we are in the
+ * drag mode.
+ */
+ return mTouchState != TOUCH_STATE_REST;
+ }
+
+ /**
+ * If one of our descendant views decides that it could be focused now, only
+ * pass that along if it's on the current screen.
+ *
+ * This happens when live folders requery, and if they're off screen, they
+ * end up calling requestFocus, which pulls it on screen.
+ */
+ @Override
+ public void focusableViewAvailable(View focused) {
+ View current = getChildAt(mCurrentScreen);
+ View v = focused;
+ while (true) {
+ if (v == current) {
+ super.focusableViewAvailable(focused);
+ return;
+ }
+ if (v == this) {
+ return;
+ }
+ ViewParent parent = v.getParent();
+ if (parent instanceof View) {
+ v = (View)v.getParent();
+ } else {
+ return;
+ }
+ }
+ }
+
+ void enableChildrenCache(int fromScreen, int toScreen) {
+ if (fromScreen > toScreen) {
+ fromScreen = toScreen;
+ toScreen = fromScreen;
+ }
+
+ final int count = getChildCount();
+
+ fromScreen = Math.max(fromScreen, 0);
+ toScreen = Math.min(toScreen, count - 1);
+
+ for (int i = fromScreen; i <= toScreen; i++) {
+ final CellLayout layout = (CellLayout) getChildAt(i);
+ layout.setChildrenDrawnWithCacheEnabled(true);
+ layout.setChildrenDrawingCacheEnabled(true);
+ }
+ }
+
+ void clearChildrenCache() {
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ final CellLayout layout = (CellLayout) getChildAt(i);
+ layout.setChildrenDrawnWithCacheEnabled(false);
+ }
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+
+ if (mLauncher.isWorkspaceLocked()) {
+ return false; // We don't want the events. Let them fall through to the all apps view.
+ }
+ if (mLauncher.isAllAppsVisible()) {
+ // Cancel any scrolling that is in progress.
+ if (!mScroller.isFinished()) {
+ mScroller.abortAnimation();
+ }
+ snapToScreen(mCurrentScreen);
+ return false; // We don't want the events. Let them fall through to the all apps view.
+ }
+
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ mVelocityTracker.addMovement(ev);
+
+ final int action = ev.getAction();
+ final float x = ev.getX();
+
+ switch (action) {
+ case MotionEvent.ACTION_DOWN:
+ /*
+ * If being flinged and user touches, stop the fling. isFinished
+ * will be false if being flinged.
+ */
+ if (!mScroller.isFinished()) {
+ mScroller.abortAnimation();
+ }
+
+ // Remember where the motion event started
+ mLastMotionX = x;
+ break;
+ case MotionEvent.ACTION_MOVE:
+ if (mTouchState == TOUCH_STATE_SCROLLING) {
+ // Scroll to follow the motion event
+ final int deltaX = (int) (mLastMotionX - x);
+ mLastMotionX = x;
+
+ if (deltaX < 0) {
+ if (mScrollX > 0) {
+ scrollBy(Math.max(-mScrollX, deltaX), 0);
+ updateWallpaperOffset();
+ }
+ } else if (deltaX > 0) {
+ final int availableToScroll = getChildAt(getChildCount() - 1).getRight() -
+ mScrollX - getWidth();
+ if (availableToScroll > 0) {
+ scrollBy(Math.min(availableToScroll, deltaX), 0);
+ updateWallpaperOffset();
+ }
+ } else {
+ awakenScrollBars();
+ }
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ if (mTouchState == TOUCH_STATE_SCROLLING) {
+ final VelocityTracker velocityTracker = mVelocityTracker;
+ velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
+ int velocityX = (int) velocityTracker.getXVelocity();
+
+ if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
+ // Fling hard enough to move left
+ snapToScreen(mCurrentScreen - 1);
+ } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
+ // Fling hard enough to move right
+ snapToScreen(mCurrentScreen + 1);
+ } else {
+ snapToDestination();
+ }
+
+ if (mVelocityTracker != null) {
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ }
+ }
+ mTouchState = TOUCH_STATE_REST;
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ mTouchState = TOUCH_STATE_REST;
+ }
+
+ return true;
+ }
+
+ private void snapToDestination() {
+ final int screenWidth = getWidth();
+ final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
+
+ snapToScreen(whichScreen);
+ }
+
+ void snapToScreen(int whichScreen) {
+ snapToScreen(whichScreen, true);
+ }
+
+ void snapToScreen(int whichScreen, boolean animate) {
+ //if (!mScroller.isFinished()) return;
+
+ whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
+
+ clearVacantCache();
+ enableChildrenCache(mCurrentScreen, whichScreen);
+
+ final int screenDelta = Math.abs(whichScreen - mCurrentScreen);
+
+ mNextScreen = whichScreen;
+
+ mPreviousIndicator.setLevel(mNextScreen);
+ mNextIndicator.setLevel(mNextScreen);
+
+ View focusedChild = getFocusedChild();
+ if (focusedChild != null && screenDelta != 0 && focusedChild == getChildAt(mCurrentScreen)) {
+ focusedChild.clearFocus();
+ }
+
+ final int newX = whichScreen * getWidth();
+ final int delta = newX - mScrollX;
+ final int duration = screenDelta * 300;
+ awakenScrollBars(duration);
+ // 1ms is close to don't animate
+ mScroller.startScroll(mScrollX, 0, delta, 0, animate ? duration : 1);
+ invalidate();
+ }
+
+ void startDrag(CellLayout.CellInfo cellInfo) {
+ View child = cellInfo.cell;
+
+ // Make sure the drag was started by a long press as opposed to a long click.
+ // Note that Search takes focus when clicked rather than entering touch mode
+ if (!child.isInTouchMode() && !(child instanceof Search)) {
+ return;
+ }
+
+ mDragInfo = cellInfo;
+ mDragInfo.screen = mCurrentScreen;
+
+ CellLayout current = ((CellLayout) getChildAt(mCurrentScreen));
+
+ current.onDragChild(child);
+ mDragController.startDrag(child, this, child.getTag(), DragController.DRAG_ACTION_MOVE);
+ invalidate();
+ }
+
+ @Override
+ protected Parcelable onSaveInstanceState() {
+ final SavedState state = new SavedState(super.onSaveInstanceState());
+ state.currentScreen = mCurrentScreen;
+ return state;
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Parcelable state) {
+ SavedState savedState = (SavedState) state;
+ super.onRestoreInstanceState(savedState.getSuperState());
+ if (savedState.currentScreen != -1) {
+ mCurrentScreen = savedState.currentScreen;
+ Launcher.setScreen(mCurrentScreen);
+ }
+ }
+
+ void addApplicationShortcut(ApplicationInfo info, CellLayout.CellInfo cellInfo) {
+ addApplicationShortcut(info, cellInfo, false);
+ }
+
+ void addApplicationShortcut(ApplicationInfo info, CellLayout.CellInfo cellInfo,
+ boolean insertAtFirst) {
+ final CellLayout layout = (CellLayout) getChildAt(cellInfo.screen);
+ final int[] result = new int[2];
+
+ layout.cellToPoint(cellInfo.cellX, cellInfo.cellY, result);
+ onDropExternal(result[0], result[1], info, layout, insertAtFirst);
+ }
+
+ public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ final CellLayout cellLayout = getCurrentDropLayout();
+ if (source != this) {
+ onDropExternal(x - xOffset, y - yOffset, dragInfo, cellLayout);
+ } else {
+ // Move internally
+ if (mDragInfo != null) {
+ final View cell = mDragInfo.cell;
+ int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
+ if (index != mDragInfo.screen) {
+ final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen);
+ originalCellLayout.removeView(cell);
+ cellLayout.addView(cell);
+ }
+ mTargetCell = estimateDropCell(x - xOffset, y - yOffset,
+ mDragInfo.spanX, mDragInfo.spanY, cell, cellLayout, mTargetCell);
+ cellLayout.onDropChild(cell, mTargetCell);
+
+ final ItemInfo info = (ItemInfo) cell.getTag();
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
+ LauncherModel.moveItemInDatabase(mLauncher, info,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP, index, lp.cellX, lp.cellY);
+ }
+ }
+ }
+
+ public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ clearVacantCache();
+ }
+
+ public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ }
+
+ public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
+ DragView dragView, Object dragInfo) {
+ clearVacantCache();
+ }
+
+ private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout) {
+ onDropExternal(x, y, dragInfo, cellLayout, false);
+ }
+
+ private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout,
+ boolean insertAtFirst) {
+ // Drag from somewhere else
+ ItemInfo info = (ItemInfo) dragInfo;
+
+ View view;
+
+ switch (info.itemType) {
+ case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
+ case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
+ if (info.container == NO_ID) {
+ // Came from all apps -- make a copy
+ info = new ApplicationInfo((ApplicationInfo) info);
+ }
+ view = mLauncher.createShortcut(R.layout.application, cellLayout,
+ (ApplicationInfo) info);
+ break;
+ case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
+ view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
+ (ViewGroup) getChildAt(mCurrentScreen), ((UserFolderInfo) info));
+ break;
+ default:
+ throw new IllegalStateException("Unknown item type: " + info.itemType);
+ }
+
+ cellLayout.addView(view, insertAtFirst ? 0 : -1);
+ view.setHapticFeedbackEnabled(false);
+ view.setOnLongClickListener(mLongClickListener);
+ if (view instanceof DropTarget) {
+ mDragController.addDropTarget((DropTarget) view);
+ }
+
+ mTargetCell = estimateDropCell(x, y, 1, 1, view, cellLayout, mTargetCell);
+ cellLayout.onDropChild(view, mTargetCell);
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
+
+ LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentScreen, lp.cellX, lp.cellY);
+ }
+
+ /**
+ * Return the current {@link CellLayout}, correctly picking the destination
+ * screen while a scroll is in progress.
+ */
+ private CellLayout getCurrentDropLayout() {
+ int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
+ return (CellLayout) getChildAt(index);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean acceptDrop(DragSource source, int x, int y,
+ int xOffset, int yOffset, DragView dragView, Object dragInfo) {
+ final CellLayout layout = getCurrentDropLayout();
+ final CellLayout.CellInfo cellInfo = mDragInfo;
+ final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
+ final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
+
+ if (mVacantCache == null) {
+ final View ignoreView = cellInfo == null ? null : cellInfo.cell;
+ mVacantCache = layout.findAllVacantCells(null, ignoreView);
+ }
+
+ return mVacantCache.findCellForSpan(mTempEstimate, spanX, spanY, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Rect estimateDropLocation(DragSource source, int x, int y,
+ int xOffset, int yOffset, DragView dragView, Object dragInfo, Rect recycle) {
+ final CellLayout layout = getCurrentDropLayout();
+
+ final CellLayout.CellInfo cellInfo = mDragInfo;
+ final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
+ final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
+ final View ignoreView = cellInfo == null ? null : cellInfo.cell;
+
+ final Rect location = recycle != null ? recycle : new Rect();
+
+ // Find drop cell and convert into rectangle
+ int[] dropCell = estimateDropCell(x - xOffset, y - yOffset,
+ spanX, spanY, ignoreView, layout, mTempCell);
+
+ if (dropCell == null) {
+ return null;
+ }
+
+ layout.cellToPoint(dropCell[0], dropCell[1], mTempEstimate);
+ location.left = mTempEstimate[0];
+ location.top = mTempEstimate[1];
+
+ layout.cellToPoint(dropCell[0] + spanX, dropCell[1] + spanY, mTempEstimate);
+ location.right = mTempEstimate[0];
+ location.bottom = mTempEstimate[1];
+
+ return location;
+ }
+
+ /**
+ * Calculate the nearest cell where the given object would be dropped.
+ */
+ private int[] estimateDropCell(int pixelX, int pixelY,
+ int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
+ // Create vacant cell cache if none exists
+ if (mVacantCache == null) {
+ mVacantCache = layout.findAllVacantCells(null, ignoreView);
+ }
+
+ // Find the best target drop location
+ return layout.findNearestVacantArea(pixelX, pixelY,
+ spanX, spanY, mVacantCache, recycle);
+ }
+
+ void setLauncher(Launcher launcher) {
+ mLauncher = launcher;
+ }
+
+ public void setDragController(DragController dragController) {
+ mDragController = dragController;
+ }
+
+ public void onDropCompleted(View target, boolean success) {
+ clearVacantCache();
+
+ if (success){
+ if (target != this && mDragInfo != null) {
+ final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
+ cellLayout.removeView(mDragInfo.cell);
+ if (mDragInfo.cell instanceof DropTarget) {
+ mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
+ }
+ //final Object tag = mDragInfo.cell.getTag();
+ }
+ } else {
+ if (mDragInfo != null) {
+ final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
+ cellLayout.onDropAborted(mDragInfo.cell);
+ }
+ }
+
+ mDragInfo = null;
+ }
+
+ public void scrollLeft() {
+ clearVacantCache();
+ if (mNextScreen == INVALID_SCREEN && mCurrentScreen > 0 && mScroller.isFinished()) {
+ snapToScreen(mCurrentScreen - 1);
+ }
+ }
+
+ public void scrollRight() {
+ clearVacantCache();
+ if (mNextScreen == INVALID_SCREEN && mCurrentScreen < getChildCount() -1 &&
+ mScroller.isFinished()) {
+ snapToScreen(mCurrentScreen + 1);
+ }
+ }
+
+ public int getScreenForView(View v) {
+ int result = -1;
+ if (v != null) {
+ ViewParent vp = v.getParent();
+ int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ if (vp == getChildAt(i)) {
+ return i;
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Find a search widget on the given screen
+ */
+ private Search findSearchWidget(CellLayout screen) {
+ final int count = screen.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View v = screen.getChildAt(i);
+ if (v instanceof Search) {
+ return (Search) v;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets the first search widget on the current screen, if there is one.
+ * Returns null otherwise.
+ */
+ public Search findSearchWidgetOnCurrentScreen() {
+ CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen);
+ return findSearchWidget(currentScreen);
+ }
+
+ public Folder getFolderForTag(Object tag) {
+ int screenCount = getChildCount();
+ for (int screen = 0; screen < screenCount; screen++) {
+ CellLayout currentScreen = ((CellLayout) getChildAt(screen));
+ int count = currentScreen.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View child = currentScreen.getChildAt(i);
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
+ if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
+ Folder f = (Folder) child;
+ if (f.getInfo() == tag) {
+ return f;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ public View getViewForTag(Object tag) {
+ int screenCount = getChildCount();
+ for (int screen = 0; screen < screenCount; screen++) {
+ CellLayout currentScreen = ((CellLayout) getChildAt(screen));
+ int count = currentScreen.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View child = currentScreen.getChildAt(i);
+ if (child.getTag() == tag) {
+ return child;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @return True is long presses are still allowed for the current touch
+ */
+ public boolean allowLongPress() {
+ return mAllowLongPress;
+ }
+
+ /**
+ * Set true to allow long-press events to be triggered, usually checked by
+ * {@link Launcher} to accept or block dpad-initiated long-presses.
+ */
+ public void setAllowLongPress(boolean allowLongPress) {
+ mAllowLongPress = allowLongPress;
+ }
+
+ void removeShortcutsForPackage(String packageName) {
+ final ArrayList childrenToRemove = new ArrayList();
+ final int count = getChildCount();
+
+ for (int i = 0; i < count; i++) {
+ final CellLayout layout = (CellLayout) getChildAt(i);
+ int childCount = layout.getChildCount();
+
+ childrenToRemove.clear();
+
+ for (int j = 0; j < childCount; j++) {
+ final View view = layout.getChildAt(j);
+ Object tag = view.getTag();
+
+ if (tag instanceof ApplicationInfo) {
+ final ApplicationInfo info = (ApplicationInfo) tag;
+ // We need to check for ACTION_MAIN otherwise getComponent() might
+ // return null for some shortcuts (for instance, for shortcuts to
+ // web pages.)
+ final Intent intent = info.intent;
+ final ComponentName name = intent.getComponent();
+
+ if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
+ name != null && packageName.equals(name.getPackageName())) {
+ LauncherModel.deleteItemFromDatabase(mLauncher, info);
+ childrenToRemove.add(view);
+ }
+ } else if (tag instanceof UserFolderInfo) {
+ final UserFolderInfo info = (UserFolderInfo) tag;
+ final ArrayList contents = info.contents;
+ final ArrayList toRemove = new ArrayList(1);
+ final int contentsCount = contents.size();
+ boolean removedFromFolder = false;
+
+ for (int k = 0; k < contentsCount; k++) {
+ final ApplicationInfo appInfo = contents.get(k);
+ final Intent intent = appInfo.intent;
+ final ComponentName name = intent.getComponent();
+
+ if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
+ name != null && packageName.equals(name.getPackageName())) {
+ toRemove.add(appInfo);
+ LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
+ removedFromFolder = true;
+ }
+ }
+
+ contents.removeAll(toRemove);
+ if (removedFromFolder) {
+ final Folder folder = getOpenFolder();
+ if (folder != null) folder.notifyDataSetChanged();
+ }
+ }
+ }
+
+ childCount = childrenToRemove.size();
+ for (int j = 0; j < childCount; j++) {
+ View child = childrenToRemove.get(j);
+ layout.removeViewInLayout(child);
+ if (child instanceof DropTarget) {
+ mDragController.removeDropTarget((DropTarget)child);
+ }
+ }
+
+ if (childCount > 0) {
+ layout.requestLayout();
+ layout.invalidate();
+ }
+ }
+ }
+
+ void updateShortcutsForPackage(String packageName) {
+ final PackageManager pm = mLauncher.getPackageManager();
+
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ final CellLayout layout = (CellLayout) getChildAt(i);
+ int childCount = layout.getChildCount();
+ for (int j = 0; j < childCount; j++) {
+ final View view = layout.getChildAt(j);
+ Object tag = view.getTag();
+ if (tag instanceof ApplicationInfo) {
+ ApplicationInfo info = (ApplicationInfo) tag;
+ // We need to check for ACTION_MAIN otherwise getComponent() might
+ // return null for some shortcuts (for instance, for shortcuts to
+ // web pages.)
+ final Intent intent = info.intent;
+ final ComponentName name = intent.getComponent();
+ if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
+ Intent.ACTION_MAIN.equals(intent.getAction()) && name != null &&
+ packageName.equals(name.getPackageName())) {
+
+ final Drawable icon = AppInfoCache.getIconDrawable(pm, info);
+ if (icon != null && icon != info.icon) {
+ info.icon.setCallback(null);
+ info.icon = Utilities.createIconThumbnail(icon, mContext);
+ info.filtered = true;
+ ((TextView) view).setCompoundDrawablesWithIntrinsicBounds(null,
+ info.icon, null, null);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ void moveToDefaultScreen(boolean animate) {
+ snapToScreen(mDefaultScreen, animate);
+ getChildAt(mDefaultScreen).requestFocus();
+ }
+
+ void setIndicators(Drawable previous, Drawable next) {
+ mPreviousIndicator = previous;
+ mNextIndicator = next;
+ previous.setLevel(mCurrentScreen);
+ next.setLevel(mCurrentScreen);
+ }
+
+ public static class SavedState extends BaseSavedState {
+ int currentScreen = -1;
+
+ SavedState(Parcelable superState) {
+ super(superState);
+ }
+
+ private SavedState(Parcel in) {
+ super(in);
+ currentScreen = in.readInt();
+ }
+
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ super.writeToParcel(out, flags);
+ out.writeInt(currentScreen);
+ }
+
+ public static final Parcelable.Creator CREATOR =
+ new Parcelable.Creator() {
+ public SavedState createFromParcel(Parcel in) {
+ return new SavedState(in);
+ }
+
+ public SavedState[] newArray(int size) {
+ return new SavedState[size];
+ }
+ };
+ }
+
+ void show() {
+ setVisibility(VISIBLE);
+ }
+
+ void hide() {
+ }
+}