blob: 382066094d4e03175aaacec5c10a5cf80ad94328 [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;
119 private final LayoutParserCallback mCallback;
120
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 Goyal3a5a9d12014-10-01 15:33:41 -0700129 private 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 Goyal0fe505b2014-08-06 09:55:36 -0700136 mContext = context;
137 mAppWidgetHost = appWidgetHost;
138 mCallback = callback;
139
140 mPackageManager = context.getPackageManager();
141 mValues = new ContentValues();
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700142 mRootTag = rootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700143
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700144 mSourceRes = res;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700145 mLayoutId = layoutId;
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700146 mHotseatAllAppsRank = LauncherAppState.getInstance()
147 .getDynamicGrid().getDeviceProfile().hotseatAllAppsRank;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700148 }
149
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700150 /**
151 * Loads the layout in the db and returns the number of entries added on the desktop.
152 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700153 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
154 mDb = db;
155 try {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700156 return parseLayout(mLayoutId, screenIds);
Sameer Padala8fd74832014-09-08 16:00:29 -0700157 } catch (Exception e) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700158 Log.w(TAG, "Got exception parsing layout.", e);
159 return -1;
160 }
161 }
162
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700163 /**
164 * Parses the layout and returns the number of elements added on the homescreen.
165 */
166 protected int parseLayout(int layoutId, ArrayList<Long> screenIds)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700167 throws XmlPullParserException, IOException {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700168 XmlResourceParser parser = mSourceRes.getXml(layoutId);
169 beginDocument(parser, mRootTag);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700170 final int depth = parser.getDepth();
171 int type;
172 HashMap<String, TagParser> tagParserMap = getLayoutElementsMap();
173 int count = 0;
174
175 while (((type = parser.next()) != XmlPullParser.END_TAG ||
176 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
177 if (type != XmlPullParser.START_TAG) {
178 continue;
179 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700180 count += parseAndAddNode(parser, tagParserMap, screenIds);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700181 }
182 return count;
183 }
184
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700185 /**
186 * Parses container and screenId attribute from the current tag, and puts it in the out.
187 * @param out array of size 2.
188 */
189 protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
190 if (HOTSEAT_CONTAINER_NAME.equals(getAttributeValue(parser, ATTR_CONTAINER))) {
191 out[0] = Favorites.CONTAINER_HOTSEAT;
192 // Hack: hotseat items are stored using screen ids
193 long rank = Long.parseLong(getAttributeValue(parser, ATTR_RANK));
194 out[1] = (rank < mHotseatAllAppsRank) ? rank : (rank + 1);
195 } else {
196 out[0] = Favorites.CONTAINER_DESKTOP;
197 out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
198 }
199 }
200
201 /**
202 * Parses the current node and returns the number of elements added.
203 */
204 protected int parseAndAddNode(
205 XmlResourceParser parser,
206 HashMap<String, TagParser> tagParserMap,
207 ArrayList<Long> screenIds)
208 throws XmlPullParserException, IOException {
Sunny Goyalb564efb2015-01-23 13:45:20 -0800209
210 if (TAG_INCLUDE.equals(parser.getName())) {
211 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
212 if (resId != 0) {
213 // recursively load some more favorites, why not?
214 return parseLayout(resId, screenIds);
215 } else {
216 return 0;
217 }
218 }
219
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700220 mValues.clear();
221 parseContainerAndScreen(parser, mTemp);
222 final long container = mTemp[0];
223 final long screenId = mTemp[1];
224
225 mValues.put(Favorites.CONTAINER, container);
226 mValues.put(Favorites.SCREEN, screenId);
227 mValues.put(Favorites.CELLX, getAttributeValue(parser, ATTR_X));
228 mValues.put(Favorites.CELLY, getAttributeValue(parser, ATTR_Y));
229
230 TagParser tagParser = tagParserMap.get(parser.getName());
231 if (tagParser == null) {
232 if (LOGD) Log.d(TAG, "Ignoring unknown element tag: " + parser.getName());
233 return 0;
234 }
235 long newElementId = tagParser.parseAndAdd(parser);
236 if (newElementId >= 0) {
237 // Keep track of the set of screens which need to be added to the db.
238 if (!screenIds.contains(screenId) &&
239 container == Favorites.CONTAINER_DESKTOP) {
240 screenIds.add(screenId);
241 }
242 return 1;
243 }
244 return 0;
245 }
246
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700247 protected long addShortcut(String title, Intent intent, int type) {
248 long id = mCallback.generateNewItemId();
249 mValues.put(Favorites.INTENT, intent.toUri(0));
250 mValues.put(Favorites.TITLE, title);
251 mValues.put(Favorites.ITEM_TYPE, type);
252 mValues.put(Favorites.SPANX, 1);
253 mValues.put(Favorites.SPANY, 1);
254 mValues.put(Favorites._ID, id);
255 if (mCallback.insertAndCheck(mDb, mValues) < 0) {
256 return -1;
257 } else {
258 return id;
259 }
260 }
261
262 protected HashMap<String, TagParser> getFolderElementsMap() {
263 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
264 parsers.put(TAG_APP_ICON, new AppShortcutParser());
265 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700266 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700267 return parsers;
268 }
269
270 protected HashMap<String, TagParser> getLayoutElementsMap() {
271 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
272 parsers.put(TAG_APP_ICON, new AppShortcutParser());
273 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
274 parsers.put(TAG_FOLDER, new FolderParser());
275 parsers.put(TAG_APPWIDGET, new AppWidgetParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700276 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700277 return parsers;
278 }
279
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700280 protected interface TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700281 /**
282 * Parses the tag and adds to the db
283 * @return the id of the row added or -1;
284 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700285 long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700286 throws XmlPullParserException, IOException;
287 }
288
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700289 /**
290 * App shortcuts: required attributes packageName and className
291 */
292 protected class AppShortcutParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700293
294 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700295 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700296 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
297 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
298
299 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
300 ActivityInfo info;
301 try {
302 ComponentName cn;
303 try {
304 cn = new ComponentName(packageName, className);
305 info = mPackageManager.getActivityInfo(cn, 0);
306 } catch (PackageManager.NameNotFoundException nnfe) {
307 String[] packages = mPackageManager.currentToCanonicalPackageNames(
308 new String[] { packageName });
309 cn = new ComponentName(packages[0], className);
310 info = mPackageManager.getActivityInfo(cn, 0);
311 }
312 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
313 .addCategory(Intent.CATEGORY_LAUNCHER)
314 .setComponent(cn)
315 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
316 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
317
318 return addShortcut(info.loadLabel(mPackageManager).toString(),
319 intent, Favorites.ITEM_TYPE_APPLICATION);
320 } catch (PackageManager.NameNotFoundException e) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700321 if (LOGD) Log.w(TAG, "Unable to add favorite: " + packageName + "/" + className, e);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700322 }
323 return -1;
324 } else {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700325 return invalidPackageOrClass(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700326 }
327 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700328
329 /**
330 * Helper method to allow extending the parser capabilities
331 */
332 protected long invalidPackageOrClass(XmlResourceParser parser) {
333 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
334 return -1;
335 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700336 }
337
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700338 /**
339 * AutoInstall: required attributes packageName and className
340 */
341 protected class AutoInstallParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700342
343 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700344 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700345 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
346 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
347 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
348 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
349 return -1;
350 }
351
Sunny Goyal34942622014-08-29 17:20:55 -0700352 mValues.put(Favorites.RESTORED, ShortcutInfo.FLAG_AUTOINTALL_ICON);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700353 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
354 .addCategory(Intent.CATEGORY_LAUNCHER)
355 .setComponent(new ComponentName(packageName, className))
356 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
357 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
358 return addShortcut(mContext.getString(R.string.package_state_unknown), intent,
359 Favorites.ITEM_TYPE_APPLICATION);
360 }
361 }
362
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700363 /**
364 * Parses a web shortcut. Required attributes url, icon, title
365 */
366 protected class ShortcutParser implements TagParser {
367
368 private final Resources mIconRes;
369
370 public ShortcutParser(Resources iconRes) {
371 mIconRes = iconRes;
372 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700373
374 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700375 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700376 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
377 final int iconId = getAttributeResourceValue(parser, ATTR_ICON, 0);
378
379 if (titleResId == 0 || iconId == 0) {
380 if (LOGD) Log.d(TAG, "Ignoring shortcut");
381 return -1;
382 }
383
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700384 final Intent intent = parseIntent(parser);
385 if (intent == null) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700386 return -1;
387 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700388
389 Drawable icon = mIconRes.getDrawable(iconId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700390 if (icon == null) {
391 if (LOGD) Log.d(TAG, "Ignoring shortcut, can't load icon");
392 return -1;
393 }
394
395 ItemInfo.writeBitmap(mValues, Utilities.createIconBitmap(icon, mContext));
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700396 mValues.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
397 mValues.put(Favorites.ICON_PACKAGE, mIconRes.getResourcePackageName(iconId));
398 mValues.put(Favorites.ICON_RESOURCE, mIconRes.getResourceName(iconId));
399
400 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700401 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700402 return addShortcut(mSourceRes.getString(titleResId),
403 intent, Favorites.ITEM_TYPE_SHORTCUT);
404 }
405
406 protected Intent parseIntent(XmlResourceParser parser) {
407 final String url = getAttributeValue(parser, ATTR_URL);
408 if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
409 if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
410 return null;
411 }
412 return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700413 }
414 }
415
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700416 /**
417 * AppWidget parser: Required attributes packageName, className, spanX and spanY.
418 * Options child nodes: <extra key=... value=... />
419 */
420 protected class AppWidgetParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700421
422 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700423 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700424 throws XmlPullParserException, IOException {
425 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
426 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
427 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
428 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
429 return -1;
430 }
431
432 ComponentName cn = new ComponentName(packageName, className);
433 try {
434 mPackageManager.getReceiverInfo(cn, 0);
435 } catch (Exception e) {
436 String[] packages = mPackageManager.currentToCanonicalPackageNames(
437 new String[] { packageName });
438 cn = new ComponentName(packages[0], className);
439 try {
440 mPackageManager.getReceiverInfo(cn, 0);
441 } catch (Exception e1) {
442 if (LOGD) Log.d(TAG, "Can't find widget provider: " + className);
443 return -1;
444 }
445 }
446
447 mValues.put(Favorites.SPANX, getAttributeValue(parser, ATTR_SPAN_X));
448 mValues.put(Favorites.SPANY, getAttributeValue(parser, ATTR_SPAN_Y));
449
450 // Read the extras
451 Bundle extras = new Bundle();
452 int widgetDepth = parser.getDepth();
453 int type;
454 while ((type = parser.next()) != XmlPullParser.END_TAG ||
455 parser.getDepth() > widgetDepth) {
456 if (type != XmlPullParser.START_TAG) {
457 continue;
458 }
459
460 if (TAG_EXTRA.equals(parser.getName())) {
461 String key = getAttributeValue(parser, ATTR_KEY);
462 String value = getAttributeValue(parser, ATTR_VALUE);
463 if (key != null && value != null) {
464 extras.putString(key, value);
465 } else {
466 throw new RuntimeException("Widget extras must have a key and value");
467 }
468 } else {
469 throw new RuntimeException("Widgets can contain only extras");
470 }
471 }
472
473 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
474 long insertedId = -1;
475 try {
476 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
477
478 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn)) {
479 if (LOGD) Log.e(TAG, "Unable to bind app widget id " + cn);
480 return -1;
481 }
482
483 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
484 mValues.put(Favorites.APPWIDGET_ID, appWidgetId);
485 mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
486 mValues.put(Favorites._ID, mCallback.generateNewItemId());
487 insertedId = mCallback.insertAndCheck(mDb, mValues);
488 if (insertedId < 0) {
489 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
490 return insertedId;
491 }
492
493 // Send a broadcast to configure the widget
494 if (!extras.isEmpty()) {
495 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
496 intent.setComponent(cn);
497 intent.putExtras(extras);
498 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
499 mContext.sendBroadcast(intent);
500 }
501 } catch (RuntimeException ex) {
502 if (LOGD) Log.e(TAG, "Problem allocating appWidgetId", ex);
503 }
504 return insertedId;
505 }
506 }
507
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700508 protected class FolderParser implements TagParser {
509 private final HashMap<String, TagParser> mFolderElements;
510
511 public FolderParser() {
512 this(getFolderElementsMap());
513 }
514
515 public FolderParser(HashMap<String, TagParser> elements) {
516 mFolderElements = elements;
517 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700518
519 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700520 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700521 throws XmlPullParserException, IOException {
522 final String title;
523 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
524 if (titleResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700525 title = mSourceRes.getString(titleResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700526 } else {
527 title = mContext.getResources().getString(R.string.folder_name);
528 }
529
530 mValues.put(Favorites.TITLE, title);
531 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
532 mValues.put(Favorites.SPANX, 1);
533 mValues.put(Favorites.SPANY, 1);
534 mValues.put(Favorites._ID, mCallback.generateNewItemId());
535 long folderId = mCallback.insertAndCheck(mDb, mValues);
536 if (folderId < 0) {
537 if (LOGD) Log.e(TAG, "Unable to add folder");
538 return -1;
539 }
540
541 final ContentValues myValues = new ContentValues(mValues);
542 ArrayList<Long> folderItems = new ArrayList<Long>();
543
544 int type;
545 int folderDepth = parser.getDepth();
546 while ((type = parser.next()) != XmlPullParser.END_TAG ||
547 parser.getDepth() > folderDepth) {
548 if (type != XmlPullParser.START_TAG) {
549 continue;
550 }
551 mValues.clear();
552 mValues.put(Favorites.CONTAINER, folderId);
553
554 TagParser tagParser = mFolderElements.get(parser.getName());
555 if (tagParser != null) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700556 final long id = tagParser.parseAndAdd(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700557 if (id >= 0) {
558 folderItems.add(id);
559 }
560 } else {
561 throw new RuntimeException("Invalid folder item " + parser.getName());
562 }
563 }
564
565 long addedId = folderId;
566
567 // We can only have folders with >= 2 items, so we need to remove the
568 // folder and clean up if less than 2 items were included, or some
569 // failed to add, and less than 2 were actually added
570 if (folderItems.size() < 2) {
571 // Delete the folder
572 Uri uri = Favorites.getContentUri(folderId, false);
573 SqlArguments args = new SqlArguments(uri, null, null);
574 mDb.delete(args.table, args.where, args.args);
575 addedId = -1;
576
577 // If we have a single item, promote it to where the folder
578 // would have been.
579 if (folderItems.size() == 1) {
580 final ContentValues childValues = new ContentValues();
581 copyInteger(myValues, childValues, Favorites.CONTAINER);
582 copyInteger(myValues, childValues, Favorites.SCREEN);
583 copyInteger(myValues, childValues, Favorites.CELLX);
584 copyInteger(myValues, childValues, Favorites.CELLY);
585
586 addedId = folderItems.get(0);
587 mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
588 Favorites._ID + "=" + addedId, null);
589 }
590 }
591 return addedId;
592 }
593 }
594
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700595 protected static final void beginDocument(XmlPullParser parser, String firstElementName)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700596 throws XmlPullParserException, IOException {
597 int type;
598 while ((type = parser.next()) != XmlPullParser.START_TAG
599 && type != XmlPullParser.END_DOCUMENT);
600
601 if (type != XmlPullParser.START_TAG) {
602 throw new XmlPullParserException("No start tag found");
603 }
604
605 if (!parser.getName().equals(firstElementName)) {
606 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
607 ", expected " + firstElementName);
608 }
609 }
610
611 /**
612 * Return attribute value, attempting launcher-specific namespace first
613 * before falling back to anonymous attribute.
614 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700615 protected static String getAttributeValue(XmlResourceParser parser, String attribute) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700616 String value = parser.getAttributeValue(
617 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
618 if (value == null) {
619 value = parser.getAttributeValue(null, attribute);
620 }
621 return value;
622 }
623
624 /**
625 * Return attribute resource value, attempting launcher-specific namespace
626 * first before falling back to anonymous attribute.
627 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700628 protected static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700629 int defaultValue) {
630 int value = parser.getAttributeResourceValue(
631 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
632 defaultValue);
633 if (value == defaultValue) {
634 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
635 }
636 return value;
637 }
638
639 public static interface LayoutParserCallback {
640 long generateNewItemId();
641
642 long insertAndCheck(SQLiteDatabase db, ContentValues values);
643 }
644
645 private static void copyInteger(ContentValues from, ContentValues to, String key) {
646 to.put(key, from.getAsInteger(key));
647 }
648}