blob: cbab08becb17e611825a1cfc65d0fd10b30403a0 [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;
48
49/**
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070050 * Layout parsing code for auto installs layout
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070052public class AutoInstallsLayout {
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053 private static final String TAG = "AutoInstalls";
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070054 private static final boolean LOGD = false;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070055
56 /** Marker action used to discover a package which defines launcher customization */
57 static final String ACTION_LAUNCHER_CUSTOMIZATION =
Sunny Goyal2233c882014-09-18 14:36:48 -070058 "android.autoinstalls.config.action.PLAY_AUTO_INSTALL";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070059
60 private static final String LAYOUT_RES = "default_layout";
61
62 static AutoInstallsLayout get(Context context, AppWidgetHost appWidgetHost,
63 LayoutParserCallback callback) {
64 Pair<String, Resources> customizationApkInfo = Utilities.findSystemApk(
65 ACTION_LAUNCHER_CUSTOMIZATION, context.getPackageManager());
66 if (customizationApkInfo == null) {
67 return null;
68 }
69
70 String pkg = customizationApkInfo.first;
71 Resources res = customizationApkInfo.second;
72 int layoutId = res.getIdentifier(LAYOUT_RES, "xml", pkg);
73 if (layoutId == 0) {
74 Log.e(TAG, "Layout definition not found in package: " + pkg);
75 return null;
76 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -070077 return new AutoInstallsLayout(context, appWidgetHost, callback, res, layoutId,
78 TAG_WORKSPACE);
Sunny Goyal0fe505b2014-08-06 09:55:36 -070079 }
80
81 // Object Tags
Sunny Goyalb564efb2015-01-23 13:45:20 -080082 private static final String TAG_INCLUDE = "include";
Sunny Goyal0fe505b2014-08-06 09:55:36 -070083 private static final String TAG_WORKSPACE = "workspace";
84 private static final String TAG_APP_ICON = "appicon";
85 private static final String TAG_AUTO_INSTALL = "autoinstall";
86 private static final String TAG_FOLDER = "folder";
87 private static final String TAG_APPWIDGET = "appwidget";
88 private static final String TAG_SHORTCUT = "shortcut";
89 private static final String TAG_EXTRA = "extra";
90
91 private static final String ATTR_CONTAINER = "container";
92 private static final String ATTR_RANK = "rank";
93
94 private static final String ATTR_PACKAGE_NAME = "packageName";
95 private static final String ATTR_CLASS_NAME = "className";
96 private static final String ATTR_TITLE = "title";
97 private static final String ATTR_SCREEN = "screen";
98 private static final String ATTR_X = "x";
99 private static final String ATTR_Y = "y";
100 private static final String ATTR_SPAN_X = "spanX";
101 private static final String ATTR_SPAN_Y = "spanY";
102 private static final String ATTR_ICON = "icon";
103 private static final String ATTR_URL = "url";
104
Sunny Goyalb564efb2015-01-23 13:45:20 -0800105 // Attrs for "Include"
106 private static final String ATTR_WORKSPACE = "workspace";
107
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700108 // Style attrs -- "Extra"
109 private static final String ATTR_KEY = "key";
110 private static final String ATTR_VALUE = "value";
111
112 private static final String HOTSEAT_CONTAINER_NAME =
113 Favorites.containerToString(Favorites.CONTAINER_HOTSEAT);
114
115 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
116 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
117
Adam Cohen091440a2015-03-18 14:16:05 -0700118 @Thunk final Context mContext;
119 @Thunk final AppWidgetHost mAppWidgetHost;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800120 protected final LayoutParserCallback mCallback;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700121
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700122 protected final PackageManager mPackageManager;
123 protected final Resources mSourceRes;
124 protected final int mLayoutId;
125
126 private final int mHotseatAllAppsRank;
127
128 private final long[] mTemp = new long[2];
Adam Cohen091440a2015-03-18 14:16:05 -0700129 @Thunk final ContentValues mValues;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800130 protected final String mRootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700131
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700132 protected SQLiteDatabase mDb;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700133
134 public AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700135 LayoutParserCallback callback, Resources res,
136 int layoutId, String rootTag) {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800137 this(context, appWidgetHost, callback, res, layoutId, rootTag,
138 LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().hotseatAllAppsRank);
139 }
140
141 public AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
142 LayoutParserCallback callback, Resources res,
143 int layoutId, String rootTag, int hotseatAllAppsRank) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700144 mContext = context;
145 mAppWidgetHost = appWidgetHost;
146 mCallback = callback;
147
148 mPackageManager = context.getPackageManager();
149 mValues = new ContentValues();
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700150 mRootTag = rootTag;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700151
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700152 mSourceRes = res;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700153 mLayoutId = layoutId;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800154 mHotseatAllAppsRank = hotseatAllAppsRank;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700155 }
156
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700157 /**
158 * Loads the layout in the db and returns the number of entries added on the desktop.
159 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700160 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
161 mDb = db;
162 try {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700163 return parseLayout(mLayoutId, screenIds);
Sameer Padala8fd74832014-09-08 16:00:29 -0700164 } catch (Exception e) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700165 Log.w(TAG, "Got exception parsing layout.", e);
166 return -1;
167 }
168 }
169
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700170 /**
171 * Parses the layout and returns the number of elements added on the homescreen.
172 */
173 protected int parseLayout(int layoutId, ArrayList<Long> screenIds)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700174 throws XmlPullParserException, IOException {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700175 XmlResourceParser parser = mSourceRes.getXml(layoutId);
176 beginDocument(parser, mRootTag);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700177 final int depth = parser.getDepth();
178 int type;
179 HashMap<String, TagParser> tagParserMap = getLayoutElementsMap();
180 int count = 0;
181
182 while (((type = parser.next()) != XmlPullParser.END_TAG ||
183 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
184 if (type != XmlPullParser.START_TAG) {
185 continue;
186 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700187 count += parseAndAddNode(parser, tagParserMap, screenIds);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700188 }
189 return count;
190 }
191
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700192 /**
193 * Parses container and screenId attribute from the current tag, and puts it in the out.
194 * @param out array of size 2.
195 */
196 protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
197 if (HOTSEAT_CONTAINER_NAME.equals(getAttributeValue(parser, ATTR_CONTAINER))) {
198 out[0] = Favorites.CONTAINER_HOTSEAT;
199 // Hack: hotseat items are stored using screen ids
200 long rank = Long.parseLong(getAttributeValue(parser, ATTR_RANK));
201 out[1] = (rank < mHotseatAllAppsRank) ? rank : (rank + 1);
202 } else {
203 out[0] = Favorites.CONTAINER_DESKTOP;
204 out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
205 }
206 }
207
208 /**
209 * Parses the current node and returns the number of elements added.
210 */
211 protected int parseAndAddNode(
212 XmlResourceParser parser,
213 HashMap<String, TagParser> tagParserMap,
214 ArrayList<Long> screenIds)
215 throws XmlPullParserException, IOException {
Sunny Goyalb564efb2015-01-23 13:45:20 -0800216
217 if (TAG_INCLUDE.equals(parser.getName())) {
218 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
219 if (resId != 0) {
220 // recursively load some more favorites, why not?
221 return parseLayout(resId, screenIds);
222 } else {
223 return 0;
224 }
225 }
226
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700227 mValues.clear();
228 parseContainerAndScreen(parser, mTemp);
229 final long container = mTemp[0];
230 final long screenId = mTemp[1];
231
232 mValues.put(Favorites.CONTAINER, container);
233 mValues.put(Favorites.SCREEN, screenId);
234 mValues.put(Favorites.CELLX, getAttributeValue(parser, ATTR_X));
235 mValues.put(Favorites.CELLY, getAttributeValue(parser, ATTR_Y));
236
237 TagParser tagParser = tagParserMap.get(parser.getName());
238 if (tagParser == null) {
239 if (LOGD) Log.d(TAG, "Ignoring unknown element tag: " + parser.getName());
240 return 0;
241 }
242 long newElementId = tagParser.parseAndAdd(parser);
243 if (newElementId >= 0) {
244 // Keep track of the set of screens which need to be added to the db.
245 if (!screenIds.contains(screenId) &&
246 container == Favorites.CONTAINER_DESKTOP) {
247 screenIds.add(screenId);
248 }
249 return 1;
250 }
251 return 0;
252 }
253
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700254 protected long addShortcut(String title, Intent intent, int type) {
255 long id = mCallback.generateNewItemId();
256 mValues.put(Favorites.INTENT, intent.toUri(0));
257 mValues.put(Favorites.TITLE, title);
258 mValues.put(Favorites.ITEM_TYPE, type);
259 mValues.put(Favorites.SPANX, 1);
260 mValues.put(Favorites.SPANY, 1);
261 mValues.put(Favorites._ID, id);
262 if (mCallback.insertAndCheck(mDb, mValues) < 0) {
263 return -1;
264 } else {
265 return id;
266 }
267 }
268
269 protected HashMap<String, TagParser> getFolderElementsMap() {
270 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
271 parsers.put(TAG_APP_ICON, new AppShortcutParser());
272 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700273 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700274 return parsers;
275 }
276
277 protected HashMap<String, TagParser> getLayoutElementsMap() {
278 HashMap<String, TagParser> parsers = new HashMap<String, TagParser>();
279 parsers.put(TAG_APP_ICON, new AppShortcutParser());
280 parsers.put(TAG_AUTO_INSTALL, new AutoInstallParser());
281 parsers.put(TAG_FOLDER, new FolderParser());
282 parsers.put(TAG_APPWIDGET, new AppWidgetParser());
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700283 parsers.put(TAG_SHORTCUT, new ShortcutParser(mSourceRes));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700284 return parsers;
285 }
286
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700287 protected interface TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700288 /**
289 * Parses the tag and adds to the db
290 * @return the id of the row added or -1;
291 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700292 long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700293 throws XmlPullParserException, IOException;
294 }
295
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700296 /**
297 * App shortcuts: required attributes packageName and className
298 */
299 protected class AppShortcutParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700300
301 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700302 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700303 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
304 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
305
306 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
307 ActivityInfo info;
308 try {
309 ComponentName cn;
310 try {
311 cn = new ComponentName(packageName, className);
312 info = mPackageManager.getActivityInfo(cn, 0);
313 } catch (PackageManager.NameNotFoundException nnfe) {
314 String[] packages = mPackageManager.currentToCanonicalPackageNames(
315 new String[] { packageName });
316 cn = new ComponentName(packages[0], className);
317 info = mPackageManager.getActivityInfo(cn, 0);
318 }
319 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
320 .addCategory(Intent.CATEGORY_LAUNCHER)
321 .setComponent(cn)
322 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
323 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
324
325 return addShortcut(info.loadLabel(mPackageManager).toString(),
326 intent, Favorites.ITEM_TYPE_APPLICATION);
327 } catch (PackageManager.NameNotFoundException e) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700328 if (LOGD) Log.w(TAG, "Unable to add favorite: " + packageName + "/" + className, e);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700329 }
330 return -1;
331 } else {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700332 return invalidPackageOrClass(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700333 }
334 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700335
336 /**
337 * Helper method to allow extending the parser capabilities
338 */
339 protected long invalidPackageOrClass(XmlResourceParser parser) {
340 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
341 return -1;
342 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700343 }
344
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700345 /**
346 * AutoInstall: required attributes packageName and className
347 */
348 protected class AutoInstallParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700349
350 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700351 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700352 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
353 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
354 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
355 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
356 return -1;
357 }
358
Sunny Goyal34942622014-08-29 17:20:55 -0700359 mValues.put(Favorites.RESTORED, ShortcutInfo.FLAG_AUTOINTALL_ICON);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700360 final Intent intent = new Intent(Intent.ACTION_MAIN, null)
361 .addCategory(Intent.CATEGORY_LAUNCHER)
362 .setComponent(new ComponentName(packageName, className))
363 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
364 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
365 return addShortcut(mContext.getString(R.string.package_state_unknown), intent,
366 Favorites.ITEM_TYPE_APPLICATION);
367 }
368 }
369
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700370 /**
371 * Parses a web shortcut. Required attributes url, icon, title
372 */
373 protected class ShortcutParser implements TagParser {
374
375 private final Resources mIconRes;
376
377 public ShortcutParser(Resources iconRes) {
378 mIconRes = iconRes;
379 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700380
381 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700382 public long parseAndAdd(XmlResourceParser parser) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700383 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
384 final int iconId = getAttributeResourceValue(parser, ATTR_ICON, 0);
385
386 if (titleResId == 0 || iconId == 0) {
387 if (LOGD) Log.d(TAG, "Ignoring shortcut");
388 return -1;
389 }
390
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700391 final Intent intent = parseIntent(parser);
392 if (intent == null) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700393 return -1;
394 }
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700395
396 Drawable icon = mIconRes.getDrawable(iconId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700397 if (icon == null) {
398 if (LOGD) Log.d(TAG, "Ignoring shortcut, can't load icon");
399 return -1;
400 }
401
402 ItemInfo.writeBitmap(mValues, Utilities.createIconBitmap(icon, mContext));
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700403 mValues.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
404 mValues.put(Favorites.ICON_PACKAGE, mIconRes.getResourcePackageName(iconId));
405 mValues.put(Favorites.ICON_RESOURCE, mIconRes.getResourceName(iconId));
406
407 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700408 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700409 return addShortcut(mSourceRes.getString(titleResId),
410 intent, Favorites.ITEM_TYPE_SHORTCUT);
411 }
412
413 protected Intent parseIntent(XmlResourceParser parser) {
414 final String url = getAttributeValue(parser, ATTR_URL);
415 if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
416 if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
417 return null;
418 }
419 return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700420 }
421 }
422
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700423 /**
424 * AppWidget parser: Required attributes packageName, className, spanX and spanY.
425 * Options child nodes: <extra key=... value=... />
426 */
427 protected class AppWidgetParser implements TagParser {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700428
429 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700430 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700431 throws XmlPullParserException, IOException {
432 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
433 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
434 if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
435 if (LOGD) Log.d(TAG, "Skipping invalid <favorite> with no component");
436 return -1;
437 }
438
439 ComponentName cn = new ComponentName(packageName, className);
440 try {
441 mPackageManager.getReceiverInfo(cn, 0);
442 } catch (Exception e) {
443 String[] packages = mPackageManager.currentToCanonicalPackageNames(
444 new String[] { packageName });
445 cn = new ComponentName(packages[0], className);
446 try {
447 mPackageManager.getReceiverInfo(cn, 0);
448 } catch (Exception e1) {
449 if (LOGD) Log.d(TAG, "Can't find widget provider: " + className);
450 return -1;
451 }
452 }
453
454 mValues.put(Favorites.SPANX, getAttributeValue(parser, ATTR_SPAN_X));
455 mValues.put(Favorites.SPANY, getAttributeValue(parser, ATTR_SPAN_Y));
456
457 // Read the extras
458 Bundle extras = new Bundle();
459 int widgetDepth = parser.getDepth();
460 int type;
461 while ((type = parser.next()) != XmlPullParser.END_TAG ||
462 parser.getDepth() > widgetDepth) {
463 if (type != XmlPullParser.START_TAG) {
464 continue;
465 }
466
467 if (TAG_EXTRA.equals(parser.getName())) {
468 String key = getAttributeValue(parser, ATTR_KEY);
469 String value = getAttributeValue(parser, ATTR_VALUE);
470 if (key != null && value != null) {
471 extras.putString(key, value);
472 } else {
473 throw new RuntimeException("Widget extras must have a key and value");
474 }
475 } else {
476 throw new RuntimeException("Widgets can contain only extras");
477 }
478 }
479
480 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
481 long insertedId = -1;
482 try {
483 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
484
485 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn)) {
486 if (LOGD) Log.e(TAG, "Unable to bind app widget id " + cn);
487 return -1;
488 }
489
490 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
491 mValues.put(Favorites.APPWIDGET_ID, appWidgetId);
492 mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
493 mValues.put(Favorites._ID, mCallback.generateNewItemId());
494 insertedId = mCallback.insertAndCheck(mDb, mValues);
495 if (insertedId < 0) {
496 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
497 return insertedId;
498 }
499
500 // Send a broadcast to configure the widget
501 if (!extras.isEmpty()) {
502 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
503 intent.setComponent(cn);
504 intent.putExtras(extras);
505 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
506 mContext.sendBroadcast(intent);
507 }
508 } catch (RuntimeException ex) {
509 if (LOGD) Log.e(TAG, "Problem allocating appWidgetId", ex);
510 }
511 return insertedId;
512 }
513 }
514
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700515 protected class FolderParser implements TagParser {
516 private final HashMap<String, TagParser> mFolderElements;
517
518 public FolderParser() {
519 this(getFolderElementsMap());
520 }
521
522 public FolderParser(HashMap<String, TagParser> elements) {
523 mFolderElements = elements;
524 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700525
526 @Override
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700527 public long parseAndAdd(XmlResourceParser parser)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700528 throws XmlPullParserException, IOException {
529 final String title;
530 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
531 if (titleResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700532 title = mSourceRes.getString(titleResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700533 } else {
534 title = mContext.getResources().getString(R.string.folder_name);
535 }
536
537 mValues.put(Favorites.TITLE, title);
538 mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
539 mValues.put(Favorites.SPANX, 1);
540 mValues.put(Favorites.SPANY, 1);
541 mValues.put(Favorites._ID, mCallback.generateNewItemId());
542 long folderId = mCallback.insertAndCheck(mDb, mValues);
543 if (folderId < 0) {
544 if (LOGD) Log.e(TAG, "Unable to add folder");
545 return -1;
546 }
547
548 final ContentValues myValues = new ContentValues(mValues);
549 ArrayList<Long> folderItems = new ArrayList<Long>();
550
551 int type;
552 int folderDepth = parser.getDepth();
553 while ((type = parser.next()) != XmlPullParser.END_TAG ||
554 parser.getDepth() > folderDepth) {
555 if (type != XmlPullParser.START_TAG) {
556 continue;
557 }
558 mValues.clear();
559 mValues.put(Favorites.CONTAINER, folderId);
560
561 TagParser tagParser = mFolderElements.get(parser.getName());
562 if (tagParser != null) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700563 final long id = tagParser.parseAndAdd(parser);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700564 if (id >= 0) {
565 folderItems.add(id);
566 }
567 } else {
568 throw new RuntimeException("Invalid folder item " + parser.getName());
569 }
570 }
571
572 long addedId = folderId;
573
574 // We can only have folders with >= 2 items, so we need to remove the
575 // folder and clean up if less than 2 items were included, or some
576 // failed to add, and less than 2 were actually added
577 if (folderItems.size() < 2) {
578 // Delete the folder
579 Uri uri = Favorites.getContentUri(folderId, false);
580 SqlArguments args = new SqlArguments(uri, null, null);
581 mDb.delete(args.table, args.where, args.args);
582 addedId = -1;
583
584 // If we have a single item, promote it to where the folder
585 // would have been.
586 if (folderItems.size() == 1) {
587 final ContentValues childValues = new ContentValues();
588 copyInteger(myValues, childValues, Favorites.CONTAINER);
589 copyInteger(myValues, childValues, Favorites.SCREEN);
590 copyInteger(myValues, childValues, Favorites.CELLX);
591 copyInteger(myValues, childValues, Favorites.CELLY);
592
593 addedId = folderItems.get(0);
594 mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
595 Favorites._ID + "=" + addedId, null);
596 }
597 }
598 return addedId;
599 }
600 }
601
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700602 protected static final void beginDocument(XmlPullParser parser, String firstElementName)
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700603 throws XmlPullParserException, IOException {
604 int type;
605 while ((type = parser.next()) != XmlPullParser.START_TAG
606 && type != XmlPullParser.END_DOCUMENT);
607
608 if (type != XmlPullParser.START_TAG) {
609 throw new XmlPullParserException("No start tag found");
610 }
611
612 if (!parser.getName().equals(firstElementName)) {
613 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
614 ", expected " + firstElementName);
615 }
616 }
617
618 /**
619 * Return attribute value, attempting launcher-specific namespace first
620 * before falling back to anonymous attribute.
621 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700622 protected static String getAttributeValue(XmlResourceParser parser, String attribute) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700623 String value = parser.getAttributeValue(
624 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
625 if (value == null) {
626 value = parser.getAttributeValue(null, attribute);
627 }
628 return value;
629 }
630
631 /**
632 * Return attribute resource value, attempting launcher-specific namespace
633 * first before falling back to anonymous attribute.
634 */
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700635 protected static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700636 int defaultValue) {
637 int value = parser.getAttributeResourceValue(
638 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
639 defaultValue);
640 if (value == defaultValue) {
641 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
642 }
643 return value;
644 }
645
646 public static interface LayoutParserCallback {
647 long generateNewItemId();
648
649 long insertAndCheck(SQLiteDatabase db, ContentValues values);
650 }
651
Adam Cohen091440a2015-03-18 14:16:05 -0700652 @Thunk static void copyInteger(ContentValues from, ContentValues to, String key) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700653 to.put(key, from.getAsInteger(key));
654 }
655}