aboutsummaryrefslogtreecommitdiffstats
path: root/sdkmanager/libs/sdklib/src/com/android/sdklib/devices/DeviceManager.java
blob: 3662c26edc59faa8f51bd964ef6f4c90413e7ba2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.sdklib.devices;

import com.android.SdkConstants;
import com.android.annotations.Nullable;
import com.android.prefs.AndroidLocation;
import com.android.prefs.AndroidLocation.AndroidLocationException;
import com.android.resources.Keyboard;
import com.android.resources.KeyboardState;
import com.android.resources.Navigation;
import com.android.sdklib.internal.avd.AvdManager;
import com.android.sdklib.internal.avd.HardwareProperties;
import com.android.sdklib.repository.PkgProps;
import com.android.utils.ILogger;

import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;

/**
 * Manager class for interacting with {@link Device}s within the SDK
 */
public class DeviceManager {

    private final static String sDeviceProfilesProp = "DeviceProfiles";
    private final static Pattern sPathPropertyPattern = Pattern.compile("^" + PkgProps.EXTRA_PATH
            + "=" + sDeviceProfilesProp + "$");
    private ILogger mLog;
    // Vendor devices can't be a static list since they change based on the SDK
    // Location
    private List<Device> mVendorDevices;
    // Keeps track of where the currently loaded vendor devices were loaded from
    private String mVendorDevicesLocation = "";
    private static List<Device> mUserDevices;
    private static List<Device> mDefaultDevices;
    private static final Object sLock = new Object();
    private static final List<DevicesChangeListener> sListeners =
                                        new ArrayList<DevicesChangeListener>();

    public static enum DeviceStatus {
        /**
         * The device exists unchanged from the given configuration
         */
        EXISTS,
        /**
         * A device exists with the given name and manufacturer, but has a different configuration
         */
        CHANGED,
        /**
         * There is no device with the given name and manufacturer
         */
        MISSING;
    }

    // TODO: Refactor this to look more like AvdManager so that we don't have
    // multiple instances in the same application, which forces us to parse
    // the XML multiple times when we don't have to.
    public DeviceManager(ILogger log) {
        mLog = log;
    }

    /**
     * Interface implemented by objects which want to know when changes occur to the {@link Device}
     * lists.
     */
    public static interface DevicesChangeListener {
        /**
         * Called after one of the {@link Device} lists has been updated.
         */
        public void onDevicesChange();
    }

    /**
     * Register a listener to be notified when the device lists are modified.
     *
     * @param listener The listener to add. Ignored if already registered.
     */
    public void registerListener(DevicesChangeListener listener) {
        if (listener != null) {
            synchronized (sListeners) {
                if (!sListeners.contains(listener)) {
                    sListeners.add(listener);
                }
            }
        }
    }

    /**
     * Removes a listener from the notification list such that it will no longer receive
     * notifications when modifications to the {@link Device} list occur.
     *
     * @param listener The listener to remove.
     */
    public boolean unregisterListener(DevicesChangeListener listener) {
        synchronized (sListeners) {
            return sListeners.remove(listener);
        }
    }

    public DeviceStatus getDeviceStatus(
            @Nullable String sdkLocation, String name, String manufacturer, int hashCode) {
        Device d = getDevice(sdkLocation, name, manufacturer);
        if (d == null) {
            return DeviceStatus.MISSING;
        } else {
            return d.hashCode() == hashCode ? DeviceStatus.EXISTS : DeviceStatus.CHANGED;
        }
    }

    public Device getDevice(@Nullable String sdkLocation, String name, String manufacturer) {
        List<Device> devices;
        if (sdkLocation != null) {
            devices = getDevices(sdkLocation);
        } else {
            devices = new ArrayList<Device>(getDefaultDevices());
            devices.addAll(getUserDevices());
        }
        for (Device d : devices) {
            if (d.getName().equals(name) && d.getManufacturer().equals(manufacturer)) {
                return d;
            }
        }
        return null;
    }

    /**
     * Returns both vendor provided and user created {@link Device}s.
     *
     * @param sdkLocation Location of the Android SDK
     * @return A list of both vendor and user provided {@link Device}s
     */
    public List<Device> getDevices(String sdkLocation) {
        List<Device> devices = new ArrayList<Device>(getVendorDevices(sdkLocation));
        devices.addAll(getDefaultDevices());
        devices.addAll(getUserDevices());
        return Collections.unmodifiableList(devices);
    }

    /**
     * Gets the {@link List} of {@link Device}s packaged with the SDK.
     *
     * @return The {@link List} of default {@link Device}s
     */
    public List<Device> getDefaultDevices() {
        synchronized (sLock) {
            if (mDefaultDevices == null) {
                try {
                    mDefaultDevices = DeviceParser.parse(
                            DeviceManager.class.getResourceAsStream(SdkConstants.FN_DEVICES_XML));
                } catch (IllegalStateException e) {
                    // The device builders can throw IllegalStateExceptions if
                    // build gets called before everything is properly setup
                    mLog.error(e, null);
                    mDefaultDevices = new ArrayList<Device>();
                } catch (Exception e) {
                    mLog.error(null, "Error reading default devices");
                    mDefaultDevices = new ArrayList<Device>();
                }
                notifyListeners();
            }
        }
        return Collections.unmodifiableList(mDefaultDevices);
    }

    /**
     * Returns all vendor-provided {@link Device}s
     *
     * @param sdkLocation Location of the Android SDK
     * @return A list of vendor-provided {@link Device}s
     */
    public List<Device> getVendorDevices(String sdkLocation) {
        synchronized (sLock) {
            if (mVendorDevices == null || !mVendorDevicesLocation.equals(sdkLocation)) {
                mVendorDevicesLocation = sdkLocation;
                List<Device> devices = new ArrayList<Device>();

                // Load devices from tools folder
                File toolsDevices = new File(sdkLocation, SdkConstants.OS_SDK_TOOLS_LIB_FOLDER +
                        File.separator + SdkConstants.FN_DEVICES_XML);
                if (toolsDevices.isFile()) {
                    devices.addAll(loadDevices(toolsDevices));
                }

                // Load devices from vendor extras
                File extrasFolder = new File(sdkLocation, SdkConstants.FD_EXTRAS);
                List<File> deviceDirs = getExtraDirs(extrasFolder);
                for (File deviceDir : deviceDirs) {
                    File deviceXml = new File(deviceDir, SdkConstants.FN_DEVICES_XML);
                    if (deviceXml.isFile()) {
                        devices.addAll(loadDevices(deviceXml));
                    }
                }
                mVendorDevices = devices;
                notifyListeners();
            }
        }
        return Collections.unmodifiableList(mVendorDevices);
    }

    /**
     * Returns all user-created {@link Device}s
     *
     * @return All user-created {@link Device}s
     */
    public List<Device> getUserDevices() {
        synchronized (sLock) {
            if (mUserDevices == null) {
                // User devices should be saved out to
                // $HOME/.android/devices.xml
                mUserDevices = new ArrayList<Device>();
                File userDevicesFile = null;
                try {
                    userDevicesFile = new File(AndroidLocation.getFolder(),
                            SdkConstants.FN_DEVICES_XML);
                    if (userDevicesFile.exists()) {
                        mUserDevices.addAll(DeviceParser.parse(userDevicesFile));
                        notifyListeners();
                    }
                } catch (AndroidLocationException e) {
                    mLog.warning("Couldn't load user devices: %1$s", e.getMessage());
                } catch (SAXException e) {
                    // Probably an old config file which we don't want to overwrite.
                    if (userDevicesFile != null) {
                        String base = userDevicesFile.getAbsoluteFile() + ".old";
                        File renamedConfig = new File(base);
                        int i = 0;
                        while (renamedConfig.exists()) {
                            renamedConfig = new File(base + '.' + (i++));
                        }
                        mLog.error(null, "Error parsing %1$s, backing up to %2$s",
                                userDevicesFile.getAbsolutePath(), renamedConfig.getAbsolutePath());
                        userDevicesFile.renameTo(renamedConfig);
                    }
                } catch (ParserConfigurationException e) {
                    mLog.error(null, "Error parsing %1$s",
                            userDevicesFile == null ? "(null)" : userDevicesFile.getAbsolutePath());
                } catch (IOException e) {
                    mLog.error(null, "Error parsing %1$s",
                            userDevicesFile == null ? "(null)" : userDevicesFile.getAbsolutePath());
                }
            }
        }
        return Collections.unmodifiableList(mUserDevices);
    }

    public void addUserDevice(Device d) {
        synchronized (sLock) {
            if (mUserDevices == null) {
                getUserDevices();
            }
            mUserDevices.add(d);
        }
        notifyListeners();
    }

    public void removeUserDevice(Device d) {
        synchronized (sLock) {
            if (mUserDevices == null) {
                getUserDevices();
            }
            Iterator<Device> it = mUserDevices.iterator();
            while (it.hasNext()) {
                Device userDevice = it.next();
                if (userDevice.getName().equals(d.getName())
                        && userDevice.getManufacturer().equals(d.getManufacturer())) {
                    it.remove();
                    notifyListeners();
                    break;
                }

            }
        }
    }

    public void replaceUserDevice(Device d) {
        synchronized (sLock) {
            if (mUserDevices == null) {
                getUserDevices();
            }
            removeUserDevice(d);
            addUserDevice(d);
        }
    }

    /**
     * Saves out the user devices to {@link SdkConstants#FN_DEVICES_XML} in
     * {@link AndroidLocation#getFolder()}.
     */
    public void saveUserDevices() {
        synchronized (sLock) {
            if (mUserDevices != null && mUserDevices.size() != 0) {
                File userDevicesFile;
                try {
                    userDevicesFile = new File(AndroidLocation.getFolder(),
                            SdkConstants.FN_DEVICES_XML);
                    DeviceWriter.writeToXml(new FileOutputStream(userDevicesFile), mUserDevices);
                } catch (AndroidLocationException e) {
                    mLog.warning("Couldn't find user directory: %1$s", e.getMessage());
                } catch (FileNotFoundException e) {
                    mLog.warning("Couldn't open file: %1$s", e.getMessage());
                } catch (ParserConfigurationException e) {
                    mLog.warning("Error writing file: %1$s", e.getMessage());
                } catch (TransformerFactoryConfigurationError e) {
                    mLog.warning("Error writing file: %1$s", e.getMessage());
                } catch (TransformerException e) {
                    mLog.warning("Error writing file: %1$s", e.getMessage());
                }
            }
        }
    }

    /**
     * Returns hardware properties (defined in hardware.ini) as a {@link Map}.
     *
     * @param s The {@link State} from which to derive the hardware properties.
     * @return A {@link Map} of hardware properties.
     */
    public static Map<String, String> getHardwareProperties(State s) {
        Hardware hw = s.getHardware();
        Map<String, String> props = new HashMap<String, String>();
        props.put(HardwareProperties.HW_MAINKEYS,
                getBooleanVal(hw.getButtonType().equals(ButtonType.HARD)));
        props.put(HardwareProperties.HW_TRACKBALL,
                getBooleanVal(hw.getNav().equals(Navigation.TRACKBALL)));
        props.put(HardwareProperties.HW_KEYBOARD,
                getBooleanVal(hw.getKeyboard().equals(Keyboard.QWERTY)));
        props.put(HardwareProperties.HW_DPAD,
                getBooleanVal(hw.getNav().equals(Navigation.DPAD)));

        Set<Sensor> sensors = hw.getSensors();
        props.put(HardwareProperties.HW_GPS, getBooleanVal(sensors.contains(Sensor.GPS)));
        props.put(HardwareProperties.HW_BATTERY,
                getBooleanVal(hw.getChargeType().equals(PowerType.BATTERY)));
        props.put(HardwareProperties.HW_ACCELEROMETER,
                getBooleanVal(sensors.contains(Sensor.ACCELEROMETER)));
        props.put(HardwareProperties.HW_ORIENTATION_SENSOR,
                getBooleanVal(sensors.contains(Sensor.GYROSCOPE)));
        props.put(HardwareProperties.HW_AUDIO_INPUT, getBooleanVal(hw.hasMic()));
        props.put(HardwareProperties.HW_SDCARD, getBooleanVal(hw.getRemovableStorage().size() > 0));
        props.put(HardwareProperties.HW_LCD_DENSITY,
                Integer.toString(hw.getScreen().getPixelDensity().getDpiValue()));
        props.put(HardwareProperties.HW_PROXIMITY_SENSOR,
                getBooleanVal(sensors.contains(Sensor.PROXIMITY_SENSOR)));
        return props;
    }

    /**
     * Returns the hardware properties defined in
     * {@link AvdManager#HARDWARE_INI} as a {@link Map}.
     *
     * @param d The {@link Device} from which to derive the hardware properties.
     * @return A {@link Map} of hardware properties.
     */
    public static Map<String, String> getHardwareProperties(Device d) {
        Map<String, String> props = getHardwareProperties(d.getDefaultState());
        for (State s : d.getAllStates()) {
            if (s.getKeyState().equals(KeyboardState.HIDDEN)) {
                props.put("hw.keyboard.lid", getBooleanVal(true));
            }
        }
        props.put(AvdManager.AVD_INI_DEVICE_HASH, Integer.toString(d.hashCode()));
        props.put(AvdManager.AVD_INI_DEVICE_NAME, d.getName());
        props.put(AvdManager.AVD_INI_DEVICE_MANUFACTURER, d.getManufacturer());
        return props;
    }

    /**
     * Takes a boolean and returns the appropriate value for
     * {@link HardwareProperties}
     *
     * @param bool The boolean value to turn into the appropriate
     *            {@link HardwareProperties} value.
     * @return {@code HardwareProperties#BOOLEAN_VALUES[0]} if true,
     *         {@code HardwareProperties#BOOLEAN_VALUES[1]} otherwise.
     */
    private static String getBooleanVal(boolean bool) {
        if (bool) {
            return HardwareProperties.BOOLEAN_VALUES[0];
        }
        return HardwareProperties.BOOLEAN_VALUES[1];
    }

    private Collection<Device> loadDevices(File deviceXml) {
        try {
            return DeviceParser.parse(deviceXml);
        } catch (SAXException e) {
            mLog.error(null, "Error parsing %1$s", deviceXml.getAbsolutePath());
        } catch (ParserConfigurationException e) {
            mLog.error(null, "Error parsing %1$s", deviceXml.getAbsolutePath());
        } catch (IOException e) {
            mLog.error(null, "Error reading %1$s", deviceXml.getAbsolutePath());
        } catch (IllegalStateException e) {
            // The device builders can throw IllegalStateExceptions if
            // build gets called before everything is properly setup
            mLog.error(e, null);
        }
        return new ArrayList<Device>();
    }

    private void notifyListeners() {
        synchronized (sListeners) {
            for (DevicesChangeListener listener : sListeners) {
                listener.onDevicesChange();
            }
        }
    }

    /* Returns all of DeviceProfiles in the extras/ folder */
    private List<File> getExtraDirs(File extrasFolder) {
        List<File> extraDirs = new ArrayList<File>();
        // All OEM provided device profiles are in
        // $SDK/extras/$VENDOR/$ITEM/devices.xml
        if (extrasFolder != null && extrasFolder.isDirectory()) {
            for (File vendor : extrasFolder.listFiles()) {
                if (vendor.isDirectory()) {
                    for (File item : vendor.listFiles()) {
                        if (item.isDirectory() && isDevicesExtra(item)) {
                            extraDirs.add(item);
                        }
                    }
                }
            }
        }

        return extraDirs;
    }

    /*
     * Returns whether a specific folder for a specific vendor is a
     * DeviceProfiles folder
     */
    private boolean isDevicesExtra(File item) {
        File properties = new File(item, SdkConstants.FN_SOURCE_PROP);
        try {
            BufferedReader propertiesReader = new BufferedReader(new FileReader(properties));
            try {
                String line;
                while ((line = propertiesReader.readLine()) != null) {
                    Matcher m = sPathPropertyPattern.matcher(line);
                    if (m.matches()) {
                        return true;
                    }
                }
            } finally {
                propertiesReader.close();
            }
        } catch (IOException ignore) {
        }
        return false;
    }
}