blob: 151048c7cfa88d7d8a19e5c0d2a0fce5d44616fd [file] [log] [blame]
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher3;
18
19import android.appwidget.AppWidgetHost;
20import android.appwidget.AppWidgetManager;
21import android.content.ComponentName;
22import android.content.ContentValues;
23import android.content.Context;
24import android.content.Intent;
25import android.content.pm.ActivityInfo;
26import android.content.pm.PackageManager;
27import android.content.res.Resources;
28import android.content.res.XmlResourceParser;
29import android.database.sqlite.SQLiteDatabase;
30import android.graphics.drawable.Drawable;
31import android.net.Uri;
32import android.os.Bundle;
33import android.text.TextUtils;
34import android.util.Log;
35import android.util.Pair;
36import android.util.Patterns;
37
38import com.android.launcher3.LauncherProvider.SqlArguments;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070039import com.android.launcher3.LauncherSettings.Favorites;
Adam Cohen091440a2015-03-18 14:16:05 -070040import com.android.launcher3.util.Thunk;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070041
42import org.xmlpull.v1.XmlPullParser;
43import org.xmlpull.v1.XmlPullParserException;
44
45import java.io.IOException;
46import java.util.ArrayList;
47import java.util.HashMap;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import java.util.Locale;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070049
50/**
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070051 * Layout parsing code for auto installs layout
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070053public class AutoInstallsLayout {
Sunny Goyal0fe505b2014-08-06 09:55:36 -070054 private static final String TAG = "AutoInstalls";
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070055 private static final boolean LOGD = false;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070056
57 /** Marker action used to discover a package which defines launcher customization */
58 static final String ACTION_LAUNCHER_CUSTOMIZATION =
Sunny Goyal2233c882014-09-18 14:36:48 -070059 "android.autoinstalls.config.action.PLAY_AUTO_INSTALL";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070060
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070061 /**
62 * Layout resource which also includes grid size and hotseat count, e.g., default_layout_6x6_h5
63 */
64 private static final String FORMATTED_LAYOUT_RES_WITH_HOSTEAT = "default_layout_%dx%d_h%s";
65 private static final String FORMATTED_LAYOUT_RES = "default_layout_%dx%d";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070066 private static final String LAYOUT_RES = "default_layout";
67
68 static AutoInstallsLayout get(Context context, AppWidgetHost appWidgetHost,
69 LayoutParserCallback callback) {
70 Pair<String, Resources> customizationApkInfo = Utilities.findSystemApk(
71 ACTION_LAUNCHER_CUSTOMIZATION, context.getPackageManager());
72 if (customizationApkInfo == null) {
73 return null;
74 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070075 return get(context, customizationApkInfo.first, customizationApkInfo.second,
76 appWidgetHost, callback);
77 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -070078
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070079 static AutoInstallsLayout get(Context context, String pkg, Resources targetRes,
80 AppWidgetHost appWidgetHost, LayoutParserCallback callback) {
Adam Cohen2e6da152015-05-06 11:42:25 -070081 InvariantDeviceProfile grid = LauncherAppState.getInstance().getInvariantDeviceProfile();
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070082
83 // Try with grid size and hotseat count
84 String layoutName = String.format(Locale.ENGLISH, FORMATTED_LAYOUT_RES_WITH_HOSTEAT,
85 (int) grid.numColumns, (int) grid.numRows, (int) grid.numHotseatIcons);
86 int layoutId = targetRes.getIdentifier(layoutName, "xml", pkg);
87
88 // Try with only grid size
89 if (layoutId == 0) {
90 Log.d(TAG, "Formatted layout: " + layoutName
91 + " not found. Trying layout without hosteat");
92 layoutName = String.format(Locale.ENGLISH, FORMATTED_LAYOUT_RES,
93 (int) grid.numColumns, (int) grid.numRows);
94 layoutId = targetRes.getIdentifier(layoutName, "xml", pkg);
95 }
96
97 // Try the default layout
98 if (layoutId == 0) {
99 Log.d(TAG, "Formatted layout: " + layoutName + " not found. Trying the default layout");
100 layoutId = targetRes.getIdentifier(LAYOUT_RES, "xml", pkg);
101 }
102
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700103 if (layoutId == 0) {
104 Log.e(TAG, "Layout definition not found in package: " + pkg);
105 return null;
106 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700107 return new AutoInstallsLayout(context, appWidgetHost, callback, targetRes, layoutId,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700108 TAG_WORKSPACE);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700109 }
110
111 // Object Tags
Sunny Goyalb564efb2015-01-23 13:45:20 -0800112 private static final String TAG_INCLUDE = "include";
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700113 private static final String TAG_WORKSPACE = "workspace";
114 private static final String TAG_APP_ICON = "appicon";
115 private static final String TAG_AUTO_INSTALL = "autoinstall";
116 private static final String TAG_FOLDER = "folder";
117 private static final String TAG_APPWIDGET = "appwidget";
118 private static final String TAG_SHORTCUT = "shortcut";
119 private static final String TAG_EXTRA = "extra";
120
121 private static final String ATTR_CONTAINER = "container";
122 private static final String ATTR_RANK = "rank";
123
124 private static final String ATTR_PACKAGE_NAME = "packageName";
125 private static final String ATTR_CLASS_NAME = "className";
126 private static final String ATTR_TITLE = "title";
127 private static final String ATTR_SCREEN = "screen";
Sunny Goyal96a09632015-12-16 11:32:54 -0800128
129 // x and y can be specified as negative integers, in which case -1 represents the
130 // last row / column, -2 represents the second last, and so on.
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700131 private static final String ATTR_X = "x";
132 private static final String ATTR_Y = "y";
Sunny Goyal96a09632015-12-16 11:32:54 -0800133
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700134 private static final String ATTR_SPAN_X = "spanX";
135 private static final String ATTR_SPAN_Y = "spanY";
136 private static final String ATTR_ICON = "icon";
137 private static final String ATTR_URL = "url";
138
Sunny Goyalb564efb2015-01-23 13:45:20 -0800139 // Attrs for "Include"
140 private static final String ATTR_WORKSPACE = "workspace";
141
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700142 // Style attrs -- "Extra"
143 private static final String ATTR_KEY = "key";
144 private static final String ATTR_VALUE = "value";
145
146 private static final String HOTSEAT_CONTAINER_NAME =
147 Favorites.containerToString(Favorites.CONTAINER_HOTSEAT);
148
149 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
150 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
151
Adam Cohen091440a2015-03-18 14:16:05 -0700152 @Thunk final Context mContext;
153 @Thunk final AppWidgetHost mAppWidgetHost;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800154 protected final LayoutParserCallback mCallback;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700155
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700156 protected final PackageManager mPackageManager;
157 protected final Resources mSourceRes;
158 protected final int mLayoutId;
159
160 private final int mHotseatAllAppsRank;
Sunny Goyal96a09632015-12-16 11:32:54 -0800161 private final int mRowCount;
162 private final int mColumnCount;
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700163
164 private final long[] mTemp = new long[2];
Adam Cohen091440a2015-03-18 14:16:05 -0700165 @Thunk final ContentValues mValues;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800166 protected final String mRootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700167
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700168 protected SQLiteDatabase mDb;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700169
170 public AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700171 LayoutParserCallback callback, Resources res,
172 int layoutId, String rootTag) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700173 mContext = context;
174 mAppWidgetHost = appWidgetHost;
175 mCallback = callback;
176
177 mPackageManager = context.getPackageManager();
178 mValues = new ContentValues();
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700179 mRootTag = rootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700180
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700181 mSourceRes = res;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700182 mLayoutId = layoutId;
Sunny Goyal96a09632015-12-16 11:32:54 -0800183
184 InvariantDeviceProfile idp = LauncherAppState.getInstance().getInvariantDeviceProfile();
185 mHotseatAllAppsRank = idp.hotseatAllAppsRank;
186 mRowCount = idp.numRows;
187 mColumnCount = idp.numColumns;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700188 }
189
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700190 /**
191 * Loads the layout in the db and returns the number of entries added on the desktop.
192 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700193 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
194 mDb = db;
195 try {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700196 return parseLayout(mLayoutId, screenIds);
Sameer Padala8fd74832014-09-08 16:00:29 -0700197 } catch (Exception e) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700198 Log.w(TAG, "Got exception parsing layout.", e);
199 return -1;
200 }
201 }
202
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700203 /**
204 * Parses the layout and returns the number of elements added on the homescreen.
205 */
206 protected int parseLayout(int layoutId, ArrayList<Long> screenIds)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700207 throws XmlPullParserException, IOException {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700208 XmlResourceParser parser = mSourceRes.getXml(layoutId);
209 beginDocument(parser, mRootTag);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700210 final int depth = parser.getDepth();
211 int type;
212 HashMap<String, TagParser> tagParserMap = getLayoutElementsMap();
213 int count = 0;
214
215 while (((type = parser.next()) != XmlPullParser.END_TAG ||
216 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
217 if (type != XmlPullParser.START_TAG) {
218 continue;
219 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700220 count += parseAndAddNode(parser, tagParserMap, screenIds);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700221 }
222 return count;
223 }
224
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700225 /**
226 * Parses container and screenId attribute from the current tag, and puts it in the out.
227 * @param out array of size 2.
228 */
229 protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
230 if (HOTSEAT_CONTAINER_NAME.equals(getAttributeValue(parser, ATTR_CONTAINER))) {
231 out[0] = Favorites.CONTAINER_HOTSEAT;
232 // Hack: hotseat items are stored using screen ids
233 long rank = Long.parseLong(getAttributeValue(parser, ATTR_RANK));
234 out[1] = (rank < mHotseatAllAppsRank) ? rank : (rank + 1);
235 } else {
236 out[0] = Favorites.CONTAINER_DESKTOP;
237 out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
238 }
239 }
240
241 /**
242 * Parses the current node and returns the number of elements added.
243 */
244 protected int parseAndAddNode(
245 XmlResourceParser parser,
246 HashMap<String, TagParser> tagParserMap,
247 ArrayList<Long> screenIds)
248 throws XmlPullParserException, IOException {
Sunny Goyalb564efb2015-01-23 13:45:20 -0800249
250 if (TAG_INCLUDE.equals(parser.getName())) {
251 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
252 if (resId != 0) {
253 // recursively load some more favorites, why not?
254 return parseLayout(resId, screenIds);
255 } else {
256 return 0;
257 }
258 }
259
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700260 mValues.clear();
261 parseContainerAndScreen(parser, mTemp);
262 final long container = mTemp[0];
263 final long screenId = mTemp[1];
264
265 mValues.put(Favorites.CONTAINER, container);
266 mValues.put(Favorites.SCREEN, screenId);
Sunny Goyal96a09632015-12-16 11:32:54 -0800267
268 mValues.put(Favorites.CELLX,
269 convertToDistanceFromEnd(getAttributeValue(parser, ATTR_X), mColumnCount);
270 mValues.put(Favorites.CELLY,
271 convertToDistanceFromEnd(getAttributeValue(parser, ATTR_Y), mRowCount);
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700272
273 TagParser tagParser = tagParserMap.get(parser.getName());
274 if (tagParser == null) {
275 if (LOGD) Log.d(TAG, "Ignoring unknown element tag: " + parser.getName());
276 return 0;
277 }
278 long newElementId = tagParser.parseAndAdd(parser);
279 if (newElementId >= 0) {
280 // Keep track of the set of screens which need to be added to the db.
281 if (!screenIds.contains(screenId) &&
282 container == Favorites.CONTAINER_DESKTOP) {
283 screenIds.add(screenId);
284 }
285 return 1;
286 }
287 return 0;
288 }
289
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700290 protected long addShortcut(String title, Intent intent, int type) {
291 long id = mCallback.generateNewItemId();
292 mValues.put(Favorites.INTENT, intent.toUri(0));
293 mValues.put(Favorites.TITLE, title);
294 mValues.put(Favorites.ITEM_TYPE, type);
295 mValues.put(Favorites.SPANX, 1);
296 mValues.put(Favorites.SPANY, 1);
297 mValues.put(Favorites._ID, id);
298 if (mCallback.insertAndCheck(mDb, mValues) < 0) {
299 return -1;
300 } else {
301 return id;
302 }
303 }
304
305 protected HashMap<String, TagParser> getFolderElementsMap() {
306 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
307 parsers.put(TAG_APP_ICON, new AppShortcutParser());
308 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700309 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700310 return parsers;
311 }
312
313 protected HashMap<String, TagParser> getLayoutElementsMap() {
314 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
315 parsers.put(TAG_APP_ICON, new AppShortcutParser());
316 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
317 parsers.put(TAG_FOLDER, new FolderParser());
318 parsers.put(TAG_APPWIDGET, new AppWidgetParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700319 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700320 return parsers;
321 }
322
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700323 protected interface TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700324 /**
325 * Parses the tag and adds to the db
326 * @return the id of the row added or -1;
327 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700328 long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700329 throws XmlPullParserException, IOException;
330 }
331
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700332 /**
333 * App shortcuts: required attributes packageName and className
334 */
335 protected class AppShortcutParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700336
337 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700338 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700339 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
340 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
341
342 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
343 ActivityInfo info;
344 try {
345 ComponentName cn;
346 try {
347 cn = new ComponentName(packageName, className);
348 info = mPackageManager.getActivityInfo(cn, 0);
349 } catch (PackageManager.NameNotFoundException nnfe) {
350 String[] packages = mPackageManager.currentToCanonicalPackageNames(
351 new String[] { packageName });
352 cn = new ComponentName(packages[0], className);
353 info = mPackageManager.getActivityInfo(cn, 0);
354 }
355 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
356 .addCategory(Intent.CATEGORY_LAUNCHER)
357 .setComponent(cn)
358 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
359 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
360
361 return addShortcut(info.loadLabel(mPackageManager).toString(),
362 intent, Favorites.ITEM_TYPE_APPLICATION);
363 } catch (PackageManager.NameNotFoundException e) {
Adam Cohencf0c7462015-08-06 14:02:23 -0700364 Log.e(TAG, "Unable to add favorite: " + packageName + "/" + className, e);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700365 }
366 return -1;
367 } else {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700368 return invalidPackageOrClass(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700369 }
370 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700371
372 /**
373 * Helper method to allow extending the parser capabilities
374 */
375 protected long invalidPackageOrClass(XmlResourceParser parser) {
Adam Cohencf0c7462015-08-06 14:02:23 -0700376 Log.w(TAG, "Skipping invalid <favorite> with no component");
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700377 return -1;
378 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700379 }
380
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700381 /**
382 * AutoInstall: required attributes packageName and className
383 */
384 protected class AutoInstallParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700385
386 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700387 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700388 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
389 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
390 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
391 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
392 return -1;
393 }
394
Sunny Goyal34942622014-08-29 17:20:55 -0700395 mValues.put(Favorites.RESTORED, ShortcutInfo.FLAG_AUTOINTALL_ICON);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700396 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
397 .addCategory(Intent.CATEGORY_LAUNCHER)
398 .setComponent(new ComponentName(packageName, className))
399 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
400 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
401 return addShortcut(mContext.getString(R.string.package_state_unknown), intent,
402 Favorites.ITEM_TYPE_APPLICATION);
403 }
404 }
405
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700406 /**
407 * Parses a web shortcut. Required attributes url, icon, title
408 */
409 protected class ShortcutParser implements TagParser {
410
411 private final Resources mIconRes;
412
413 public ShortcutParser(Resources iconRes) {
414 mIconRes = iconRes;
415 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700416
417 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700418 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700419 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
420 final int iconId = getAttributeResourceValue(parser, ATTR_ICON, 0);
421
422 if (titleResId == 0 || iconId == 0) {
423 if (LOGD) Log.d(TAG, "Ignoring shortcut");
424 return -1;
425 }
426
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700427 final Intent intent = parseIntent(parser);
428 if (intent == null) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700429 return -1;
430 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700431
432 Drawable icon = mIconRes.getDrawable(iconId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700433 if (icon == null) {
434 if (LOGD) Log.d(TAG, "Ignoring shortcut, can't load icon");
435 return -1;
436 }
437
438 ItemInfo.writeBitmap(mValues, Utilities.createIconBitmap(icon, mContext));
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700439 mValues.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
440 mValues.put(Favorites.ICON_PACKAGE, mIconRes.getResourcePackageName(iconId));
441 mValues.put(Favorites.ICON_RESOURCE, mIconRes.getResourceName(iconId));
442
443 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700444 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700445 return addShortcut(mSourceRes.getString(titleResId),
446 intent, Favorites.ITEM_TYPE_SHORTCUT);
447 }
448
449 protected Intent parseIntent(XmlResourceParser parser) {
450 final String url = getAttributeValue(parser, ATTR_URL);
451 if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
452 if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
453 return null;
454 }
455 return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700456 }
457 }
458
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700459 /**
460 * AppWidget parser: Required attributes packageName, className, spanX and spanY.
461 * Options child nodes: <extra key=... value=... />
462 */
463 protected class AppWidgetParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700464
465 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700466 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 throws XmlPullParserException, IOException {
468 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
469 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
470 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
471 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
472 return -1;
473 }
474
475 ComponentName cn = new ComponentName(packageName, className);
476 try {
477 mPackageManager.getReceiverInfo(cn, 0);
478 } catch (Exception e) {
479 String[] packages = mPackageManager.currentToCanonicalPackageNames(
480 new String[] { packageName });
481 cn = new ComponentName(packages[0], className);
482 try {
483 mPackageManager.getReceiverInfo(cn, 0);
484 } catch (Exception e1) {
485 if (LOGD) Log.d(TAG, "Can't find widget provider: " + className);
486 return -1;
487 }
488 }
489
490 mValues.put(Favorites.SPANX, getAttributeValue(parser, ATTR_SPAN_X));
491 mValues.put(Favorites.SPANY, getAttributeValue(parser, ATTR_SPAN_Y));
492
493 // Read the extras
494 Bundle extras = new Bundle();
495 int widgetDepth = parser.getDepth();
496 int type;
497 while ((type = parser.next()) != XmlPullParser.END_TAG ||
498 parser.getDepth() > widgetDepth) {
499 if (type != XmlPullParser.START_TAG) {
500 continue;
501 }
502
503 if (TAG_EXTRA.equals(parser.getName())) {
504 String key = getAttributeValue(parser, ATTR_KEY);
505 String value = getAttributeValue(parser, ATTR_VALUE);
506 if (key != null && value != null) {
507 extras.putString(key, value);
508 } else {
509 throw new RuntimeException("Widget extras must have a key and value");
510 }
511 } else {
512 throw new RuntimeException("Widgets can contain only extras");
513 }
514 }
515
516 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
517 long insertedId = -1;
518 try {
519 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
520
521 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn)) {
522 if (LOGD) Log.e(TAG, "Unable to bind app widget id " + cn);
523 return -1;
524 }
525
526 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
527 mValues.put(Favorites.APPWIDGET_ID, appWidgetId);
528 mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
529 mValues.put(Favorites._ID, mCallback.generateNewItemId());
530 insertedId = mCallback.insertAndCheck(mDb, mValues);
531 if (insertedId < 0) {
532 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
533 return insertedId;
534 }
535
536 // Send a broadcast to configure the widget
537 if (!extras.isEmpty()) {
538 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
539 intent.setComponent(cn);
540 intent.putExtras(extras);
541 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
542 mContext.sendBroadcast(intent);
543 }
544 } catch (RuntimeException ex) {
545 if (LOGD) Log.e(TAG, "Problem allocating appWidgetId", ex);
546 }
547 return insertedId;
548 }
549 }
550
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700551 protected class FolderParser implements TagParser {
552 private final HashMap<String, TagParser> mFolderElements;
553
554 public FolderParser() {
555 this(getFolderElementsMap());
556 }
557
558 public FolderParser(HashMap<String, TagParser> elements) {
559 mFolderElements = elements;
560 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700561
562 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700563 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700564 throws XmlPullParserException, IOException {
565 final String title;
566 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
567 if (titleResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700568 title = mSourceRes.getString(titleResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700569 } else {
570 title = mContext.getResources().getString(R.string.folder_name);
571 }
572
573 mValues.put(Favorites.TITLE, title);
574 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
575 mValues.put(Favorites.SPANX, 1);
576 mValues.put(Favorites.SPANY, 1);
577 mValues.put(Favorites._ID, mCallback.generateNewItemId());
578 long folderId = mCallback.insertAndCheck(mDb, mValues);
579 if (folderId < 0) {
580 if (LOGD) Log.e(TAG, "Unable to add folder");
581 return -1;
582 }
583
584 final ContentValues myValues = new ContentValues(mValues);
585 ArrayList<Long> folderItems = new ArrayList<Long>();
586
587 int type;
588 int folderDepth = parser.getDepth();
Sunny Goyal56a57bb2015-07-06 11:15:45 -0700589 int rank = 0;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700590 while ((type = parser.next()) != XmlPullParser.END_TAG ||
591 parser.getDepth() > folderDepth) {
592 if (type != XmlPullParser.START_TAG) {
593 continue;
594 }
595 mValues.clear();
596 mValues.put(Favorites.CONTAINER, folderId);
Sunny Goyal56a57bb2015-07-06 11:15:45 -0700597 mValues.put(Favorites.RANK, rank);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700598
599 TagParser tagParser = mFolderElements.get(parser.getName());
600 if (tagParser != null) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700601 final long id = tagParser.parseAndAdd(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700602 if (id >= 0) {
603 folderItems.add(id);
Sunny Goyal56a57bb2015-07-06 11:15:45 -0700604 rank++;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700605 }
606 } else {
607 throw new RuntimeException("Invalid folder item " + parser.getName());
608 }
609 }
610
611 long addedId = folderId;
612
613 // We can only have folders with >= 2 items, so we need to remove the
614 // folder and clean up if less than 2 items were included, or some
615 // failed to add, and less than 2 were actually added
616 if (folderItems.size() < 2) {
617 // Delete the folder
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700618 Uri uri = Favorites.getContentUri(folderId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700619 SqlArguments args = new SqlArguments(uri, null, null);
620 mDb.delete(args.table, args.where, args.args);
621 addedId = -1;
622
623 // If we have a single item, promote it to where the folder
624 // would have been.
625 if (folderItems.size() == 1) {
626 final ContentValues childValues = new ContentValues();
627 copyInteger(myValues, childValues, Favorites.CONTAINER);
628 copyInteger(myValues, childValues, Favorites.SCREEN);
629 copyInteger(myValues, childValues, Favorites.CELLX);
630 copyInteger(myValues, childValues, Favorites.CELLY);
631
632 addedId = folderItems.get(0);
633 mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
634 Favorites._ID + "=" + addedId, null);
635 }
636 }
637 return addedId;
638 }
639 }
640
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700641 protected static final void beginDocument(XmlPullParser parser, String firstElementName)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700642 throws XmlPullParserException, IOException {
643 int type;
644 while ((type = parser.next()) != XmlPullParser.START_TAG
645 && type != XmlPullParser.END_DOCUMENT);
646
647 if (type != XmlPullParser.START_TAG) {
648 throw new XmlPullParserException("No start tag found");
649 }
650
651 if (!parser.getName().equals(firstElementName)) {
652 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
653 ", expected " + firstElementName);
654 }
655 }
656
Sunny Goyal96a09632015-12-16 11:32:54 -0800657 private static String convertToDistanceFromEnd(String value, int endValue) {
658 if (!TextUtils.isEmpty(value)) {
659 int x = Integer.parseInt(value);
660 if (x < 0) {
661 return Integer.toString(endValue + x);
662 }
663 }
664 return value;
665 }
666
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700667 /**
668 * Return attribute value, attempting launcher-specific namespace first
669 * before falling back to anonymous attribute.
670 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700671 protected static String getAttributeValue(XmlResourceParser parser, String attribute) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700672 String value = parser.getAttributeValue(
673 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
674 if (value == null) {
675 value = parser.getAttributeValue(null, attribute);
676 }
677 return value;
678 }
679
680 /**
681 * Return attribute resource value, attempting launcher-specific namespace
682 * first before falling back to anonymous attribute.
683 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700684 protected static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700685 int defaultValue) {
686 int value = parser.getAttributeResourceValue(
687 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
688 defaultValue);
689 if (value == defaultValue) {
690 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
691 }
692 return value;
693 }
694
695 public static interface LayoutParserCallback {
696 long generateNewItemId();
697
698 long insertAndCheck(SQLiteDatabase db, ContentValues values);
699 }
700
Adam Cohen091440a2015-03-18 14:16:05 -0700701 @Thunk static void copyInteger(ContentValues from, ContentValues to, String key) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700702 to.put(key, from.getAsInteger(key));
703 }
704}