blob: 908bd3d797144a7570b284d8c207c149176b777d [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;
40
41import org.xmlpull.v1.XmlPullParser;
42import org.xmlpull.v1.XmlPullParserException;
43
44import java.io.IOException;
45import java.util.ArrayList;
46import java.util.HashMap;
47
48/**
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070049 * Layout parsing code for auto installs layout
Sunny Goyal0fe505b2014-08-06 09:55:36 -070050 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070051public class AutoInstallsLayout {
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052 private static final String TAG = "AutoInstalls";
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070053 private static final boolean LOGD = false;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070054
55 /** Marker action used to discover a package which defines launcher customization */
56 static final String ACTION_LAUNCHER_CUSTOMIZATION =
Sunny Goyal2233c882014-09-18 14:36:48 -070057 "android.autoinstalls.config.action.PLAY_AUTO_INSTALL";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070058
59 private static final String LAYOUT_RES = "default_layout";
60
61 static AutoInstallsLayout get(Context context, AppWidgetHost appWidgetHost,
62 LayoutParserCallback callback) {
63 Pair<String, Resources> customizationApkInfo = Utilities.findSystemApk(
64 ACTION_LAUNCHER_CUSTOMIZATION, context.getPackageManager());
65 if (customizationApkInfo == null) {
66 return null;
67 }
68
69 String pkg = customizationApkInfo.first;
70 Resources res = customizationApkInfo.second;
71 int layoutId = res.getIdentifier(LAYOUT_RES, "xml", pkg);
72 if (layoutId == 0) {
73 Log.e(TAG, "Layout definition not found in package: " + pkg);
74 return null;
75 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070076 return new AutoInstallsLayout(context, appWidgetHost, callback, res, layoutId,
77 TAG_WORKSPACE);
Sunny Goyal0fe505b2014-08-06 09:55:36 -070078 }
79
80 // Object Tags
Sunny Goyalb564efb2015-01-23 13:45:20 -080081 private static final String TAG_INCLUDE = "include";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070082 private static final String TAG_WORKSPACE = "workspace";
83 private static final String TAG_APP_ICON = "appicon";
84 private static final String TAG_AUTO_INSTALL = "autoinstall";
85 private static final String TAG_FOLDER = "folder";
86 private static final String TAG_APPWIDGET = "appwidget";
87 private static final String TAG_SHORTCUT = "shortcut";
88 private static final String TAG_EXTRA = "extra";
89
90 private static final String ATTR_CONTAINER = "container";
91 private static final String ATTR_RANK = "rank";
92
93 private static final String ATTR_PACKAGE_NAME = "packageName";
94 private static final String ATTR_CLASS_NAME = "className";
95 private static final String ATTR_TITLE = "title";
96 private static final String ATTR_SCREEN = "screen";
97 private static final String ATTR_X = "x";
98 private static final String ATTR_Y = "y";
99 private static final String ATTR_SPAN_X = "spanX";
100 private static final String ATTR_SPAN_Y = "spanY";
101 private static final String ATTR_ICON = "icon";
102 private static final String ATTR_URL = "url";
103
Sunny Goyalb564efb2015-01-23 13:45:20 -0800104 // Attrs for "Include"
105 private static final String ATTR_WORKSPACE = "workspace";
106
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700107 // Style attrs -- "Extra"
108 private static final String ATTR_KEY = "key";
109 private static final String ATTR_VALUE = "value";
110
111 private static final String HOTSEAT_CONTAINER_NAME =
112 Favorites.containerToString(Favorites.CONTAINER_HOTSEAT);
113
114 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
115 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
116
117 private final Context mContext;
118 private final AppWidgetHost mAppWidgetHost;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800119 protected final LayoutParserCallback mCallback;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700120
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700121 protected final PackageManager mPackageManager;
122 protected final Resources mSourceRes;
123 protected final int mLayoutId;
124
125 private final int mHotseatAllAppsRank;
126
127 private final long[] mTemp = new long[2];
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700128 private final ContentValues mValues;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800129 protected final String mRootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700130
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700131 protected SQLiteDatabase mDb;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700132
133 public AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700134 LayoutParserCallback callback, Resources res,
135 int layoutId, String rootTag) {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800136 this(context, appWidgetHost, callback, res, layoutId, rootTag,
137 LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().hotseatAllAppsRank);
138 }
139
140 public AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
141 LayoutParserCallback callback, Resources res,
142 int layoutId, String rootTag, int hotseatAllAppsRank) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700143 mContext = context;
144 mAppWidgetHost = appWidgetHost;
145 mCallback = callback;
146
147 mPackageManager = context.getPackageManager();
148 mValues = new ContentValues();
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700149 mRootTag = rootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700150
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700151 mSourceRes = res;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700152 mLayoutId = layoutId;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800153 mHotseatAllAppsRank = hotseatAllAppsRank;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700154 }
155
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700156 /**
157 * Loads the layout in the db and returns the number of entries added on the desktop.
158 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700159 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
160 mDb = db;
161 try {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700162 return parseLayout(mLayoutId, screenIds);
Sameer Padala8fd74832014-09-08 16:00:29 -0700163 } catch (Exception e) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700164 Log.w(TAG, "Got exception parsing layout.", e);
165 return -1;
166 }
167 }
168
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700169 /**
170 * Parses the layout and returns the number of elements added on the homescreen.
171 */
172 protected int parseLayout(int layoutId, ArrayList<Long> screenIds)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700173 throws XmlPullParserException, IOException {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700174 XmlResourceParser parser = mSourceRes.getXml(layoutId);
175 beginDocument(parser, mRootTag);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700176 final int depth = parser.getDepth();
177 int type;
178 HashMap<String, TagParser> tagParserMap = getLayoutElementsMap();
179 int count = 0;
180
181 while (((type = parser.next()) != XmlPullParser.END_TAG ||
182 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
183 if (type != XmlPullParser.START_TAG) {
184 continue;
185 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700186 count += parseAndAddNode(parser, tagParserMap, screenIds);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700187 }
188 return count;
189 }
190
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700191 /**
192 * Parses container and screenId attribute from the current tag, and puts it in the out.
193 * @param out array of size 2.
194 */
195 protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
196 if (HOTSEAT_CONTAINER_NAME.equals(getAttributeValue(parser, ATTR_CONTAINER))) {
197 out[0] = Favorites.CONTAINER_HOTSEAT;
198 // Hack: hotseat items are stored using screen ids
199 long rank = Long.parseLong(getAttributeValue(parser, ATTR_RANK));
200 out[1] = (rank < mHotseatAllAppsRank) ? rank : (rank + 1);
201 } else {
202 out[0] = Favorites.CONTAINER_DESKTOP;
203 out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
204 }
205 }
206
207 /**
208 * Parses the current node and returns the number of elements added.
209 */
210 protected int parseAndAddNode(
211 XmlResourceParser parser,
212 HashMap<String, TagParser> tagParserMap,
213 ArrayList<Long> screenIds)
214 throws XmlPullParserException, IOException {
Sunny Goyalb564efb2015-01-23 13:45:20 -0800215
216 if (TAG_INCLUDE.equals(parser.getName())) {
217 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
218 if (resId != 0) {
219 // recursively load some more favorites, why not?
220 return parseLayout(resId, screenIds);
221 } else {
222 return 0;
223 }
224 }
225
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700226 mValues.clear();
227 parseContainerAndScreen(parser, mTemp);
228 final long container = mTemp[0];
229 final long screenId = mTemp[1];
230
231 mValues.put(Favorites.CONTAINER, container);
232 mValues.put(Favorites.SCREEN, screenId);
233 mValues.put(Favorites.CELLX, getAttributeValue(parser, ATTR_X));
234 mValues.put(Favorites.CELLY, getAttributeValue(parser, ATTR_Y));
235
236 TagParser tagParser = tagParserMap.get(parser.getName());
237 if (tagParser == null) {
238 if (LOGD) Log.d(TAG, "Ignoring unknown element tag: " + parser.getName());
239 return 0;
240 }
241 long newElementId = tagParser.parseAndAdd(parser);
242 if (newElementId >= 0) {
243 // Keep track of the set of screens which need to be added to the db.
244 if (!screenIds.contains(screenId) &&
245 container == Favorites.CONTAINER_DESKTOP) {
246 screenIds.add(screenId);
247 }
248 return 1;
249 }
250 return 0;
251 }
252
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700253 protected long addShortcut(String title, Intent intent, int type) {
254 long id = mCallback.generateNewItemId();
255 mValues.put(Favorites.INTENT, intent.toUri(0));
256 mValues.put(Favorites.TITLE, title);
257 mValues.put(Favorites.ITEM_TYPE, type);
258 mValues.put(Favorites.SPANX, 1);
259 mValues.put(Favorites.SPANY, 1);
260 mValues.put(Favorites._ID, id);
261 if (mCallback.insertAndCheck(mDb, mValues) < 0) {
262 return -1;
263 } else {
264 return id;
265 }
266 }
267
268 protected HashMap<String, TagParser> getFolderElementsMap() {
269 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
270 parsers.put(TAG_APP_ICON, new AppShortcutParser());
271 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700272 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700273 return parsers;
274 }
275
276 protected HashMap<String, TagParser> getLayoutElementsMap() {
277 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
278 parsers.put(TAG_APP_ICON, new AppShortcutParser());
279 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
280 parsers.put(TAG_FOLDER, new FolderParser());
281 parsers.put(TAG_APPWIDGET, new AppWidgetParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700282 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700283 return parsers;
284 }
285
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700286 protected interface TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700287 /**
288 * Parses the tag and adds to the db
289 * @return the id of the row added or -1;
290 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700291 long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700292 throws XmlPullParserException, IOException;
293 }
294
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700295 /**
296 * App shortcuts: required attributes packageName and className
297 */
298 protected class AppShortcutParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700299
300 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700301 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700302 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
303 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
304
305 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
306 ActivityInfo info;
307 try {
308 ComponentName cn;
309 try {
310 cn = new ComponentName(packageName, className);
311 info = mPackageManager.getActivityInfo(cn, 0);
312 } catch (PackageManager.NameNotFoundException nnfe) {
313 String[] packages = mPackageManager.currentToCanonicalPackageNames(
314 new String[] { packageName });
315 cn = new ComponentName(packages[0], className);
316 info = mPackageManager.getActivityInfo(cn, 0);
317 }
318 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
319 .addCategory(Intent.CATEGORY_LAUNCHER)
320 .setComponent(cn)
321 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
322 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
323
324 return addShortcut(info.loadLabel(mPackageManager).toString(),
325 intent, Favorites.ITEM_TYPE_APPLICATION);
326 } catch (PackageManager.NameNotFoundException e) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700327 if (LOGD) Log.w(TAG, "Unable to add favorite: " + packageName + "/" + className, e);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700328 }
329 return -1;
330 } else {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700331 return invalidPackageOrClass(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700332 }
333 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700334
335 /**
336 * Helper method to allow extending the parser capabilities
337 */
338 protected long invalidPackageOrClass(XmlResourceParser parser) {
339 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
340 return -1;
341 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700342 }
343
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700344 /**
345 * AutoInstall: required attributes packageName and className
346 */
347 protected class AutoInstallParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700348
349 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700350 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700351 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
352 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
353 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
354 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
355 return -1;
356 }
357
Sunny Goyal34942622014-08-29 17:20:55 -0700358 mValues.put(Favorites.RESTORED, ShortcutInfo.FLAG_AUTOINTALL_ICON);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700359 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
360 .addCategory(Intent.CATEGORY_LAUNCHER)
361 .setComponent(new ComponentName(packageName, className))
362 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
363 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
364 return addShortcut(mContext.getString(R.string.package_state_unknown), intent,
365 Favorites.ITEM_TYPE_APPLICATION);
366 }
367 }
368
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700369 /**
370 * Parses a web shortcut. Required attributes url, icon, title
371 */
372 protected class ShortcutParser implements TagParser {
373
374 private final Resources mIconRes;
375
376 public ShortcutParser(Resources iconRes) {
377 mIconRes = iconRes;
378 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700379
380 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700381 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700382 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
383 final int iconId = getAttributeResourceValue(parser, ATTR_ICON, 0);
384
385 if (titleResId == 0 || iconId == 0) {
386 if (LOGD) Log.d(TAG, "Ignoring shortcut");
387 return -1;
388 }
389
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700390 final Intent intent = parseIntent(parser);
391 if (intent == null) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700392 return -1;
393 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700394
395 Drawable icon = mIconRes.getDrawable(iconId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700396 if (icon == null) {
397 if (LOGD) Log.d(TAG, "Ignoring shortcut, can't load icon");
398 return -1;
399 }
400
401 ItemInfo.writeBitmap(mValues, Utilities.createIconBitmap(icon, mContext));
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700402 mValues.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
403 mValues.put(Favorites.ICON_PACKAGE, mIconRes.getResourcePackageName(iconId));
404 mValues.put(Favorites.ICON_RESOURCE, mIconRes.getResourceName(iconId));
405
406 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700407 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700408 return addShortcut(mSourceRes.getString(titleResId),
409 intent, Favorites.ITEM_TYPE_SHORTCUT);
410 }
411
412 protected Intent parseIntent(XmlResourceParser parser) {
413 final String url = getAttributeValue(parser, ATTR_URL);
414 if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
415 if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
416 return null;
417 }
418 return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700419 }
420 }
421
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700422 /**
423 * AppWidget parser: Required attributes packageName, className, spanX and spanY.
424 * Options child nodes: <extra key=... value=... />
425 */
426 protected class AppWidgetParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700427
428 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700429 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700430 throws XmlPullParserException, IOException {
431 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
432 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
433 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
434 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
435 return -1;
436 }
437
438 ComponentName cn = new ComponentName(packageName, className);
439 try {
440 mPackageManager.getReceiverInfo(cn, 0);
441 } catch (Exception e) {
442 String[] packages = mPackageManager.currentToCanonicalPackageNames(
443 new String[] { packageName });
444 cn = new ComponentName(packages[0], className);
445 try {
446 mPackageManager.getReceiverInfo(cn, 0);
447 } catch (Exception e1) {
448 if (LOGD) Log.d(TAG, "Can't find widget provider: " + className);
449 return -1;
450 }
451 }
452
453 mValues.put(Favorites.SPANX, getAttributeValue(parser, ATTR_SPAN_X));
454 mValues.put(Favorites.SPANY, getAttributeValue(parser, ATTR_SPAN_Y));
455
456 // Read the extras
457 Bundle extras = new Bundle();
458 int widgetDepth = parser.getDepth();
459 int type;
460 while ((type = parser.next()) != XmlPullParser.END_TAG ||
461 parser.getDepth() > widgetDepth) {
462 if (type != XmlPullParser.START_TAG) {
463 continue;
464 }
465
466 if (TAG_EXTRA.equals(parser.getName())) {
467 String key = getAttributeValue(parser, ATTR_KEY);
468 String value = getAttributeValue(parser, ATTR_VALUE);
469 if (key != null && value != null) {
470 extras.putString(key, value);
471 } else {
472 throw new RuntimeException("Widget extras must have a key and value");
473 }
474 } else {
475 throw new RuntimeException("Widgets can contain only extras");
476 }
477 }
478
479 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
480 long insertedId = -1;
481 try {
482 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
483
484 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn)) {
485 if (LOGD) Log.e(TAG, "Unable to bind app widget id " + cn);
486 return -1;
487 }
488
489 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
490 mValues.put(Favorites.APPWIDGET_ID, appWidgetId);
491 mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
492 mValues.put(Favorites._ID, mCallback.generateNewItemId());
493 insertedId = mCallback.insertAndCheck(mDb, mValues);
494 if (insertedId < 0) {
495 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
496 return insertedId;
497 }
498
499 // Send a broadcast to configure the widget
500 if (!extras.isEmpty()) {
501 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
502 intent.setComponent(cn);
503 intent.putExtras(extras);
504 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
505 mContext.sendBroadcast(intent);
506 }
507 } catch (RuntimeException ex) {
508 if (LOGD) Log.e(TAG, "Problem allocating appWidgetId", ex);
509 }
510 return insertedId;
511 }
512 }
513
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700514 protected class FolderParser implements TagParser {
515 private final HashMap<String, TagParser> mFolderElements;
516
517 public FolderParser() {
518 this(getFolderElementsMap());
519 }
520
521 public FolderParser(HashMap<String, TagParser> elements) {
522 mFolderElements = elements;
523 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700524
525 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700526 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700527 throws XmlPullParserException, IOException {
528 final String title;
529 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
530 if (titleResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700531 title = mSourceRes.getString(titleResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700532 } else {
533 title = mContext.getResources().getString(R.string.folder_name);
534 }
535
536 mValues.put(Favorites.TITLE, title);
537 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
538 mValues.put(Favorites.SPANX, 1);
539 mValues.put(Favorites.SPANY, 1);
540 mValues.put(Favorites._ID, mCallback.generateNewItemId());
541 long folderId = mCallback.insertAndCheck(mDb, mValues);
542 if (folderId < 0) {
543 if (LOGD) Log.e(TAG, "Unable to add folder");
544 return -1;
545 }
546
547 final ContentValues myValues = new ContentValues(mValues);
548 ArrayList<Long> folderItems = new ArrayList<Long>();
549
550 int type;
551 int folderDepth = parser.getDepth();
552 while ((type = parser.next()) != XmlPullParser.END_TAG ||
553 parser.getDepth() > folderDepth) {
554 if (type != XmlPullParser.START_TAG) {
555 continue;
556 }
557 mValues.clear();
558 mValues.put(Favorites.CONTAINER, folderId);
559
560 TagParser tagParser = mFolderElements.get(parser.getName());
561 if (tagParser != null) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700562 final long id = tagParser.parseAndAdd(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700563 if (id >= 0) {
564 folderItems.add(id);
565 }
566 } else {
567 throw new RuntimeException("Invalid folder item " + parser.getName());
568 }
569 }
570
571 long addedId = folderId;
572
573 // We can only have folders with >= 2 items, so we need to remove the
574 // folder and clean up if less than 2 items were included, or some
575 // failed to add, and less than 2 were actually added
576 if (folderItems.size() < 2) {
577 // Delete the folder
578 Uri uri = Favorites.getContentUri(folderId, false);
579 SqlArguments args = new SqlArguments(uri, null, null);
580 mDb.delete(args.table, args.where, args.args);
581 addedId = -1;
582
583 // If we have a single item, promote it to where the folder
584 // would have been.
585 if (folderItems.size() == 1) {
586 final ContentValues childValues = new ContentValues();
587 copyInteger(myValues, childValues, Favorites.CONTAINER);
588 copyInteger(myValues, childValues, Favorites.SCREEN);
589 copyInteger(myValues, childValues, Favorites.CELLX);
590 copyInteger(myValues, childValues, Favorites.CELLY);
591
592 addedId = folderItems.get(0);
593 mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
594 Favorites._ID + "=" + addedId, null);
595 }
596 }
597 return addedId;
598 }
599 }
600
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700601 protected static final void beginDocument(XmlPullParser parser, String firstElementName)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700602 throws XmlPullParserException, IOException {
603 int type;
604 while ((type = parser.next()) != XmlPullParser.START_TAG
605 && type != XmlPullParser.END_DOCUMENT);
606
607 if (type != XmlPullParser.START_TAG) {
608 throw new XmlPullParserException("No start tag found");
609 }
610
611 if (!parser.getName().equals(firstElementName)) {
612 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
613 ", expected " + firstElementName);
614 }
615 }
616
617 /**
618 * Return attribute value, attempting launcher-specific namespace first
619 * before falling back to anonymous attribute.
620 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700621 protected static String getAttributeValue(XmlResourceParser parser, String attribute) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700622 String value = parser.getAttributeValue(
623 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
624 if (value == null) {
625 value = parser.getAttributeValue(null, attribute);
626 }
627 return value;
628 }
629
630 /**
631 * Return attribute resource value, attempting launcher-specific namespace
632 * first before falling back to anonymous attribute.
633 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700634 protected static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700635 int defaultValue) {
636 int value = parser.getAttributeResourceValue(
637 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
638 defaultValue);
639 if (value == defaultValue) {
640 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
641 }
642 return value;
643 }
644
645 public static interface LayoutParserCallback {
646 long generateNewItemId();
647
648 long insertAndCheck(SQLiteDatabase db, ContentValues values);
649 }
650
651 private static void copyInteger(ContentValues from, ContentValues to, String key) {
652 to.put(key, from.getAsInteger(key));
653 }
654}