code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import android.os.Parcel; import android.os.Parcelable; /** * A request for the service to create a waypoint at the current location. * * @author Sandor Dornbush */ public class WaypointCreationRequest implements Parcelable { public static enum WaypointType { MARKER, STATISTICS; } private WaypointType type; private String name; private String description; private String iconUrl; public final static WaypointCreationRequest DEFAULT_MARKER = new WaypointCreationRequest(WaypointType.MARKER); public final static WaypointCreationRequest DEFAULT_STATISTICS = new WaypointCreationRequest(WaypointType.STATISTICS); private WaypointCreationRequest(WaypointType type) { this.type = type; } public WaypointCreationRequest(WaypointType type, String name, String description, String iconUrl) { this.type = type; this.name = name; this.description = description; this.iconUrl = iconUrl; } public static class Creator implements Parcelable.Creator<WaypointCreationRequest> { @Override public WaypointCreationRequest createFromParcel(Parcel source) { int i = source.readInt(); if (i > WaypointType.values().length) { throw new IllegalArgumentException("Could not find waypoint type: " + i); } WaypointCreationRequest request = new WaypointCreationRequest(WaypointType.values()[i]); request.description = source.readString(); request.iconUrl = source.readString(); request.name = source.readString(); return request; } public WaypointCreationRequest[] newArray(int size) { return new WaypointCreationRequest[size]; } } public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int arg1) { parcel.writeInt(type.ordinal()); parcel.writeString(description); parcel.writeString(iconUrl); parcel.writeString(name); } public WaypointType getType() { return type; } public String getName() { return name; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointCreationRequest.java
Java
asf20
2,886
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * A class representing a (GPS) Track. * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class Track implements Parcelable { /** * Creator for a Track object. */ public static class Creator implements Parcelable.Creator<Track> { public Track createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Track track = new Track(); track.id = source.readLong(); track.name = source.readString(); track.description = source.readString(); track.mapId = source.readString(); track.category = source.readString(); track.startId = source.readLong(); track.stopId = source.readLong(); track.stats = source.readParcelable(classLoader); track.numberOfPoints = source.readInt(); for (int i = 0; i < track.numberOfPoints; ++i) { Location loc = source.readParcelable(classLoader); track.locations.add(loc); } track.tableId = source.readString(); return track; } public Track[] newArray(int size) { return new Track[size]; } } public static final Creator CREATOR = new Creator(); /** * The track points (which may not have been loaded). */ private ArrayList<Location> locations = new ArrayList<Location>(); /** * The number of location points (present even if the points themselves were * not loaded). */ private int numberOfPoints = 0; private long id = -1; private String name = ""; private String description = ""; private String mapId = ""; private String tableId = ""; private long startId = -1; private long stopId = -1; private String category = ""; private TripStatistics stats = new TripStatistics(); public Track() { } public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(mapId); dest.writeString(category); dest.writeLong(startId); dest.writeLong(stopId); dest.writeParcelable(stats, 0); dest.writeInt(numberOfPoints); for (int i = 0; i < numberOfPoints; ++i) { dest.writeParcelable(locations.get(i), 0); } dest.writeString(tableId); } // Getters and setters: //--------------------- public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMapId() { return mapId; } public void setMapId(String mapId) { this.mapId = mapId; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNumberOfPoints() { return numberOfPoints; } public void setNumberOfPoints(int numberOfPoints) { this.numberOfPoints = numberOfPoints; } public void addLocation(Location l) { locations.add(l); } public ArrayList<Location> getLocations() { return locations; } public void setLocations(ArrayList<Location> locations) { this.locations = locations; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/Track.java
Java
asf20
4,761
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import android.location.Location; /** * This class extends the standard Android location with extra information. * * @author Sandor Dornbush */ public class MyTracksLocation extends Location { private Sensor.SensorDataSet sensorDataSet = null; /** * The id of this location from the provider. */ private int id = -1; public MyTracksLocation(Location location, Sensor.SensorDataSet sd) { super(location); this.sensorDataSet = sd; } public MyTracksLocation(String provider) { super(provider); } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public void setSensorData(Sensor.SensorDataSet sensorData) { this.sensorDataSet = sensorData; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void reset() { super.reset(); sensorDataSet = null; id = -1; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksLocation.java
Java
asf20
1,550
package com.google.android.apps.mytracks.content; parcelable WaypointCreationRequest;
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointCreationRequest.aidl
AIDL
asf20
85
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface WaypointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/waypoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.waypoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.waypoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String ICON = "icon"; public static final String TRACKID = "trackid"; public static final String TYPE = "type"; public static final String LENGTH = "length"; public static final String DURATION = "duration"; public static final String STARTTIME = "starttime"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointsColumns.java
Java
asf20
2,815
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the track points provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TrackPointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/trackpoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.trackpoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.trackpoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String TRACKID = "trackid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String SENSOR = "sensor"; }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/TrackPointsColumns.java
Java
asf20
1,754
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.protobuf.InvalidProtocolBufferException; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * Helper class providing easy access to locations and tracks in the * MyTracksProvider. All static members. * * @author Leif Hendrik Wilden */ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final ContentResolver contentResolver; private int defaultCursorBatchSize = 2000; public MyTracksProviderUtilsImpl(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * Creates the ContentValues for a given location object. * * @param location a given location * @param trackId the id of the track it belongs to * @return a filled in ContentValues object */ private static ContentValues createContentValues( Location location, long trackId) { ContentValues values = new ContentValues(); values.put(TrackPointsColumns.TRACKID, trackId); values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); // This is an ugly hack for Samsung phones that don't properly populate the // time field. values.put(TrackPointsColumns.TIME, (location.getTime() == 0) ? System.currentTimeMillis() : location.getTime()); if (location.hasAltitude()) { values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(TrackPointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(TrackPointsColumns.SPEED, location.getSpeed()); } if (location instanceof MyTracksLocation) { MyTracksLocation mtLocation = (MyTracksLocation) location; if (mtLocation.getSensorDataSet() != null) { values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray()); } } return values; } @Override public ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics stats = track.getStatistics(); // Values id < 0 indicate no id is available: if (track.getId() >= 0) { values.put(TracksColumns._ID, track.getId()); } values.put(TracksColumns.NAME, track.getName()); values.put(TracksColumns.DESCRIPTION, track.getDescription()); values.put(TracksColumns.MAPID, track.getMapId()); values.put(TracksColumns.TABLEID, track.getTableId()); values.put(TracksColumns.CATEGORY, track.getCategory()); values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints()); values.put(TracksColumns.STARTID, track.getStartId()); values.put(TracksColumns.STARTTIME, stats.getStartTime()); values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.STOPID, track.getStopId()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); return values; } private static ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Values id < 0 indicate no id is available: if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); TripStatistics stats = waypoint.getStatistics(); if (stats != null) { values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, stats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade()); values.put(WaypointsColumns.STARTTIME, stats.getStartTime()); } Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } } return values; } @Override public Location createLocation(Cursor cursor) { Location location = new MyTracksLocation(""); fillLocation(cursor, location); return location; } /** * A cache of track column indices. */ private static class CachedTrackColumnIndices { public final int idxId; public final int idxLatitude; public final int idxLongitude; public final int idxAltitude; public final int idxTime; public final int idxBearing; public final int idxAccuracy; public final int idxSpeed; public final int idxSensor; public CachedTrackColumnIndices(Cursor cursor) { idxId = cursor.getColumnIndex(TrackPointsColumns._ID); idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE); idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE); idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE); idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME); idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING); idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY); idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED); idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR); } } private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices, Location location) { location.reset(); if (!cursor.isNull(columnIndices.idxLatitude)) { location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6); } if (!cursor.isNull(columnIndices.idxLongitude)) { location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6); } if (!cursor.isNull(columnIndices.idxAltitude)) { location.setAltitude(cursor.getFloat(columnIndices.idxAltitude)); } if (!cursor.isNull(columnIndices.idxTime)) { location.setTime(cursor.getLong(columnIndices.idxTime)); } if (!cursor.isNull(columnIndices.idxBearing)) { location.setBearing(cursor.getFloat(columnIndices.idxBearing)); } if (!cursor.isNull(columnIndices.idxSpeed)) { location.setSpeed(cursor.getFloat(columnIndices.idxSpeed)); } if (!cursor.isNull(columnIndices.idxAccuracy)) { location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy)); } if (location instanceof MyTracksLocation && !cursor.isNull(columnIndices.idxSensor)) { MyTracksLocation mtLocation = (MyTracksLocation) location; // TODO get the right buffer. Sensor.SensorDataSet sensorData; try { sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor)); mtLocation.setSensorData(sensorData); } catch (InvalidProtocolBufferException e) { Log.w(TAG, "Failed to parse sensor data.", e); } } } @Override public void fillLocation(Cursor cursor, Location location) { CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor); fillLocation(cursor, columnIndicies, location); } @Override public Track createTrack(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID); int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION); int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY); int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID); int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME); int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID); int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS); int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT); int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT); int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON); int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON); int idxTotalDistance = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE); Track track = new Track(); TripStatistics stats = track.getStatistics(); if (!cursor.isNull(idxId)) { track.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { track.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { track.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxMapId)) { track.setMapId(cursor.getString(idxMapId)); } if (!cursor.isNull(idxTableId)) { track.setTableId(cursor.getString(idxTableId)); } if (!cursor.isNull(idxCategory)) { track.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxStartId)) { track.setStartId(cursor.getInt(idxStartId)); } if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); } if (!cursor.isNull(idxStopTime)) { stats.setStopTime(cursor.getLong(idxStopTime)); } if (!cursor.isNull(idxStopId)) { track.setStopId(cursor.getInt(idxStopId)); } if (!cursor.isNull(idxNumPoints)) { track.setNumberOfPoints(cursor.getInt(idxNumPoints)); } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); } if (!cursor.isNull(idxMaxlat) && !cursor.isNull(idxMinlat) && !cursor.isNull(idxMaxlon) && !cursor.isNull(idxMinlon)) { int top = cursor.getInt(idxMaxlat); int bottom = cursor.getInt(idxMinlat); int right = cursor.getInt(idxMaxlon); int left = cursor.getInt(idxMinlon); stats.setBounds(left, top, right, bottom); } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); } return track; } @Override public Waypoint createWaypoint(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID); int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION); int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY); int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON); int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID); int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH); int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION); int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME); int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID); int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID); int idxTotalDistance = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE); int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE); int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE); int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME); int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING); int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY); int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED); Waypoint waypoint = new Waypoint(); if (!cursor.isNull(idxId)) { waypoint.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { waypoint.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { waypoint.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxCategory)) { waypoint.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxIcon)) { waypoint.setIcon(cursor.getString(idxIcon)); } if (!cursor.isNull(idxTrackId)) { waypoint.setTrackId(cursor.getLong(idxTrackId)); } if (!cursor.isNull(idxType)) { waypoint.setType(cursor.getInt(idxType)); } if (!cursor.isNull(idxLength)) { waypoint.setLength(cursor.getDouble(idxLength)); } if (!cursor.isNull(idxDuration)) { waypoint.setDuration(cursor.getLong(idxDuration)); } if (!cursor.isNull(idxStartId)) { waypoint.setStartId(cursor.getLong(idxStartId)); } if (!cursor.isNull(idxStopId)) { waypoint.setStopId(cursor.getLong(idxStopId)); } TripStatistics stats = new TripStatistics(); boolean hasStats = false; if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); hasStats = true; } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); hasStats = true; } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); hasStats = true; } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); hasStats = true; } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); hasStats = true; } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); hasStats = true; } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); hasStats = true; } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); hasStats = true; } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); hasStats = true; } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); hasStats = true; } if (hasStats) { waypoint.setStatistics(stats); } Location location = new Location(""); if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) { location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6); location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6); } if (!cursor.isNull(idxAltitude)) { location.setAltitude(cursor.getFloat(idxAltitude)); } if (!cursor.isNull(idxTime)) { location.setTime(cursor.getLong(idxTime)); } if (!cursor.isNull(idxBearing)) { location.setBearing(cursor.getFloat(idxBearing)); } if (!cursor.isNull(idxSpeed)) { location.setSpeed(cursor.getFloat(idxSpeed)); } if (!cursor.isNull(idxAccuracy)) { location.setAccuracy(cursor.getFloat(idxAccuracy)); } waypoint.setLocation(location); return waypoint; } @Override public void deleteAllTracks() { contentResolver.delete(TracksColumns.CONTENT_URI, null, null); contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); } @Override public void deleteTrack(long trackId) { Track track = getTrack(trackId); if (track != null) { contentResolver.delete(TrackPointsColumns.CONTENT_URI, "_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(), null); } contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=" + trackId, null); contentResolver.delete( TracksColumns.CONTENT_URI, "_id=" + trackId, null); } @Override public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { final Waypoint deletedWaypoint = getWaypoint(waypointId); if (deletedWaypoint != null && deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) { final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(deletedWaypoint); if (nextWaypoint != null) { Log.d(TAG, "Correcting marker " + nextWaypoint.getId() + " after deleted marker " + deletedWaypoint.getId()); nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics()); nextWaypoint.setDescription( descriptionGenerator.generateWaypointDescription(nextWaypoint)); if (!updateWaypoint(nextWaypoint)) { Log.w(TAG, "Update of marker was unsuccessful."); } } else { Log.d(TAG, "No statistics marker after the deleted one was found."); } } contentResolver.delete( WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null); } @Override public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { final String selection = WaypointsColumns._ID + ">" + waypoint.getId() + " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId() + " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; final String sortOrder = WaypointsColumns._ID + " LIMIT 1"; Cursor cursor = null; try { cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, selection, null /*selectionArgs*/, sortOrder); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public boolean updateWaypoint(Waypoint waypoint) { try { final int rows = contentResolver.update( WaypointsColumns.CONTENT_URI, createContentValues(waypoint), "_id=" + waypoint.getId(), null /*selectionArgs*/); return rows == 1; } catch (RuntimeException e) { Log.e(TAG, "Caught unexpected exception.", e); } return false; } /** * Finds a locations from the provider by the given selection. * * @param select a selection argument that identifies a unique location * @return the fist location matching, or null if not found */ private Location findLocationBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createLocation(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpeceted exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } /** * Finds a track from the provider by the given selection. * * @param select a selection argument that identifies a unique track * @return the first track matching, or null if not found */ private Track findTrackBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public Location getLastLocation() { return findLocationBy("_id=(select max(_id) from trackpoints)"); } @Override public Waypoint getFirstWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1"); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public Waypoint getWaypoint(long waypointId) { if (waypointId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "_id=" + waypointId, null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public long getLastLocationId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, projection, "_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")", null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getFirstWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getLastWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, WaypointsColumns.TRACKID + "=" + trackId, null /*selectionArgs*/, "_id DESC LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public Track getLastTrack() { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)", null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public long getLastTrackId() { String[] proj = { TracksColumns._ID }; Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)", null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TracksColumns._ID)); } } finally { cursor.close(); } } return -1; } @Override public Location getLocation(long id) { if (id < 0) { return null; } String selection = TrackPointsColumns._ID + "=" + id; return findLocationBy(selection); } @Override public Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } String selection; if (minTrackPointId >= 0) { selection = String.format("%s=%d AND %s%s%d", TrackPointsColumns.TRACKID, trackId, TrackPointsColumns._ID, descending ? "<=" : ">=", minTrackPointId); } else { selection = String.format("%s=%d", TrackPointsColumns.TRACKID, trackId); } String sortOrder = "_id " + (descending ? "DESC" : "ASC"); if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { if (trackId < 0) { return null; } String selection; if (minWaypointId > 0) { selection = String.format("%s=%d AND %s>=%d", WaypointsColumns.TRACKID, trackId, WaypointsColumns._ID, minWaypointId); } else { selection = String.format("%s=%d", WaypointsColumns.TRACKID, trackId); } String sortOrder = "_id ASC"; if (maxWaypoints > 0) { sortOrder += " LIMIT " + maxWaypoints; } return contentResolver.query( WaypointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Track getTrack(long id) { if (id < 0) { return null; } String select = TracksColumns._ID + "=" + id; return findTrackBy(select); } @Override public List<Track> getAllTracks() { Cursor cursor = getTracksCursor(null); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while(cursor.moveToNext()); } cursor.close(); } return tracks; } @Override public Cursor getTracksCursor(String selection) { Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, selection, null, "_id"); return cursor; } @Override public Uri insertTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack"); return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); } @Override public Uri insertTrackPoint(Location location, long trackId) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint"); return contentResolver.insert(TrackPointsColumns.CONTENT_URI, createContentValues(location, trackId)); } @Override public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) { if (length == -1) { length = locations.length; } ContentValues[] values = new ContentValues[length]; for (int i = 0; i < length; i++) { values[i] = createContentValues(locations[i], trackId); } return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); } @Override public Uri insertWaypoint(Waypoint waypoint) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint"); waypoint.setId(-1); return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); } @Override public boolean trackExists(long id) { if (id < 0) { return false; } Cursor cursor = null; try { final String[] projection = { TracksColumns._ID }; cursor = contentResolver.query( TracksColumns.CONTENT_URI, projection, TracksColumns._ID + "=" + id/*selection*/, null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null && cursor.moveToNext()) { return true; } } finally { if (cursor != null) { cursor.close(); } } return false; } @Override public void updateTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack"); contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), "_id=" + track.getId(), null); } @Override public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("Expecting non-null locationFactory"); } return new LocationIterator() { private long lastTrackPointId = startTrackPointId; private Cursor cursor = getCursor(startTrackPointId); private final CachedTrackColumnIndices columnIndices = cursor != null ? new CachedTrackColumnIndices(cursor) : null; private Cursor getCursor(long trackPointId) { return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } private boolean advanceCursorToNextBatch() { long pointId = lastTrackPointId + (descending ? -1 : 1); Log.d(TAG, "Advancing cursor point ID: " + pointId); cursor.close(); cursor = getCursor(pointId); return cursor != null; } @Override public long getLocationId() { return lastTrackPointId; } @Override public boolean hasNext() { if (cursor == null) { return false; } if (cursor.isAfterLast()) { return false; } if (cursor.isLast()) { // If the current batch size was less that max, we can safely return, otherwise // we need to advance to the next batch. return cursor.getCount() == defaultCursorBatchSize && advanceCursorToNextBatch() && !cursor.isAfterLast(); } return true; } @Override public Location next() { if (cursor == null || !(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) { throw new NoSuchElementException(); } lastTrackPointId = cursor.getLong(columnIndices.idxId); Location location = locationFactory.createLocation(); fillLocation(cursor, columnIndices, location); return location; } @Override public void close() { if (cursor != null) { cursor.close(); cursor = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // @VisibleForTesting void setDefaultCursorBatchSize(int defaultCursorBatchSize) { this.defaultCursorBatchSize = defaultCursorBatchSize; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java
Java
asf20
36,807
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TracksColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/tracks"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.track"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.track"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String STARTTIME = "starttime"; public static final String STOPTIME = "stoptime"; public static final String NUMPOINTS = "numpoints"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; public static final String MINLAT = "minlat"; public static final String MAXLAT = "maxlat"; public static final String MINLON = "minlon"; public static final String MAXLON = "maxlon"; public static final String MAPID = "mapid"; public static final String TABLEID = "tableid"; }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/TracksColumns.java
Java
asf20
2,606
package com.google.android.apps.mytracks.content; parcelable Waypoint;
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/Waypoint.aidl
AIDL
asf20
70
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import java.util.Iterator; import java.util.List; /** * Utility to access data from the mytracks content provider. * * @author Rodrigo Damazio */ public interface MyTracksProviderUtils { /** * Authority (first part of URI) for the MyTracks content provider: */ public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** * Deletes all tracks (including track points) from the provider. */ void deleteAllTracks(); /** * Deletes a track with the given track id. * * @param trackId the unique track id */ void deleteTrack(long trackId); /** * Deletes a way point with the given way point id. * This will also correct the next statistics way point after the deleted one * to reflect the deletion. * The generator is needed to stitch together statistics waypoints. * * @param waypointId the unique way point id * @param descriptionGenerator the class to generate descriptions */ void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Finds the next statistics waypoint after the given waypoint. * * @param waypoint a given waypoint * @return the next statistics waypoint, or null if none found. */ Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); /** * Updates the waypoint in the provider. * * @param waypoint * @return true if successful */ boolean updateWaypoint(Waypoint waypoint); /** * Finds the last recorded location from the location provider. * * @return the last location, or null if no locations available */ Location getLastLocation(); /** * Finds the first recorded waypoint for a given track from the location * provider. * This is a special waypoint that holds the stats for current segment. * * @param trackId the id of the track the waypoint belongs to * @return the first waypoint, or null if no waypoints available */ Waypoint getFirstWaypoint(long trackId); /** * Finds the given waypoint from the location provider. * * @param waypointId * @return the waypoint, or null if it does not exist */ Waypoint getWaypoint(long waypointId); /** * Finds the last recorded location id from the track points provider. * * @param trackId find last location on this track * @return the location id, or -1 if no locations available */ long getLastLocationId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getFirstWaypointId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getLastWaypointId(long trackId); /** * Finds the last recorded track from the track provider. * * @return the last track, or null if no tracks available */ Track getLastTrack(); /** * Finds the last recorded track id from the tracks provider. * * @return the track id, or -1 if no tracks available */ long getLastTrackId(); /** * Finds a location by given unique id. * * @param id the desired id * @return a Location object, or null if not found */ Location getLocation(long id); /** * Creates a cursor over the locations in the track points provider which * iterates over a given range of unique ids. * Caller gets to own the returned cursor. Don't forget to close it. * * @param trackId the id of the track for which to get the points * @param minTrackPointId the minimum id for the track points * @param maxLocations maximum number of locations retrieved * @param descending if true the results will be returned in descending id * order (latest location first) * @return A cursor over the selected range of locations */ Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending); /** * Creates a cursor over the waypoints of a track. * Caller gets to own the returned cursor. Don't forget to close it. * * @param trackId the id of the track for which to get the points * @param minWaypointId the minimum id for the track points * @param maxWaypoints the maximum number of waypoints to return * @return A cursor over the selected range of locations */ Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); /** * Finds a track by given unique track id. * Note that the returned track object does not have any track points attached. * Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load * the track points. * * @param id desired unique track id * @return a Track object, or null if not found */ Track getTrack(long id); /** * Retrieves all tracks without track points. If no tracks exist, an empty * list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} * to load the track points. * * @return a list of all the recorded tracks */ List<Track> getAllTracks(); /** * Creates a cursor over the tracks provider with a given selection. * Caller gets to own the returned cursor. Don't forget to close it. * * @param selection a given selection * @return a cursor of the selected tracks */ Cursor getTracksCursor(String selection); /** * Inserts a track in the tracks provider. * Note: This does not insert any track points. * Use {@link #insertTrackPoint(Location, long)} to insert them. * * @param track the track to insert * @return the content provider URI for the inserted track */ Uri insertTrack(Track track); /** * Inserts a track point in the tracks provider. * * @param location the location to insert * @return the content provider URI for the inserted track point */ Uri insertTrackPoint(Location location, long trackId); /** * Inserts multiple track points in a single operation. * * @param locations an array of locations to insert * @param length the number of locations (from the beginning of the array) * to actually insert, or -1 for all of them * @param trackId the ID of the track to insert the points into * @return the number of points inserted */ int bulkInsertTrackPoints(Location[] locations, int length, long trackId); /** * Inserts a waypoint in the provider. * * @param waypoint the waypoint to insert * @return the content provider URI for the inserted track */ Uri insertWaypoint(Waypoint waypoint); /** * Tests if a track with given id exists. * * @param id the unique id * @return true if track exists */ boolean trackExists(long id); /** * Updates a track in the content provider. * Note: This will not update any track points. * * @param track a given track */ void updateTrack(Track track); /** * Creates a Track object from a given cursor. * * @param cursor a cursor pointing at a db or provider with tracks * @return a new Track object */ Track createTrack(Cursor cursor); /** * Creates the ContentValues for a given Track object. * * Note: If the track has an id<0 the id column will not be filled. * * @param track a given track object * @return a filled in ContentValues object */ ContentValues createContentValues(Track track); /** * Creates a location object from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @return a new location object */ Location createLocation(Cursor cursor); /** * Fill a location object with values from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @param location a location object to be overwritten */ void fillLocation(Cursor cursor, Location location); /** * Creates a waypoint object from a given cursor. * * @param cursor a cursor pointing at a db or provider with waypoints. * @return a new waypoint object */ Waypoint createWaypoint(Cursor cursor); /** * A lightweight wrapper around the original {@link Cursor} with a method to clean up. */ interface LocationIterator extends Iterator<Location> { /** * Returns ID of the most recently retrieved track point through a call to {@link #next()}. * * @return the ID of the most recent track point ID. */ long getLocationId(); /** * Should be called in case the underlying iterator hasn't reached the last record. * Calling it if it has reached the last record is a no-op. */ void close(); } /** * A factory for creating new {@class Location}s. */ interface LocationFactory { /** * Creates a new {@link Location} object to be populated from the underlying database record. * It's up to the implementing class to decide whether to create a new instance or reuse * existing to optimize for speed. * * @return a {@link Location} to be populated from the database. */ Location createLocation(); } /** * The default {@class Location}s factory, which creates a new location of 'gps' type. */ LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() { @Override public Location createLocation() { return new Location("gps"); } }; /** * A location factory which uses two location instances (one for the current location, * and one for the previous), useful when we need to keep the last location. */ public class DoubleBufferedLocationFactory implements LocationFactory { private final Location locs[] = new MyTracksLocation[] { new MyTracksLocation("gps"), new MyTracksLocation("gps") }; private int lastLoc = 0; @Override public Location createLocation() { lastLoc = (lastLoc + 1) % locs.length; return locs[lastLoc]; } } /** * Creates a new read-only iterator over all track points for the given track. It provides * a lightweight way of iterating over long tracks without failing due to the underlying cursor * limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws * {@class UnsupportedOperationException}. * * Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so, * the iterator calls {@link LocationFactory#createLocation()} and populates it with information * retrieved from the record. * * When done with iteration, you must call {@link LocationIterator#close()} to make sure that all * resources are properly deallocated. * * Example use: * <code> * ... * LocationIterator it = providerUtils.getLocationIterator( * 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); * try { * for (Location loc : it) { * ... // Do something useful with the location. * } * } finally { * it.close(); * } * ... * </code> * * @param trackId the ID of a track to retrieve locations for. * @param startTrackPointId the ID of the first track point to load, or -1 to start from * the first point. * @param descending if true the results will be returned in descending ID * order (latest location first). * @param locationFactory the factory for creating new locations. * * @return the read-only iterator over the given track's points. */ LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); /** * A factory which can produce instances of {@link MyTracksProviderUtils}, * and can be overridden in tests (a.k.a. poor man's guice). */ public static class Factory { private static Factory instance = new Factory(); /** * Creates and returns an instance of {@link MyTracksProviderUtils} which * uses the given context to access its data. */ public static MyTracksProviderUtils get(Context context) { return instance.newForContext(context); } /** * Returns the global instance of this factory. */ public static Factory getInstance() { return instance; } /** * Overrides the global instance for this factory, to be used for testing. * If used, don't forget to set it back to the original value after the * test is run. */ public static void overrideInstance(Factory factory) { instance = factory; } /** * Creates an instance of {@link MyTracksProviderUtils}. */ protected MyTracksProviderUtils newForContext(Context context) { return new MyTracksProviderUtilsImpl(context.getContentResolver()); } } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java
Java
asf20
13,929
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import java.util.Vector; /** * An interface for an object that can generate descriptions of waypoints. * * @author Sandor Dornbush */ public interface DescriptionGenerator { /** * Generate a description of the waypoint. */ public String generateWaypointDescription(Waypoint waypoint); /** * Generates a description for a track (with information about the * statistics). * * @param track the track * @return a track description */ public String generateTrackDescription(Track track, Vector<Double> distances, Vector<Double> elevations); }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/DescriptionGenerator.java
Java
asf20
1,233
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; /** * A way point. It has a location, meta data such as name, description, * category, and icon, plus it can store track statistics for a "sub-track". * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public final class Waypoint implements Parcelable { /** * Creator for a Waypoint object */ public static class Creator implements Parcelable.Creator<Waypoint> { public Waypoint createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Waypoint waypoint = new Waypoint(); waypoint.id = source.readLong(); waypoint.name = source.readString(); waypoint.description = source.readString(); waypoint.category = source.readString(); waypoint.icon = source.readString(); waypoint.trackId = source.readLong(); waypoint.type = source.readInt(); waypoint.startId = source.readLong(); waypoint.stopId = source.readLong(); byte hasStats = source.readByte(); if (hasStats > 0) { waypoint.stats = source.readParcelable(classLoader); } byte hasLocation = source.readByte(); if (hasLocation > 0) { waypoint.location = source.readParcelable(classLoader); } return waypoint; } public Waypoint[] newArray(int size) { return new Waypoint[size]; } } public static final Creator CREATOR = new Creator(); public static final int TYPE_WAYPOINT = 0; public static final int TYPE_STATISTICS = 1; private long id = -1; private String name = ""; private String description = ""; private String category = ""; private String icon = ""; private long trackId = -1; private int type = 0; private Location location; /** Start track point id */ private long startId = -1; /** Stop track point id */ private long stopId = -1; private TripStatistics stats; /** The length of the track, without smoothing. */ private double length; /** The total duration of the track (not from the last waypoint) */ private long duration; public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(category); dest.writeString(icon); dest.writeLong(trackId); dest.writeInt(type); dest.writeLong(startId); dest.writeLong(stopId); dest.writeByte(stats == null ? (byte) 0 : (byte) 1); if (stats != null) { dest.writeParcelable(stats, 0); } dest.writeByte(location == null ? (byte) 0 : (byte) 1); if (location != null) { dest.writeParcelable(location, 0); } } // Getters and setters: //--------------------- public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Location getLocation() { return location; } public void setTrackId(long trackId) { this.trackId = trackId; } public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTrackId() { return trackId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setLocation(Location location) { this.location = location; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } // WARNING: These fields are used for internal state keeping. You probably // want to look at getStatistics instead. public double getLength() { return length; } public void setLength(double length) { this.length = length; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/content/Waypoint.java
Java
asf20
5,336
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.stats; /** * A helper class that tracks a minimum and a maximum of a variable. * * @author Sandor Dornbush */ public class ExtremityMonitor { /** * The smallest value seen so far. */ private double min; /** * The largest value seen so far. */ private double max; public ExtremityMonitor() { reset(); } /** * Updates the min and the max with the new value. * * @param value the new value for the monitor * @return true if an extremity was found */ public boolean update(double value) { boolean changed = false; if (value < min) { min = value; changed = true; } if (value > max) { max = value; changed = true; } return changed; } /** * Gets the minimum value seen. * * @return The minimum value passed into the update() function */ public double getMin() { return min; } /** * Gets the maximum value seen. * * @return The maximum value passed into the update() function */ public double getMax() { return max; } /** * Resets this object to it's initial state where the min and max are unknown. */ public void reset() { min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; } /** * Sets the minimum and maximum values. */ public void set(double min, double max) { this.min = min; this.max = max; } /** * Sets the minimum value. */ public void setMin(double min) { this.min = min; } /** * Sets the maximum value. */ public void setMax(double max) { this.max = max; } public boolean hasData() { return min != Double.POSITIVE_INFINITY && max != Double.NEGATIVE_INFINITY; } @Override public String toString() { return "Min: " + min + " Max: " + max; } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/stats/ExtremityMonitor.java
Java
asf20
2,451
package com.google.android.apps.mytracks.stats; parcelable TripStatistics;
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/stats/TripStatistics.aidl
AIDL
asf20
74
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.stats; import android.os.Parcel; import android.os.Parcelable; /** * Statistical data about a trip. * The data in this class should be filled out by TripStatisticsBuilder. * * TODO: hashCode and equals * * @author Rodrigo Damazio */ public class TripStatistics implements Parcelable { /** * The start time for the trip. This is system time which might not match gps * time. */ private long startTime = -1; /** * The stop time for the trip. This is the system time which might not match * gps time. */ private long stopTime = -1; /** * The total time that we believe the user was traveling in milliseconds. */ private long movingTime; /** * The total time of the trip in milliseconds. * This is only updated when new points are received, so it may be stale. */ private long totalTime; /** * The total distance in meters that the user traveled on this trip. */ private double totalDistance; /** * The total elevation gained on this trip in meters. */ private double totalElevationGain; /** * The maximum speed in meters/second reported that we believe to be a valid * speed. */ private double maxSpeed; /** * The min and max latitude values seen in this trip. */ private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor(); /** * The min and max longitude values seen in this trip. */ private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor(); /** * The min and max elevation seen on this trip in meters. */ private final ExtremityMonitor elevationExtremities = new ExtremityMonitor(); /** * The minimum and maximum grade calculations on this trip. */ private final ExtremityMonitor gradeExtremities = new ExtremityMonitor(); /** * Default constructor. */ public TripStatistics() { } /** * Copy constructor. * * @param other another statistics data object to copy from */ public TripStatistics(TripStatistics other) { this.maxSpeed = other.maxSpeed; this.movingTime = other.movingTime; this.startTime = other.startTime; this.stopTime = other.stopTime; this.totalDistance = other.totalDistance; this.totalElevationGain = other.totalElevationGain; this.totalTime = other.totalTime; this.latitudeExtremities.set(other.latitudeExtremities.getMin(), other.latitudeExtremities.getMax()); this.longitudeExtremities.set(other.longitudeExtremities.getMin(), other.longitudeExtremities.getMax()); this.elevationExtremities.set(other.elevationExtremities.getMin(), other.elevationExtremities.getMax()); this.gradeExtremities.set(other.gradeExtremities.getMin(), other.gradeExtremities.getMax()); } /** * Combines these statistics with those from another object. * This assumes that the time periods covered by each do not intersect. * * @param other the other waypoint */ public void merge(TripStatistics other) { startTime = Math.min(startTime, other.startTime); stopTime = Math.max(stopTime, other.stopTime); totalTime += other.totalTime; movingTime += other.movingTime; totalDistance += other.totalDistance; totalElevationGain += other.totalElevationGain; maxSpeed = Math.max(maxSpeed, other.maxSpeed); latitudeExtremities.update(other.latitudeExtremities.getMax()); latitudeExtremities.update(other.latitudeExtremities.getMin()); longitudeExtremities.update(other.longitudeExtremities.getMax()); longitudeExtremities.update(other.longitudeExtremities.getMin()); elevationExtremities.update(other.elevationExtremities.getMax()); elevationExtremities.update(other.elevationExtremities.getMin()); gradeExtremities.update(other.gradeExtremities.getMax()); gradeExtremities.update(other.gradeExtremities.getMin()); } /** * Gets the time that this track started. * * @return The number of milliseconds since epoch to the time when this track * started */ public long getStartTime() { return startTime; } /** * Gets the time that this track stopped. * * @return The number of milliseconds since epoch to the time when this track * stopped */ public long getStopTime() { return stopTime; } /** * Gets the total time that this track has been active. * This statistic is only updated when a new point is added to the statistics, * so it may be off. If you need to calculate the proper total time, use * {@link #getStartTime} with the current time. * * @return The total number of milliseconds the track was active */ public long getTotalTime() { return totalTime; } /** * Gets the total distance the user traveled. * * @return The total distance traveled in meters */ public double getTotalDistance() { return totalDistance; } /** * Gets the the average speed the user traveled. * This calculation only takes into account the displacement until the last * point that was accounted for in statistics. * * @return The average speed in m/s */ public double getAverageSpeed() { return totalDistance / ((double) totalTime / 1000); } /** * Gets the the average speed the user traveled when they were actively * moving. * * @return The average moving speed in m/s */ public double getAverageMovingSpeed() { return totalDistance / ((double) movingTime / 1000); } /** * Gets the the maximum speed for this track. * * @return The maximum speed in m/s */ public double getMaxSpeed() { return maxSpeed; } /** * Gets the moving time. * * @return The total number of milliseconds the user was moving */ public long getMovingTime() { return movingTime; } /** * Gets the total elevation gain for this trip. This is calculated as the sum * of all positive differences in the smoothed elevation. * * @return The elevation gain in meters for this trip */ public double getTotalElevationGain() { return totalElevationGain; } /** * Returns the leftmost position (lowest longitude) of the track, in signed * decimal degrees. */ public int getLeft() { return (int) (longitudeExtremities.getMin() * 1E6); } /** * Returns the rightmost position (highest longitude) of the track, in signed * decimal degrees. */ public int getRight() { return (int) (longitudeExtremities.getMax() * 1E6); } /** * Returns the bottommost position (lowest latitude) of the track, in meters. */ public int getBottom() { return (int) (latitudeExtremities.getMin() * 1E6); } /** * Returns the topmost position (highest latitude) of the track, in meters. */ public int getTop() { return (int) (latitudeExtremities.getMax() * 1E6); } /** * Gets the minimum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be more than the current elevation. * * @return The smallest elevation reading for this trip in meters */ public double getMinElevation() { return elevationExtremities.getMin(); } /** * Gets the maximum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be less than the current elevation. * * @return The largest elevation reading for this trip in meters */ public double getMaxElevation() { return elevationExtremities.getMax(); } /** * Gets the maximum grade for this trip. * * @return The maximum grade for this trip as a fraction */ public double getMaxGrade() { return gradeExtremities.getMax(); } /** * Gets the minimum grade for this trip. * * @return The minimum grade for this trip as a fraction */ public double getMinGrade() { return gradeExtremities.getMin(); } // Setters - to be used when restoring state or loading from the DB /** * Sets the start time for this trip. * * @param startTime the start time, in milliseconds since the epoch */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * Sets the stop time for this trip. * * @param stopTime the stop time, in milliseconds since the epoch */ public void setStopTime(long stopTime) { this.stopTime = stopTime; } /** * Sets the total moving time. * * @param movingTime the moving time in milliseconds */ public void setMovingTime(long movingTime) { this.movingTime = movingTime; } /** * Sets the total trip time. * * @param totalTime the total trip time in milliseconds */ public void setTotalTime(long totalTime) { this.totalTime = totalTime; } /** * Sets the total trip distance. * * @param totalDistance the trip distance in meters */ public void setTotalDistance(double totalDistance) { this.totalDistance = totalDistance; } /** * Sets the total elevation variation during the trip. * * @param totalElevationGain the elevation variation in meters */ public void setTotalElevationGain(double totalElevationGain) { this.totalElevationGain = totalElevationGain; } /** * Sets the maximum speed reached during the trip. * * @param maxSpeed the maximum speed in meters per second */ public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } /** * Sets the minimum elevation reached during the trip. * * @param elevation the minimum elevation in meters */ public void setMinElevation(double elevation) { elevationExtremities.setMin(elevation); } /** * Sets the maximum elevation reached during the trip. * * @param elevation the maximum elevation in meters */ public void setMaxElevation(double elevation) { elevationExtremities.setMax(elevation); } /** * Sets the minimum grade obtained during the trip. * * @param grade the grade as a fraction (-1.0 would mean vertical downwards) */ public void setMinGrade(double grade) { gradeExtremities.setMin(grade); } /** * Sets the maximum grade obtained during the trip). * * @param grade the grade as a fraction (1.0 would mean vertical upwards) */ public void setMaxGrade(double grade) { gradeExtremities.setMax(grade); } /** * Sets the bounding box for this trip. * The unit for all parameters is signed decimal degrees (degrees * 1E6). * * @param leftE6 the westmost longitude reached * @param topE6 the northmost latitude reached * @param rightE6 the eastmost longitude reached * @param bottomE6 the southmost latitude reached */ public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) { latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6); longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6); } // Data manipulation methods /** * Adds to the current total distance. * * @param distance the distance to add in meters */ void addTotalDistance(double distance) { totalDistance += distance; } /** * Adds to the total elevation variation. * * @param gain the elevation variation in meters */ void addTotalElevationGain(double gain) { totalElevationGain += gain; } /** * Adds to the total moving time of the trip. * * @param time the time in milliseconds */ void addMovingTime(long time) { movingTime += time; } /** * Accounts for a new latitude value for the bounding box. * * @param latitude the latitude value in signed decimal degrees */ void updateLatitudeExtremities(double latitude) { latitudeExtremities.update(latitude); } /** * Accounts for a new longitude value for the bounding box. * * @param longitude the longitude value in signed decimal degrees */ void updateLongitudeExtremities(double longitude) { longitudeExtremities.update(longitude); } /** * Accounts for a new elevation value for the bounding box. * * @param elevation the elevation value in meters */ void updateElevationExtremities(double elevation) { elevationExtremities.update(elevation); } /** * Accounts for a new grade value. * * @param grade the grade value as a fraction */ void updateGradeExtremities(double grade) { gradeExtremities.update(grade); } // String conversion @Override public String toString() { return "TripStatistics { Start Time: " + getStartTime() + "; Total Time: " + getTotalTime() + "; Moving Time: " + getMovingTime() + "; Total Distance: " + getTotalDistance() + "; Elevation Gain: " + getTotalElevationGain() + "; Min Elevation: " + getMinElevation() + "; Max Elevation: " + getMaxElevation() + "; Average Speed: " + getAverageMovingSpeed() + "; Min Grade: " + getMinGrade() + "; Max Grade: " + getMaxGrade() + "}"; } // Parcelable interface and creator /** * Creator of statistics data from parcels. */ public static class Creator implements Parcelable.Creator<TripStatistics> { @Override public TripStatistics createFromParcel(Parcel source) { TripStatistics data = new TripStatistics(); data.startTime = source.readLong(); data.movingTime = source.readLong(); data.totalTime = source.readLong(); data.totalDistance = source.readDouble(); data.totalElevationGain = source.readDouble(); data.maxSpeed = source.readDouble(); double minLat = source.readDouble(); double maxLat = source.readDouble(); data.latitudeExtremities.set(minLat, maxLat); double minLong = source.readDouble(); double maxLong = source.readDouble(); data.longitudeExtremities.set(minLong, maxLong); double minElev = source.readDouble(); double maxElev = source.readDouble(); data.elevationExtremities.set(minElev, maxElev); double minGrade = source.readDouble(); double maxGrade = source.readDouble(); data.gradeExtremities.set(minGrade, maxGrade); return data; } @Override public TripStatistics[] newArray(int size) { return new TripStatistics[size]; } } /** * Creator of {@link TripStatistics} from parcels. */ public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startTime); dest.writeLong(movingTime); dest.writeLong(totalTime); dest.writeDouble(totalDistance); dest.writeDouble(totalElevationGain); dest.writeDouble(maxSpeed); dest.writeDouble(latitudeExtremities.getMin()); dest.writeDouble(latitudeExtremities.getMax()); dest.writeDouble(longitudeExtremities.getMin()); dest.writeDouble(longitudeExtremities.getMax()); dest.writeDouble(elevationExtremities.getMin()); dest.writeDouble(elevationExtremities.getMax()); dest.writeDouble(gradeExtremities.getMin()); dest.writeDouble(gradeExtremities.getMax()); } }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/stats/TripStatistics.java
Java
asf20
15,887
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.lib; /** * Constants for the My Tracks common library. * These constants should ideally not be used by third-party applications. * * @author Rodrigo Damazio */ public class MyTracksLibConstants { public static final String TAG = "MyTracksLib"; private MyTracksLibConstants() {} }
0000som143-mytracks
MyTracksLib/src/com/google/android/apps/mytracks/lib/MyTracksLibConstants.java
Java
asf20
925
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerEclair.java
Java
asf20
5,243
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthConstants.java
Java
asf20
1,200
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthService.java
Java
asf20
7,870
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/RecordingStateReceiver.java
Java
asf20
2,316
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerCupcake.java
Java
asf20
6,236
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerFactory.java
Java
asf20
1,650
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthPreferences.java
Java
asf20
2,044
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
0000som143-mytracks
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListener.java
Java
asf20
1,157
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.samples.api; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * A receiver to receive MyTracks notifications. * * @author Jimmy Shih */ public class MyTracksReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); long trackId = intent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L); Toast.makeText(context, action + " " + trackId, Toast.LENGTH_LONG).show(); } }
0000som143-mytracks
MyTracksApiSample/src/com/google/android/apps/mytracks/samples/api/MyTracksReceiver.java
Java
asf20
1,220
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.samples.api; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.ITrackRecordingService; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Calendar; import java.util.List; /** * An activity to access MyTracks content provider and service. * * Note you must first install MyTracks before installing this app. * * You also need to enable third party application access inside MyTracks * MyTracks -> menu -> Settings -> Sharing -> Allow access * * @author Jimmy Shih */ public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); // utils to access the MyTracks content provider private MyTracksProviderUtils myTracksProviderUtils; // display output from the MyTracks content provider private TextView outputTextView; // MyTracks service private ITrackRecordingService myTracksService; // intent to access the MyTracks service private Intent intent; // connection to the MyTracks service private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { myTracksService = ITrackRecordingService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName className) { myTracksService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // for the MyTracks content provider myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); outputTextView = (TextView) findViewById(R.id.output); Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button); addWaypointsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Track> tracks = myTracksProviderUtils.getAllTracks(); Calendar now = Calendar.getInstance(); for (Track track : tracks) { Waypoint waypoint = new Waypoint(); waypoint.setTrackId(track.getId()); waypoint.setName(now.getTime().toLocaleString()); waypoint.setDescription(now.getTime().toLocaleString()); myTracksProviderUtils.insertWaypoint(waypoint); } } }); // for the MyTracks service intent = new Intent(); ComponentName componentName = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); intent.setComponent(componentName); Button startRecordingButton = (Button) findViewById(R.id.start_recording_button); startRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.startNewTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button); stopRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.endCurrentTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); } @Override protected void onStart() { super.onStart(); // use the MyTracks content provider to get all the tracks List<Track> tracks = myTracksProviderUtils.getAllTracks(); for (Track track : tracks) { outputTextView.append(track.getId() + " "); } // start and bind the MyTracks service startService(intent); bindService(intent, serviceConnection, 0); } @Override protected void onStop() { super.onStop(); // unbind and stop the MyTracks service if (myTracksService != null) { unbindService(serviceConnection); } stopService(intent); } }
0000som143-mytracks
MyTracksApiSample/src/com/google/android/apps/mytracks/samples/api/MainActivity.java
Java
asf20
5,172
#ifndef DRIVE_H_ #define DRIVE_H_ #include "WPILib.h" #include "GlobalInclude.h" class Drive { public: Drive(); virtual ~Drive(); void printLeft(void); void jagDebug(int); void printRight(void); /* CANJaguar *leftJag;// CAN attached Jag for the Left1 motor **** 2 CANJaguar *rightJag;// CAN attached Jag for the Right1 motor ** 3 CANJaguar *leftJag2;// 4 CANJaguar *rightJag2;//5 */ Jaguar *leftJag; Jaguar *rightJag; Jaguar *leftJag2; Jaguar *rightJag2; Encoder *leftEnc; Encoder *rightEnc; DoubleSolenoid *shifter; // 1,2 RobotDrive *myRobot; // robot drive system }; #endif /*DRIVE_H_*/
1138eagle-engineering2011
Drive.h
C++
gpl3
675
#ifndef ARM_H_ #define ARM_H_ #include "WPILib.h" #include "DoubleSolenoid.h" #include "GlobalInclude.h" #include "PIDCalculator.h" #include "OperatorInterface.h" class Arm { public: Arm(OperatorInterface *oiArmX); //void jagDebug(int); virtual ~Arm(); void liftInit(void); OperatorInterface *oiArm; Jaguar *lift1; // 6 Jaguar *lift2; // 7 Jaguar *arm; // 8 DigitalInput *bottomLiftSwitch; DigitalInput *topLiftSwitch; DigitalInput *bottomArmSwitch; DigitalInput *topArmSwitch; Encoder *liftEnc; //Encoder *armEnc; PIDCalculator *armCalc; PIDCalculator *liftCalc; PIDController *liftPID; PIDController *armPID; DoubleSolenoid *gripperSolenoid; // 3 DoubleSolenoid *minibotSolenoid; // 4 DoubleSolenoid *brakeSolenoid; void liftSubroutine(); void armSubroutine(); //AnalogInput *armPot; private: float Kpl, Kil, Kdl, Kpa, Kia, Kda; float liftSetpoints[8]; }; #endif /*ARM_H_*/
1138eagle-engineering2011
Arm.h
C++
gpl3
972
#ifndef PHOTOSWITCH_H_ #define PHOTOSWITCH_H_ #include "WPIlib.h" #include "GlobalInclude.h" #include "Sensor.h" class PhotoSwitch { public: PhotoSwitch(Drive *y); ~PhotoSwitch(void); int onLight(void); int onDark(void); int onDark1(void); int onDark3(void); int allLight(void); int allDark(void); int dLeft(void); int dRight(void); int lLeft(void); int lRight(void); float drive(int); float getLeftSpeed(void); float getRightSpeed(void); //void gyroSubroutine(int); DigitalInput *p1;//dark 1 DigitalInput *p2;//dark 2 DigitalInput *p3;//dark 3 DigitalInput *p4;//light 1 DigitalInput *p5;//light 2 DigitalInput *p6;//light 3 //Sensor *sensor; float leftSpeed; float rightSpeed; int binary; Sensor *sensor; private: float steeringGain; }; #endif /*PHOTOSWITCH_H_*/
1138eagle-engineering2011
PhotoSwitch.h
C++
gpl3
870
#include "WPILib.h" #include "GlobalInclude.h" //#include "CANJaguar.h" #include "PhotoSwitch.h" #include "Drive.h" #include "OperatorInterface.h" #include "PIDCalculator.h" #include "Arm.h" #define waitTime 0.01//try 0.05 or 0.1 class CANRobotDemo : public IterativeRobot { Drive *dr; OperatorInterface *oi; PhotoSwitch *ps; Arm *arm; Compressor *comp; public: CANRobotDemo(void){ //SmartDashboard::init(); GetWatchdog().SetExpiration(100); }//end of constructor void RobotInit() { printf("RobotInit"); /*****moved from constructor*****/ wpi_stackTraceEnable(true); dr = new Drive(); oi = new OperatorInterface(); ps = new PhotoSwitch(dr); arm = new Arm(oi); comp = new Compressor(10,1); /*****end moved*****/ //oi->lcd->Printf(DriverStationLCD::kMain_Line6, 1, "Bus Voltage: %f",dr->leftJag->GetBusVoltage()); }//end of RobotInit void AutonomousInit(void) { printf("AutonomousInit\n"); GetWatchdog().SetEnabled(false); oi->updateButtons(); arm->liftInit(); }//end of AutonomousInit void AutonomousPeriodic(void) { ps->drive(oi->ds->GetDigitalIn(1)); dr->myRobot->TankDrive(ps->leftSpeed,ps->rightSpeed); if((ps->allLight()) || (ps->allDark())) { //run lift and arm } //SmartDashboard::Log /* printf("onDark: %i\n", ps->onDark()); printf("onDark1: %i\n", ps->onDark1()); printf("onDark3: %i\n", ps->onDark3()); printf("dleft: %i\n", ps->dLeft()); printf("dRight: %i\n", ps->dRight()); printf("allDark: %i\n", ps->allDark()); */ }//end of AutonomousPeriodic void TeleopInit(void) { printf("TeleOpInit\n"); GetWatchdog().SetEnabled(false); arm->liftInit(); oi->updateButtons(); comp->Start(); }//end of TeleopInit void TeleopPeriodic(void) { //printf("my teleopPeriodic\n"); }//end of TeleOpPeriodic void TeleopContinuous(void) { //printf("my teleopContinuous\n"); //printf("killSw true\n"); dr->myRobot->TankDrive(oi->rightStick,oi->leftStick); // drive with tank style arm->liftSubroutine(); arm->armSubroutine(); if(oi->rightStick->GetTrigger()) { dr->shifter->Set(DoubleSolenoid::kForward);//high gear }else if(oi->leftStick->GetTrigger()) { dr->shifter->Set(DoubleSolenoid::kReverse);//low gear }else { //do nothing } //printf("its working"); if(oi->killSw == true) { }else if (oi->killSw == false){ //comp->Stop(); }//end of else } //void TeleOpContinuous(){} not currently used void DisabledInit(void) { printf("DisabledInit\n"); }//end of DisabledInit void DisabledPeriodic(void) { //printf("Disabled\n"); //pid->Disable(); //gyro->Reset(); //delete ps; //ps = NULL; //dr->leftJag->Set(0.0); //dr->rightJag->Set(0.0); //comp->Stop(); }//end of DisabledPeriodic //void DisabledContinuous(void){} not currently used };//end of CANRobotDemo Class START_ROBOT_CLASS(CANRobotDemo);
1138eagle-engineering2011
MyRobot.cpp
C++
gpl3
3,005
#ifndef GLOBALINCLUDE_H_ #define GLOBALINCLUDE_H_ //#define armExperimental 1 #define oiExperimental 1 #define armDebug 0 #define liftDebug 1 #define driveDebug 0 #endif /*GLOBALINCLUDE_H_*/
1138eagle-engineering2011
GlobalInclude.h
C
gpl3
208
#ifndef SENSOR_H_ #define SENSOR_H_ #include "WPILib.h" #include "GlobalInclude.h" #include "PIDCalculator.h" #include "Drive.h" class Sensor { public: Sensor(Drive *z); virtual ~Sensor(); Drive *sensorDrive; Gyro *gyro; PIDCalculator *calc; PIDController *pid; void gyroSubroutine(int); float leftOutput; float rightOutput; }; #endif /*SENSOR_H_*/
1138eagle-engineering2011
Sensor.h
C++
gpl3
380
#include "Sensor.h" Sensor::Sensor(Drive *z) { sensorDrive = z; gyro = new Gyro(1); calc = new PIDCalculator(); pid = new PIDController(0.0625,0.003,0,gyro,calc); pid->SetInputRange(-360,360);//-360 degrees to 360 degrees pid->SetTolerance(0.15);//tolerance is 0.15% of total range pid->SetOutputRange(-1.0,1.0); } void Sensor::gyroSubroutine(int direction)//0 for left, 1 for right { int flag = 0; //outside tolerance zone printf("gyroSubroutine() function called"); if(direction == 0) { pid->SetSetpoint(-12); //take left fork printf("Setpoint = -10"); }else if (direction == 1 ){ pid->SetSetpoint(12); //take right fork printf("Setpoint = 10"); }else{ pid->SetSetpoint(12);//default to right fork printf("Setpoint = default"); }//end of else gyro->Reset(); pid->Enable(); printf("OnTarget: %i", pid->OnTarget()); while(flag == 0) { leftOutput = calc->getOutput()*-1.0; rightOutput = leftOutput * -1.0; sensorDrive->myRobot->TankDrive(leftOutput,rightOutput); printf("Gyro: %f PID Output: %f\n" , gyro->GetAngle(), calc->getOutput()); if((gyro->GetAngle()<13) && (gyro->GetAngle()>11)) { flag = 1; }else if((gyro->GetAngle()>-13) && (gyro->GetAngle()<-11)){ flag = 1; } Wait(0.02); } pid->Disable(); }//end of gyroSubroutine Sensor::~Sensor() { printf("*****Sensor Deconstructor Called*****"); delete pid; delete gyro; delete sensorDrive; delete calc; pid = NULL; gyro = NULL; sensorDrive = NULL; calc = NULL; }
1138eagle-engineering2011
Sensor.cpp
C++
gpl3
1,555
#include "Arm.h" #define manual 1 #define armGain 0.4 #define liftGain 0.5 Arm::Arm(OperatorInterface *oiArmX) { oiArm = oiArmX; lift1 = new Jaguar(5); lift2 = new Jaguar(6); arm = new Jaguar(7); liftEnc = new Encoder(7,8); liftEnc->SetDistancePerPulse(1); liftEnc->Start(); //armEnc = new Encoder(12);//ToDo check the port gripperSolenoid = new DoubleSolenoid(1,2);//shifter is 2 and 3 minibotSolenoid = new DoubleSolenoid(7,8); brakeSolenoid = new DoubleSolenoid(3,4); Kpl = 0.00001; //todo tune PID loop Kil = Kdl = Kia = Kda = 0.0; Kpa = 1.0; //liftSetpoints [8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //max is -4959 liftSetpoints[0] = 4959;//top right 113.5" liftSetpoints[1] = 4036.5;//middle right 76.5" -4036.5 liftSetpoints[2] = 1943.25;//bottom right 39.5" -1943.25 liftSetpoints[3] = 4959;//top left 105" 10" past max liftSetpoints[4] = 3594.75;//middle left 68" -3594.75 liftSetpoints[5] = 1526.75;//bottom left 31" -1526.75 liftSetpoints[6] = 2067.25;//feeding 42" -2067.25 liftSetpoints[7] = 0.0;//ground liftCalc = new PIDCalculator(); liftPID = new PIDController(Kpl,Kil,Kdl,liftEnc,liftCalc); armCalc = new PIDCalculator(); armPID = new PIDController(Kpa,Kia,Kda,liftEnc,armCalc);//CHANGE INPUT //set input range, ouput range, and tolerance for each liftPID->SetSetpoint(0); liftPID->SetTolerance(15); liftPID->SetOutputRange(1,-1); liftPID->SetInputRange(0,-4959); armPID->SetTolerance(.5); armPID->SetOutputRange(-0.5,0.5); topLiftSwitch = new DigitalInput(11); }//end of constructor void Arm::liftInit() { liftPID->Enable(); liftEnc->Reset(); liftPID->SetSetpoint(liftSetpoints[7]); #if liftDebug == 1 SmartDashboard::init(); #endif }//end of liftInit() void Arm::liftSubroutine() { oiArm->updateButtons(); /*********Start Manual Lift Control*********/ #if manual == 1 if(oiArm->ds->GetDigitalIn(4)==0) { lift1->Set(liftGain); lift2->Set(liftGain)); }else if(oiArm->ds->GetDigitalIn(2)==0) { lift1->Set(-liftGain); lift2->Set(-liftGain); }else{ lift1->Set(0.0); lift2->Set(0.0); } brakeSolenoid->Set(DoubleSolenoid::kReverse);//or kForward #endif /*********End Manual Lift Control*********/ /*********Start Setpoint Lift Control*********/ #if manual == 0 if(oiArm->bottomLeft) { liftPID->SetSetpoint(liftSetpoints[5]); printf("bottomLeft"); } else if(oiArm->middleLeft) { liftPID->SetSetpoint(liftSetpoints[4]); printf("middleLeft"); } else if(oiArm->topLeft) { liftPID->SetSetpoint(liftSetpoints[3]); printf("topLeft"); } else if(oiArm->bottomRight) { liftPID->SetSetpoint(liftSetpoints[2]); printf("bottomRight"); } else if(oiArm->middleRight) { liftPID->SetSetpoint(liftSetpoints[1]); printf("middleRight"); } else if(oiArm->topRight) { liftPID->SetSetpoint(liftSetpoints[0]); printf("topRight"); }else if(oiArm->ground) { liftPID->SetSetpoint(liftSetpoints[7]); printf("ground"); }else if(oiArm->feeding) { liftPID->SetSetpoint(liftSetpoints[6]); printf("feeding"); } lift1->Set((-1)*(liftCalc->getOutput())); lift2->Set((-1)*(liftCalc->getOutput())); brakeSolenoid->Set(DoubleSolenoid::kForward);//or backward #endif //end of manual == 0 //printf("LiftEnc: %f\n",liftEnc->GetDistance()); #if liftDebug == 1 SmartDashboard::Log(liftEnc->GetDistance(),"Encoder Value"); SmartDashboard::Log(liftPID->GetSetpoint(),"PID Setpoint"); SmartDashboard::Log(liftPID->GetError(),"PID Error"); SmartDashboard::Log(liftPID->OnTarget(),"OnTarget"); SmartDashboard::Log(liftCalc->getOutput(),"PID Output"); printf("PID Setpoint: %f\n",liftPID->GetSetpoint()); #endif }//end of liftSubroutine void Arm::armSubroutine() { oiArm->updateButtons(); #if manual == 0 if(oiArm->ds->GetDigitalIn(4)==0) { arm->Set(-0.4); }else if(oiArm->ds->GetDigitalIn(2)==0) { arm->Set(0.4); }else{ arm->Set(0.0); } #endif #if manual == 1 if(oiArm->middleRight) { arm->Set(-armGain); //printf("arm down\n"); }else if(oiArm->topRight) { arm->Set(armGain); //printf("arm up\n"); }else{ arm->Set(0.0); } #endif /*****Gripper pneumatics*****/ if(oiArm->gripper) { gripperSolenoid->Set(DoubleSolenoid::kReverse); }else if(oiArm->gripper == false) { gripperSolenoid->Set(DoubleSolenoid::kForward); } /*****Minibot pneumatics*****/ if(oiArm->mbUp==false) { minibotSolenoid->Set(DoubleSolenoid::kReverse); }else if(oiArm->mbDown==false) { minibotSolenoid->Set(DoubleSolenoid::kForward); } // negative values raise the arm }//end of armSubroutine Arm::~Arm() { delete lift1; delete lift2; delete arm; delete oiArm; delete bottomLiftSwitch; delete topLiftSwitch; delete bottomArmSwitch; delete topArmSwitch; delete liftCalc; delete liftPID; delete armCalc; delete armPID; delete liftEnc; delete gripperSolenoid; delete minibotSolenoid; delete brakeSolenoid; oiArm = NULL; lift1 = NULL; lift2 = NULL; arm = NULL; bottomLiftSwitch = NULL; topLiftSwitch = NULL; bottomArmSwitch = NULL; topArmSwitch = NULL; liftCalc = NULL; liftPID = NULL; armCalc = NULL; armPID = NULL; liftEnc = NULL; gripperSolenoid = NULL; minibotSolenoid = NULL; brakeSolenoid = NULL; }
1138eagle-engineering2011
Arm.cpp
C++
gpl3
5,435
#include "OperatorInterface.h" OperatorInterface::OperatorInterface() { leftStick = new Joystick(1); rightStick = new Joystick(2); ds = DriverStation::GetInstance(); lcd = DriverStationLCD::GetInstance(); estop = new Joystick(3); } void OperatorInterface::updateButtons() { #if oiExperimental == 1 killSw = ds->GetDigitalIn(3); //true is enable, false is disabled liftUp = ds->GetDigitalIn(2); //false for up liftDown = ds->GetDigitalIn(4); //false for down mbUp = ds->GetDigitalIn(5); mbDown = ds->GetDigitalIn(7); topRight = estop->GetRawButton(1); middleRight = estop->GetRawButton(2); bottomRight = estop->GetRawButton(3); topLeft = estop->GetRawButton(4); middleLeft = estop->GetRawButton(5); bottomLeft = estop->GetRawButton(6); feeding = estop->GetRawButton(7); ground = estop->GetRawButton(8); gripper = estop->GetRawButton(9); lineTrack = estop->GetRawButton(10); //true is up forkDirection = estop->GetRawButton(11); //0 for left, 1 for right #endif } OperatorInterface::~OperatorInterface() { delete leftStick; delete rightStick; delete estop; delete ds; leftStick = NULL; rightStick = NULL; estop = NULL; ds = NULL; }
1138eagle-engineering2011
OperatorInterface.cpp
C++
gpl3
1,219
#include "PIDCalculator.h" PIDCalculator::PIDCalculator() { printf("PIDCalculator Initialized"); pidOutput = 0; } PIDCalculator::~PIDCalculator() { printf("PIDCalculator Deconstructor Called"); //delete instance; //instance = NULL; } float PIDCalculator::getOutput() { return pidOutput; } void PIDCalculator::PIDWrite(float output) { //printf("PIDWrite Called\n"); pidOutput = output; } /* PIDCalculator* PIDCalculator::Clone() { if(instance == NULL) { instance = new PIDCalculator(); }//end of if return instance; } */
1138eagle-engineering2011
PIDCalculator.cpp
C++
gpl3
576
#include "WPILib.h" #include "Drive.h" Drive::Drive() { /* leftJag = new CANJaguar(5); // These must be initialized in the same order rightJag = new CANJaguar(3); // as they are declared above. leftJag2 = new CANJaguar(4); rightJag2 = new CANJaguar(2); */ leftJag = new Jaguar(4); // These must be initialized in the same order leftJag2 = new Jaguar(3); rightJag = new Jaguar(2); // as they are declared above. rightJag2 = new Jaguar(1); //myRobot = new RobotDrive(leftJag, rightJag); myRobot = new RobotDrive(leftJag, leftJag2, rightJag, rightJag2); //myRobot->SetSafetyEnabled(false); shifter = new DoubleSolenoid(5,6); //myRobot->SetInvertedMotor(RobotDrive::kFrontRightMotor, true); //myRobot->SetInvertedMotor(RobotDrive::kFrontLeftMotor, true); //myRobot->SetInvertedMotor(RobotDrive::kRearRightMotor, true); //myRobot->SetInvertedMotor(RobotDrive::kRearLeftMotor, true); }//end of constructor Drive::~Drive() { delete leftJag; delete leftJag2; delete rightJag; delete rightJag2; delete myRobot; delete shifter; leftJag = NULL; leftJag2 = NULL; rightJag = NULL; rightJag2 = NULL; myRobot = NULL; shifter = NULL; }
1138eagle-engineering2011
Drive.cpp
C++
gpl3
1,199
#ifndef PIDCALCULATOR_H_ #define PIDCALCULATOR_H_ #include "WPILib.h" #include "GlobalInclude.h" class PIDCalculator : public PIDOutput { public: //static PIDCalculator* PIDCalculator::instance; PIDCalculator(); virtual ~PIDCalculator(); virtual void PIDWrite(float output); virtual float getOutput(void); //static PIDCalculator *Clone(void); protected: private: float pidOutput; }; #endif /*PIDCALCULATOR_H_*/
1138eagle-engineering2011
PIDCalculator.h
C++
gpl3
454
#ifndef OPERATORINTERFACE_H_ #define OPERATORINTERFACE_H_ #include "WPILib.h" #include "GlobalInclude.h" class OperatorInterface { public: OperatorInterface(); virtual ~OperatorInterface(); void updateButtons(void); Joystick *leftStick; // left joystick Joystick *rightStick; DriverStation *ds; DriverStationLCD *lcd; #if oiExperimental == 1 Joystick *estop; bool killSw; bool liftUp;//false is up bool liftDown;//false is down bool lineTrack; bool topRight, middleRight, bottomRight; bool topLeft, middleLeft, bottomLeft; bool feeding, ground; bool gripper; bool forkDirection; bool mbUp; bool mbDown; //true on the two above is center #endif }; #endif /*OPERATORINTERFACE_H_*/
1138eagle-engineering2011
OperatorInterface.h
C++
gpl3
739
#include "PhotoSwitch.h" #define defaultSteeringGain 0.3 #define defaultLeftSpeed -0.5 #define defaultRightSpeed -0.5 #define lineStyle 0 //1 for Dark, 0 for Light PhotoSwitch::PhotoSwitch(Drive *y) { p1 = new DigitalInput(1);//dark 1 p2 = new DigitalInput(2);//dark 2 p3 = new DigitalInput(3);//dark 3 p4 = new DigitalInput(4);//light 1 p5 = new DigitalInput(5);//light 2 p6 = new DigitalInput(6);//light 3 sensor = new Sensor(y); binary = 0; steeringGain = 0; leftSpeed = 0; rightSpeed = 0; //s1 = p1->Get(); //s2 = p2->Get(); //s3 = p3->Get(); //printf("Left Dark: %f\n" , p1->Get()); //printf("Center Dark: %f\n" , p2->Get()); //printf("Right Dark: %f\n" , p3->Get()); //printf("Left Light: %f\n" , p4->Get()); //printf("Center Light: %f\n" , p5->Get()); //printf("Right Light: %f\n" , p6->Get()); } float PhotoSwitch::drive(int x)//parameter of fork selection: 0 for left, 1 for right { if(lineStyle == 1){ binary = ((onDark()) + (onDark3()*3) + (dRight()*2) + (onDark1() *2) + (dLeft()*3) + ((allDark()*4) )); if (binary == 4){ binary += x; }//end of embedded if }else if (lineStyle == 0){ binary = onLight() + (lRight()*2) + (lLeft()*3) + ((allLight()*4) + x); }else{ binary = 0; }//end of else switch(binary){ case 1: //on line printf("Case 1\n"); leftSpeed = defaultLeftSpeed; rightSpeed = defaultRightSpeed; //printf("leftSpeed: %f\n", leftSpeed); //printf("rightSpeed: %f\n", rightSpeed); //drive straight break; case 2: //error to the left printf("Case 2\n"); leftSpeed = 0.0; rightSpeed = -0.7;//correct to the right //printf("Right Speed: %i \n", rightSpeed); break; case 3: //error to the right printf("Case 3\n"); leftSpeed = -0.7; rightSpeed = 0.0;//correct to the left //printf("Left Speed: %i \n", leftSpeed); break; case 4: //ALL Dark; fork to the left printf("Case 4\n"); leftSpeed = 0.0; rightSpeed = 0.0; //sensor->gyroSubroutine(0); break; case 5: //ALL Dark; fork to the right printf("Case 5\n"); leftSpeed = 0.0; rightSpeed = 0.0; //sensor->gyroSubroutine(1); break; case 6: case 0: printf("Case 0\n"); //no sensors - do nothing leftSpeed = -0.2; rightSpeed = -0.2; break; default: //what is wrong?? printf("Default\n"); leftSpeed = 0; rightSpeed = 0; //do nothing break; }//end of binary switch return steeringGain; }//end of drive float PhotoSwitch::getLeftSpeed() { return leftSpeed; } float PhotoSwitch::getRightSpeed() { return rightSpeed; } int PhotoSwitch::onDark()//following Dark line accurately { if((p2->Get()== 0) && (p1->Get() == 1) && (p3->Get() == 1)) { return 1; } else { return 0; } }//end of onDark int PhotoSwitch::onDark1()//follow Dark line { if((p1->Get() == 0) && (p2->Get() == 1) && (p3->Get() == 1)) { return 1; } else { return 0; } } int PhotoSwitch::onDark3()//follow Dark line { if((p1->Get() == 1) && (p2->Get() == 1) && (p3->Get() == 0)) { return 1; } else { return 0; } } int PhotoSwitch::dLeft()//error to the left { if((p2->Get()== 0) && (p1->Get() == 1) && (p3->Get() == 0)) { return 1; } else { return 0; } }//end of dLeft int PhotoSwitch::dRight()//error to the right { if((p2->Get()== 0) && (p1->Get() == 0) && (p3->Get() == 1)) { return 1; } else { return 0; } }//end of dRgiht int PhotoSwitch::onLight()//following Light line accurately { if((p5->Get()== 0) && (p4->Get() == 1) && (p6->Get() == 1)) { return 1; } else { return 0; } }//end of onLight int PhotoSwitch::lLeft()//error to the left { if((p5->Get()== 0) && (p4->Get() == 1) && (p6->Get() == 0)) { return 1; } else { return 0; } }//end of lLeft int PhotoSwitch::lRight()//error to the right { if((p5->Get()== 0) && (p4->Get() == 0) && (p6->Get() == 1)) { return 1; } else { return 0; } }//end of lRight int PhotoSwitch::allDark()//Dark fork { if((p2->Get()== 0) && (p1->Get() == 0) && (p3->Get() == 0)) { return 1; } else { return 0; } }//end of allDark int PhotoSwitch::allLight()//Light fork { if((p5->Get()== 0) && (p4->Get() == 0) && (p6->Get() == 0)) { return 1; } else { return 0; } }//end of allLight PhotoSwitch::~PhotoSwitch() { printf("*****Photoswitch Deconstructor Called*****"); delete sensor; sensor = NULL; }//end of deconstructor
1138eagle-engineering2011
PhotoSwitch.cpp
C++
gpl3
4,404
#!/bin/sh # Create a backup tar gzip file of the cwd with the date appended # located in the parent directory. FILENAME=../`pwd|xargs basename`-`date -j "+%Y-%m-%d"`.tgz echo Will create $FILENAME tar cfz $FILENAME . echo Done.
115371172-shuffle
createBackup.sh
Shell
asf20
232
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboListActivity; public abstract class FlurryEnabledListActivity extends RoboListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledListActivity.java
Java
asf20
479
package org.dodgybits.shuffle.android.core.activity.flurry; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryApiKey; import java.util.Map; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.Context; import com.flurry.android.FlurryAgent; import com.google.inject.Inject; public class Analytics { private Context mContext; @Inject public Analytics(Context context) { mContext = context; } public void start() { if (isEnabled()) { FlurryAgent.onStartSession(mContext, cFlurryApiKey); } } public void stop() { if (isEnabled()) { FlurryAgent.onEndSession(mContext); } } public void onEvent(String eventId, Map<String, String> parameters) { if (isEnabled()) { FlurryAgent.onEvent(eventId, parameters); } } public void onEvent(String eventId) { if (isEnabled()) { FlurryAgent.onEvent(eventId); } } public void onError(String errorId, String message, String errorClass) { if (isEnabled()) { FlurryAgent.onError(errorId, message, errorClass); } } public void onPageView(Context context) { if (isEnabled()) { FlurryAgent.onPageView(); } } private boolean isEnabled() { return Preferences.isAnalyticsEnabled(mContext); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/Analytics.java
Java
asf20
1,482
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboExpandableListActivity; public abstract class FlurryEnabledExpandableListActivity extends RoboExpandableListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledExpandableListActivity.java
Java
asf20
509
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboPreferenceActivity; public abstract class FlurryEnabledPreferenceActivity extends RoboPreferenceActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledPreferenceActivity.java
Java
asf20
497
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboActivity; public abstract class FlurryEnabledActivity extends RoboActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledActivity.java
Java
asf20
472
package org.dodgybits.shuffle.android.core.activity.flurry; import android.content.Intent; import com.google.inject.Inject; import roboguice.service.RoboService; public abstract class FlurryEnabledService extends RoboService { @Inject protected Analytics mAnalytics; @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); mAnalytics.start(); } @Override public void onDestroy() { super.onDestroy(); mAnalytics.stop(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledService.java
Java
asf20
538
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.activity; import static org.dodgybits.shuffle.android.core.util.Constants.cPackage; import static org.dodgybits.shuffle.android.core.util.Constants.cStringType; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.inject.InjectView; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; public class HelpActivity extends FlurryEnabledActivity { public static final String cHelpPage = "helpPage"; @InjectView(R.id.help_screen) Spinner mHelpSpinner; @InjectView(R.id.help_text) TextView mHelpContent; @InjectView(R.id.previous_button) Button mPrevious; @InjectView(R.id.next_button) Button mNext; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.help); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.help_screens, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mHelpSpinner.setAdapter(adapter); mHelpSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onNothingSelected(AdapterView<?> arg0) { // do nothing } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { int resId = HelpActivity.this.getResources().getIdentifier( "help" + position, cStringType, cPackage); mHelpContent.setText(HelpActivity.this.getText(resId)); updateNavigationButtons(); } }); mPrevious.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position - 1); } }); mNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position + 1); } }); setSelectionFromBundle(getIntent().getExtras()); } private void setSelectionFromBundle(Bundle bundle) { int position = 0; if (bundle != null) { position = bundle.getInt(cHelpPage, 0); } mHelpSpinner.setSelection(position); } private void updateNavigationButtons() { int position = mHelpSpinner.getSelectedItemPosition(); mPrevious.setEnabled(position > 0); mNext.setEnabled(position < mHelpSpinner.getCount() - 1); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/HelpActivity.java
Java
asf20
3,581
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.InjectView; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import com.google.inject.Inject; public class WelcomeActivity extends FlurryEnabledActivity { private static final String cTag = "WelcomeActivity"; @InjectView(R.id.sample_data_button) Button mSampleDataButton; @InjectView(R.id.clean_slate_button) Button mCleanSlateButton; @Inject InitialDataGenerator mGenerator; private Handler mHandler; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Log.d(cTag, "onCreate"); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.welcome); mSampleDataButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCreateSampleData(); } }); mCleanSlateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCleanSlate(); } }); mHandler = new Handler() { @Override public void handleMessage(Message msg) { updateFirstTimePref(false); // Stop the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); startActivity(new Intent(WelcomeActivity.this, TopLevelActivity.class)); finish(); } }; } private void disableButtons() { mCleanSlateButton.setEnabled(false); mSampleDataButton.setEnabled(false); } private void startProgressAnimation() { // Start the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); } private void performCreateSampleData() { Log.i(cTag, "Adding sample data"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.createSampleData(mHandler); } }.start(); } private void performCleanSlate() { Log.i(cTag, "Cleaning the slate"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.cleanSlate(mHandler); } }.start(); } private void updateFirstTimePref(boolean value) { SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putBoolean(Preferences.FIRST_TIME, value); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID) || super.onOptionsItemSelected(item); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/WelcomeActivity.java
Java
asf20
4,453
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.activity; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.service.SynchronizationService; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class BootstrapActivity extends FlurryEnabledActivity { private static final String cTag = "BootstrapActivity"; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Class<? extends Activity> activityClass = null; boolean firstTime = Preferences.isFirstTime(this); if (firstTime) { Log.i(cTag, "First time using Shuffle. Show intro screen"); activityClass = WelcomeActivity.class; } else { activityClass = TopLevelActivity.class; } startService(new Intent(this, SynchronizationService.class)); startActivity(new Intent(this, activityClass)); finish(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/BootstrapActivity.java
Java
asf20
1,693
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.activity; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.core.util.Constants; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.*; import org.dodgybits.shuffle.android.list.config.DueActionsListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.app.AlertDialog; import android.app.Dialog; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.AndroidException; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Displays a list of the main activities. */ public class TopLevelActivity extends FlurryEnabledListActivity { private static final String cTag = "TopLevelActivity"; private static final int INBOX = 0; private static final int DUE_TASKS = 1; private static final int TOP_TASKS = 2; private static final int PROJECTS = 3; private static final int CONTEXTS = 4; private static final int TICKLER = 5; private static final int ITEM_COUNT = 6; private static final String[] cProjection = new String[]{"_id"}; private final static int WHATS_NEW_DIALOG = 0; private Integer[] mIconIds = new Integer[ITEM_COUNT]; private AsyncTask<?, ?, ?> mTask; @Inject @Inbox private TaskListConfig mInboxConfig; @Inject @DueTasks private DueActionsListConfig mDueTasksConfig; @Inject @TopTasks private TaskListConfig mTopTasksConfig; @Inject @Tickler private TaskListConfig mTicklerConfig; @Inject @Projects private ListConfig mProjectsConfig; @Inject @Contexts private ListConfig mContextsConfig; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.top_level); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); addVersionToTitle(); checkLastVersion(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.findItem(MenuUtils.SYNC_ID); if (item != null) { item.setVisible(Preferences.validateTracksSettings(this)); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); MenuUtils.addSearchMenuItem(this, menu); MenuUtils.addSyncMenuItem(this, menu); return true; } @Override protected void onResume() { Log.d(cTag, "onResume+"); super.onResume(); CursorGenerator[] generators = new CursorGenerator[ITEM_COUNT]; generators[INBOX] = new EntityCursorGenerator(mInboxConfig); generators[DUE_TASKS] = new EntityCursorGenerator(mDueTasksConfig); generators[TOP_TASKS] = new EntityCursorGenerator(mTopTasksConfig); generators[PROJECTS] = new EntityCursorGenerator(mProjectsConfig); generators[CONTEXTS] = new EntityCursorGenerator(mContextsConfig); generators[TICKLER] = new EntityCursorGenerator(mTicklerConfig); mIconIds[INBOX] = R.drawable.inbox; mIconIds[DUE_TASKS] = R.drawable.due_actions; mIconIds[TOP_TASKS] = R.drawable.next_actions; mIconIds[PROJECTS] = R.drawable.projects; mIconIds[CONTEXTS] = R.drawable.contexts; mIconIds[TICKLER] = R.drawable.ic_media_pause; mTask = new CalculateCountTask().execute(generators); String[] perspectives = getResources().getStringArray(R.array.perspectives).clone(); ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.list_item_view, R.id.name, perspectives, mIconIds); setListAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) { mTask.cancel(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (MenuUtils.checkCommonItemsSelected(item, this, -1)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { MenuUtils.checkCommonItemsSelected(position + MenuUtils.INBOX_ID, this, -1, false); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; if (id == WHATS_NEW_DIALOG) { dialog = new AlertDialog.Builder(this) .setTitle(R.string.whats_new_dialog_title) .setPositiveButton(R.string.ok_button_title, null) .setMessage(R.string.whats_new_dialog_message) .create(); } else { dialog = super.onCreateDialog(id); } return dialog; } private interface CursorGenerator { Cursor generate(); } private class EntityCursorGenerator implements CursorGenerator { private EntitySelector mEntitySelector; public EntityCursorGenerator(ListConfig config) { mEntitySelector = config.getEntitySelector(); mEntitySelector = mEntitySelector.builderFrom() .applyListPreferences(TopLevelActivity.this, config.getListPreferenceSettings()) .build(); } public Cursor generate() { return getContentResolver().query( mEntitySelector.getContentUri(), cProjection, mEntitySelector.getSelection(TopLevelActivity.this), mEntitySelector.getSelectionArgs(), mEntitySelector.getSortOrder()); } } private class UriCursorGenerator implements CursorGenerator { private Uri mUri; public UriCursorGenerator(Uri uri) { mUri = uri; } public Cursor generate() { return getContentResolver().query( mUri, cProjection, null, null, null); } } private class CalculateCountTask extends AsyncTask<CursorGenerator, CharSequence[], Void> { public Void doInBackground(CursorGenerator... params) { String[] perspectives = getResources().getStringArray(R.array.perspectives); int colour = getResources().getColor(R.drawable.pale_blue); ForegroundColorSpan span = new ForegroundColorSpan(colour); CharSequence[] labels = new CharSequence[perspectives.length]; int length = perspectives.length; for (int i = 0; i < length; i++) { labels[i] = " " + perspectives[i]; } int[] cachedCounts = Preferences.getTopLevelCounts(TopLevelActivity.this); if (cachedCounts != null && cachedCounts.length == length) { for (int i = 0; i < length; i++) { CharSequence label = labels[i] + " (" + cachedCounts[i] + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, labels[i].length(), label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; } } publishProgress(labels); String cachedCountStr = ""; for (int i = 0; i < length; i++) { CursorGenerator generator = params[i]; Cursor cursor = generator.generate(); int count = cursor.getCount(); cursor.close(); CharSequence label = " " + perspectives[i] + " (" + count + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, perspectives[i].length() + 2, label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; publishProgress(labels); cachedCountStr += count; if (i < length - 1) { cachedCountStr += ","; } } // updated cached counts SharedPreferences.Editor editor = Preferences.getEditor(TopLevelActivity.this); editor.putString(Preferences.TOP_LEVEL_COUNTS_KEY, cachedCountStr); editor.commit(); return null; } @Override public void onProgressUpdate(CharSequence[]... progress) { CharSequence[] labels = progress[0]; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( TopLevelActivity.this, R.layout.list_item_view, R.id.name, labels, mIconIds); int position = getSelectedItemPosition(); setListAdapter(adapter); setSelection(position); } @SuppressWarnings("unused") public void onPostExecute() { mTask = null; } } private void addVersionToTitle() { String title = getTitle().toString(); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); title += " " + info.versionName; setTitle(title); } catch (AndroidException e) { Log.e(cTag, "Failed to add version to title: " + e.getMessage()); } } private void checkLastVersion() { final int lastVersion = Preferences.getLastVersion(this); if (Math.abs(lastVersion) < Math.abs(Constants.cVersion)) { // This is a new install or an upgrade. // show what's new message SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putInt(Preferences.LAST_VERSION, Constants.cVersion); editor.commit(); showDialog(WHATS_NEW_DIALOG); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/TopLevelActivity.java
Java
asf20
11,447
package org.dodgybits.shuffle.android.core.activity; import java.util.ArrayList; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class LauncherShortcutActivity extends FlurryEnabledListActivity { private static final String cScreenId = "screenId"; private static final int NEW_TASK = 0; private static final int INBOX = 1; private static final int DUE_TASKS = 2; private static final int TOP_TASKS = 3; private static final int PROJECTS = 4; private static final int CONTEXTS = 5; private List<String> mLabels; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); final String action = getIntent().getAction(); setContentView(R.layout.launcher_shortcut); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); String[] perspectives = getResources().getStringArray(R.array.perspectives); mLabels = new ArrayList<String>(); // TODO figure out a non-retarded way of added padding between text and icon mLabels.add(0, " " + getString(R.string.title_new_task)); for (String label : perspectives) { mLabels.add(" " + label); } if (!Intent.ACTION_CREATE_SHORTCUT.equals(action)) { int screenId = getIntent().getExtras().getInt(cScreenId, -1); if (screenId < INBOX && screenId > CONTEXTS) { // unknown id - just go to BootstrapActivity startActivity(new Intent(this, BootstrapActivity.class)); } else { int menuIndex = (screenId - INBOX) + MenuUtils.INBOX_ID; MenuUtils.checkCommonItemsSelected( menuIndex, this, -1, false); } finish(); return; } setTitle(R.string.title_shortcut_picker); Integer[] iconIds = new Integer[6]; iconIds[NEW_TASK] = R.drawable.list_add; iconIds[INBOX] = R.drawable.inbox; iconIds[DUE_TASKS] = R.drawable.due_actions; iconIds[TOP_TASKS] = R.drawable.next_actions; iconIds[PROJECTS] = R.drawable.projects; iconIds[CONTEXTS] = R.drawable.contexts; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.text_item_view, R.id.name, mLabels.toArray(new String[0]), iconIds); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent shortcutIntent; Parcelable iconResource; if (position == NEW_TASK) { shortcutIntent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon_add); } else { shortcutIntent = new Intent(this, LauncherShortcutActivity.class); shortcutIntent.putExtra(cScreenId, position); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon); } Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mLabels.get(position).trim()); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); finish(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/activity/LauncherShortcutActivity.java
Java
asf20
3,847
package org.dodgybits.shuffle.android.core.configuration; import android.content.ContextWrapper; import com.google.inject.Provides; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.encoding.ContextEncoder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.encoding.ProjectEncoder; import org.dodgybits.shuffle.android.core.model.encoding.TaskEncoder; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.DefaultEntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.*; import org.dodgybits.shuffle.android.list.config.*; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import roboguice.config.AbstractAndroidModule; import com.google.inject.TypeLiteral; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.no; public class ShuffleModule extends AbstractAndroidModule { @Override protected void configure() { addCaches(); addPersisters(); addEncoders(); addListPreferenceSettings(); addListConfig(); } private void addCaches() { bind(new TypeLiteral<EntityCache<Context>>() {}).to(new TypeLiteral<DefaultEntityCache<Context>>() {}); bind(new TypeLiteral<EntityCache<Project>>() {}).to(new TypeLiteral<DefaultEntityCache<Project>>() {}); } private void addPersisters() { bind(new TypeLiteral<EntityPersister<Context>>() {}).to(ContextPersister.class); bind(new TypeLiteral<EntityPersister<Project>>() {}).to(ProjectPersister.class); bind(new TypeLiteral<EntityPersister<Task>>() {}).to(TaskPersister.class); } private void addEncoders() { bind(new TypeLiteral<EntityEncoder<Context>>() {}).to(ContextEncoder.class); bind(new TypeLiteral<EntityEncoder<Project>>() {}).to(ProjectEncoder.class); bind(new TypeLiteral<EntityEncoder<Task>>() {}).to(TaskEncoder.class); } private void addListPreferenceSettings() { bind(ListPreferenceSettings.class).annotatedWith(Inbox.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cInbox)); bind(ListPreferenceSettings.class).annotatedWith(TopTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cNextTasks) .setDefaultCompleted(Flag.no) .disableCompleted() .disableDeleted() .disableActive()); ListPreferenceSettings projectSettings = new ListPreferenceSettings(StandardTaskQueries.cProjectFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ProjectTasks.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(Projects.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableProjects.class).toInstance(projectSettings); ListPreferenceSettings contextSettings = new ListPreferenceSettings(StandardTaskQueries.cContextFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ContextTasks.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(Contexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableContexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(DueTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cDueTasksFilterPrefs).setDefaultCompleted(Flag.no)); bind(ListPreferenceSettings.class).annotatedWith(Tickler.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cTickler) .setDefaultCompleted(Flag.no) .setDefaultActive(Flag.no)); } private void addListConfig() { bind(DueActionsListConfig.class).annotatedWith(DueTasks.class).to(DueActionsListConfig.class); bind(ContextTasksListConfig.class).annotatedWith(ContextTasks.class).to(ContextTasksListConfig.class); bind(ProjectTasksListConfig.class).annotatedWith(ProjectTasks.class).to(ProjectTasksListConfig.class); bind(ListConfig.class).annotatedWith(Projects.class).to(ProjectListConfig.class); bind(ListConfig.class).annotatedWith(Contexts.class).to(ContextListConfig.class); } @Provides @Inbox TaskListConfig providesInboxTaskListConfig(TaskPersister taskPersister, @Inbox ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cInbox), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_inbox); } }; } @Provides @TopTasks TaskListConfig providesTopTasksTaskListConfig(TaskPersister taskPersister, @TopTasks ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cNextTasks), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.TOP_TASKS_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_next_tasks); } }; } @Provides @Tickler TaskListConfig providesTicklerTaskListConfig(TaskPersister taskPersister, @Tickler ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cTickler), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_tickler); } }; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/configuration/ShuffleModule.java
Java
asf20
7,142
package org.dodgybits.shuffle.android.core; import com.google.inject.Module; import org.dodgybits.shuffle.android.core.configuration.ShuffleModule; import roboguice.application.RoboApplication; import java.util.List; public class ShuffleApplication extends RoboApplication { @Override protected void addApplicationModules(List<Module> modules) { modules.add(new ShuffleModule()); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/ShuffleApplication.java
Java
asf20
410
package org.dodgybits.shuffle.android.core.model; public final class Id { private final long mId; public static final Id NONE = new Id(0L); private Id(long id) { mId = id; } public long getId() { return mId; } public boolean isInitialised() { return mId != 0L; } @Override public String toString() { return isInitialised() ? String.valueOf(mId) : ""; } @Override public boolean equals(Object o) { boolean result = false; if (o instanceof Id) { result = ((Id)o).mId == mId; } return result; } @Override public int hashCode() { return (int)mId; } public static Id create(long id) { Id result = NONE; if (id != 0L) { result = new Id(id); } return result; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Id.java
Java
asf20
907
package org.dodgybits.shuffle.android.core.model; public class Reminder { public Integer id; public final int minutes; public final Method method; public Reminder(Integer id, int minutes, Method method) { this.id = id; this.minutes = minutes; this.method = method; } public Reminder(int minutes, Method method) { this(null, minutes, method); } public static enum Method { DEFAULT, ALERT; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Reminder.java
Java
asf20
416
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Project implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private Id mDefaultContextId = Id.NONE; private long mModifiedDate; private boolean mParallel; private boolean mArchived; private Id mTracksId = Id.NONE; private boolean mDeleted; private boolean mActive = true; private Project() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final Id getDefaultContextId() { return mDefaultContextId; } public final long getModifiedDate() { return mModifiedDate; } public final boolean isParallel() { return mParallel; } public final boolean isArchived() { return mArchived; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public final boolean isDeleted() { return mDeleted; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public boolean isActive() { return mActive; } @Override public final String toString() { return String.format( "[Project id=%1$s name='%2$s' defaultContextId='%3$s' " + "parallel=%4$s archived=%5$s tracksId='%6$s' deleted=%7$s active=%8$s]", mLocalId, mName, mDefaultContextId, mParallel, mArchived, mTracksId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Project> { private Builder() { } private Project result; private static Builder create() { Builder builder = new Builder(); builder.result = new Project(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public Id getDefaultContextId() { return result.mDefaultContextId; } public Builder setDefaultContextId(Id value) { assert value != null; result.mDefaultContextId = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public boolean isParallel() { return result.mParallel; } public Builder setParallel(boolean value) { result.mParallel = value; return this; } public boolean isArchived() { return result.mArchived; } public Builder setArchived(boolean value) { result.mArchived = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Project build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Project returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Project project) { setLocalId(project.mLocalId); setName(project.mName); setDefaultContextId(project.mDefaultContextId); setModifiedDate(project.mModifiedDate); setParallel(project.mParallel); setArchived(project.mArchived); setTracksId(project.mTracksId); setDeleted(project.mDeleted); setActive(project.mActive); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Project.java
Java
asf20
5,810
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public final class Task implements TracksEntity { private Id mLocalId = Id.NONE; private String mDescription; private String mDetails; private Id mContextId = Id.NONE; private Id mProjectId = Id.NONE; private long mCreatedDate; private long mModifiedDate; private long mStartDate; private long mDueDate; private String mTimezone; private boolean mAllDay; private boolean mHasAlarms; private boolean mActive = true; private boolean mDeleted; private Id mCalendarEventId = Id.NONE; // 0-indexed order within a project. private int mOrder; private boolean mComplete; private Id mTracksId = Id.NONE; private Task() { }; @Override public final Id getLocalId() { return mLocalId; } public final String getDescription() { return mDescription; } public final String getDetails() { return mDetails; } public final Id getContextId() { return mContextId; } public final Id getProjectId() { return mProjectId; } public final long getCreatedDate() { return mCreatedDate; } @Override public final long getModifiedDate() { return mModifiedDate; } public final long getStartDate() { return mStartDate; } public final long getDueDate() { return mDueDate; } public final String getTimezone() { return mTimezone; } public final boolean isAllDay() { return mAllDay; } public final boolean hasAlarms() { return mHasAlarms; } public final Id getCalendarEventId() { return mCalendarEventId; } public final int getOrder() { return mOrder; } public final boolean isComplete() { return mComplete; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mDescription; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public boolean isPending() { long now = System.currentTimeMillis(); return mStartDate > now; } @Override public final boolean isValid() { if (TextUtils.isEmpty(mDescription)) { return false; } return true; } @Override public final String toString() { return String.format( "[Task id=%8$s description='%1$s' detail='%2$s' contextId=%3$s projectId=%4$s " + "order=%5$s complete=%6$s tracksId='%7$s' deleted=%9$s active=%10$s]", mDescription, mDetails, mContextId, mProjectId, mOrder, mComplete, mTracksId, mLocalId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Task> { private Builder() { } private Task result; private static Builder create() { Builder builder = new Builder(); builder.result = new Task(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getDescription() { return result.mDescription; } public Builder setDescription(String value) { result.mDescription = value; return this; } public String getDetails() { return result.mDetails; } public Builder setDetails(String value) { result.mDetails = value; return this; } public Id getContextId() { return result.mContextId; } public Builder setContextId(Id value) { assert value != null; result.mContextId = value; return this; } public Id getProjectId() { return result.mProjectId; } public Builder setProjectId(Id value) { assert value != null; result.mProjectId = value; return this; } public long getCreatedDate() { return result.mCreatedDate; } public Builder setCreatedDate(long value) { result.mCreatedDate = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public long getStartDate() { return result.mStartDate; } public Builder setStartDate(long value) { result.mStartDate = value; return this; } public long getDueDate() { return result.mDueDate; } public Builder setDueDate(long value) { result.mDueDate = value; return this; } public String getTimezone() { return result.mTimezone; } public Builder setTimezone(String value) { result.mTimezone = value; return this; } public boolean isAllDay() { return result.mAllDay; } public Builder setAllDay(boolean value) { result.mAllDay = value; return this; } public boolean hasAlarms() { return result.mHasAlarms; } public Builder setHasAlarm(boolean value) { result.mHasAlarms = value; return this; } public Id getCalendarEventId() { return result.mCalendarEventId; } public Builder setCalendarEventId(Id value) { assert value != null; result.mCalendarEventId = value; return this; } public int getOrder() { return result.mOrder; } public Builder setOrder(int value) { result.mOrder = value; return this; } public boolean isComplete() { return result.mComplete; } public Builder setComplete(boolean value) { result.mComplete = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Task build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Task returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Task task) { setLocalId(task.mLocalId); setDescription(task.mDescription); setDetails(task.mDetails); setContextId(task.mContextId); setProjectId(task.mProjectId); setCreatedDate(task.mCreatedDate); setModifiedDate(task.mModifiedDate); setStartDate(task.mStartDate); setDueDate(task.mDueDate); setTimezone(task.mTimezone); setAllDay(task.mAllDay); setDeleted(task.mDeleted); setHasAlarm(task.mHasAlarms); setCalendarEventId(task.mCalendarEventId); setOrder(task.mOrder); setComplete(task.mComplete); setTracksId(task.mTracksId); setDeleted(task.mDeleted); setActive(task.mActive); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Task.java
Java
asf20
9,326
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Context implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private int mColourIndex; private String mIconName; private long mModifiedDate; private boolean mDeleted; private boolean mActive = true; private Id mTracksId = Id.NONE; private Context() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final int getColourIndex() { return mColourIndex; } public final String getIconName() { return mIconName; } public final long getModifiedDate() { return mModifiedDate; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public final String toString() { return String.format( "[Context id=%1$s name='%2$s' colourIndex='%3$s' " + "iconName=%4$s tracksId='%5$s' active=%6$s deleted=%7$s]", mLocalId, mName, mColourIndex, mIconName, mTracksId, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Context> { private Builder() { } private Context result; private static Builder create() { Builder builder = new Builder(); builder.result = new Context(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public int getColourIndex() { return result.mColourIndex; } public Builder setColourIndex(int value) { result.mColourIndex = value; return this; } public String getIconName() { return result.mIconName; } public Builder setIconName(String value) { result.mIconName = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Context build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Context returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Context context) { setLocalId(context.mLocalId); setName(context.mName); setColourIndex(context.mColourIndex); setIconName(context.mIconName); setModifiedDate(context.mModifiedDate); setTracksId(context.mTracksId); setDeleted(context.mDeleted); setActive(context.mActive); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Context.java
Java
asf20
5,328
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.COLOUR; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.ICON; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ContextEncoder extends AbstractEntityEncoder implements EntityEncoder<Context> { @Override public void save(Bundle icicle, Context context) { putId(icicle, _ID, context.getLocalId()); putId(icicle, TRACKS_ID, context.getTracksId()); icicle.putLong(MODIFIED_DATE, context.getModifiedDate()); putString(icicle, NAME, context.getName()); icicle.putInt(COLOUR, context.getColourIndex()); putString(icicle, ICON, context.getIconName()); } @Override public Context restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Context.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setColourIndex(icicle.getInt(COLOUR)); builder.setIconName(getString(icicle, ICON)); return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/encoding/ContextEncoder.java
Java
asf20
1,843
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.ARCHIVED; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.DEFAULT_CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.PARALLEL; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ProjectEncoder extends AbstractEntityEncoder implements EntityEncoder<Project> { @Override public void save(Bundle icicle, Project project) { putId(icicle, _ID, project.getLocalId()); putId(icicle, TRACKS_ID, project.getTracksId()); icicle.putLong(MODIFIED_DATE, project.getModifiedDate()); putString(icicle, NAME, project.getName()); putId(icicle, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); icicle.putBoolean(ARCHIVED, project.isArchived()); icicle.putBoolean(PARALLEL, project.isParallel()); } @Override public Project restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Project.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setDefaultContextId(getId(icicle, DEFAULT_CONTEXT_ID)); builder.setArchived(icicle.getBoolean(ARCHIVED)); builder.setParallel(icicle.getBoolean(PARALLEL)); return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/encoding/ProjectEncoder.java
Java
asf20
2,124
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.ALL_DAY; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CAL_EVENT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.COMPLETE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CREATED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DESCRIPTION; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DETAILS; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DUE_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.HAS_ALARM; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.PROJECT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.START_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TIMEZONE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class TaskEncoder extends AbstractEntityEncoder implements EntityEncoder<Task> { @Override public void save(Bundle icicle, Task task) { putId(icicle, _ID, task.getLocalId()); putId(icicle, TRACKS_ID, task.getTracksId()); icicle.putLong(MODIFIED_DATE, task.getModifiedDate()); putString(icicle, DESCRIPTION, task.getDescription()); putString(icicle, DETAILS, task.getDetails()); putId(icicle, CONTEXT_ID, task.getContextId()); putId(icicle, PROJECT_ID, task.getProjectId()); icicle.putLong(CREATED_DATE, task.getCreatedDate()); icicle.putLong(START_DATE, task.getStartDate()); icicle.putLong(DUE_DATE, task.getDueDate()); putString(icicle, TIMEZONE, task.getTimezone()); putId(icicle, CAL_EVENT_ID, task.getCalendarEventId()); icicle.putBoolean(ALL_DAY, task.isAllDay()); icicle.putBoolean(HAS_ALARM, task.hasAlarms()); icicle.putInt(DISPLAY_ORDER, task.getOrder()); icicle.putBoolean(COMPLETE, task.isComplete()); } @Override public Task restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Task.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setDescription(getString(icicle, DESCRIPTION)); builder.setDetails(getString(icicle, DETAILS)); builder.setContextId(getId(icicle, CONTEXT_ID)); builder.setProjectId(getId(icicle, PROJECT_ID)); builder.setCreatedDate(icicle.getLong(CREATED_DATE, 0L)); builder.setStartDate(icicle.getLong(START_DATE, 0L)); builder.setDueDate(icicle.getLong(DUE_DATE, 0L)); builder.setTimezone(getString(icicle, TIMEZONE)); builder.setCalendarEventId(getId(icicle, CAL_EVENT_ID)); builder.setAllDay(icicle.getBoolean(ALL_DAY)); builder.setHasAlarm(icicle.getBoolean(HAS_ALARM)); builder.setOrder(icicle.getInt(DISPLAY_ORDER)); builder.setComplete(icicle.getBoolean(COMPLETE)); return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/encoding/TaskEncoder.java
Java
asf20
3,943
package org.dodgybits.shuffle.android.core.model.encoding; import android.os.Bundle; public interface EntityEncoder<Entity> { void save(Bundle icicle, Entity e); Entity restore(Bundle icicle); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/encoding/EntityEncoder.java
Java
asf20
211
package org.dodgybits.shuffle.android.core.model.encoding; import org.dodgybits.shuffle.android.core.model.Id; import android.os.Bundle; public abstract class AbstractEntityEncoder { protected static Id getId(Bundle icicle, String key) { Id result = Id.NONE; if (icicle.containsKey(key)) { result = Id.create(icicle.getLong(key)); } return result; } protected static void putId(Bundle icicle, String key, Id value) { if (value.isInitialised()) { icicle.putLong(key, value.getId()); } } protected static String getString(Bundle icicle, String key) { String result = null; if (icicle.containsKey(key)) { result = icicle.getString(key); } return result; } protected static void putString(Bundle icicle, String key, String value) { if (value != null) { icicle.putString(key, value); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/encoding/AbstractEntityEncoder.java
Java
asf20
990
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.dto.ShuffleProtos.Context.Builder; public class ContextProtocolTranslator implements EntityProtocolTranslator<Context , org.dodgybits.shuffle.dto.ShuffleProtos.Context>{ public org.dodgybits.shuffle.dto.ShuffleProtos.Context toMessage(Context context) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Context.newBuilder(); builder .setId(context.getLocalId().getId()) .setName((context.getName())) .setModified(ProtocolUtil.toDate(context.getModifiedDate())) .setColourIndex(context.getColourIndex()) .setActive(context.isActive()) .setDeleted(context.isDeleted()); final Id tracksId = context.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } final String iconName = context.getIconName(); if (iconName != null) { builder.setIcon(iconName); } return builder.build(); } public Context fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Context dto) { Context.Builder builder = Context.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setColourIndex(dto.getColourIndex()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } if (dto.hasIcon()) { builder.setIconName(dto.getIcon()); } return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/ContextProtocolTranslator.java
Java
asf20
2,145
package org.dodgybits.shuffle.android.core.model.protocol; import com.google.protobuf.MessageLite; public interface EntityProtocolTranslator<E,M extends MessageLite> { E fromMessage(M message); M toMessage(E entity); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/EntityProtocolTranslator.java
Java
asf20
240
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.dto.ShuffleProtos.Project.Builder; public class ProjectProtocolTranslator implements EntityProtocolTranslator<Project, org.dodgybits.shuffle.dto.ShuffleProtos.Project> { private EntityDirectory<Context> mContextDirectory; public ProjectProtocolTranslator(EntityDirectory<Context> contextDirectory) { mContextDirectory = contextDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Project toMessage(Project project) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Project.newBuilder(); builder .setId(project.getLocalId().getId()) .setName((project.getName())) .setModified(ProtocolUtil.toDate(project.getModifiedDate())) .setParallel(project.isParallel()) .setActive(project.isActive()) .setDeleted(project.isDeleted()); final Id defaultContextId = project.getDefaultContextId(); if (defaultContextId.isInitialised()) { builder.setDefaultContextId(defaultContextId.getId()); } final Id tracksId = project.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Project fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Project dto) { Project.Builder builder = Project.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setParallel(dto.getParallel()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasDefaultContextId()) { Id defaultContextId = Id.create(dto.getDefaultContextId()); Context context = mContextDirectory.findById(defaultContextId); builder.setDefaultContextId(context.getLocalId()); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/ProjectProtocolTranslator.java
Java
asf20
2,599
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.dto.ShuffleProtos.Date; public final class ProtocolUtil { private ProtocolUtil() { // deny } public static Date toDate(long millis) { return Date.newBuilder() .setMillis(millis) .build(); } public static long fromDate(Date date) { long millis = 0L; if (date != null) { millis = date.getMillis(); } return millis; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/ProtocolUtil.java
Java
asf20
536
package org.dodgybits.shuffle.android.core.model.protocol; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.model.Id; public class HashEntityDirectory<Entity> implements EntityDirectory<Entity> { private Map<String,Entity> mItemsByName; private Map<Id, Entity> mItemsById; public HashEntityDirectory() { mItemsByName = new HashMap<String,Entity>(); mItemsById = new HashMap<Id,Entity>(); } public void addItem(Id id, String name, Entity item) { mItemsById.put(id, item); mItemsByName.put(name, item); } @Override public Entity findById(Id id) { return mItemsById.get(id); } @Override public Entity findByName(String name) { return mItemsByName.get(name); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/HashEntityDirectory.java
Java
asf20
736
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.dto.ShuffleProtos.Task.Builder; public class TaskProtocolTranslator implements EntityProtocolTranslator<Task, org.dodgybits.shuffle.dto.ShuffleProtos.Task> { private final EntityDirectory<Context> mContextDirectory; private final EntityDirectory<Project> mProjectDirectory; public TaskProtocolTranslator( EntityDirectory<Context> contextDirectory, EntityDirectory<Project> projectDirectory) { mContextDirectory = contextDirectory; mProjectDirectory = projectDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Task toMessage(Task task) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Task.newBuilder(); builder .setId(task.getLocalId().getId()) .setDescription(task.getDescription()) .setCreated(ProtocolUtil.toDate(task.getCreatedDate())) .setModified(ProtocolUtil.toDate(task.getModifiedDate())) .setStartDate(ProtocolUtil.toDate(task.getStartDate())) .setDueDate(ProtocolUtil.toDate(task.getDueDate())) .setAllDay(task.isAllDay()) .setOrder(task.getOrder()) .setComplete(task.isComplete()) .setActive(task.isActive()) .setDeleted(task.isDeleted()); final String details = task.getDetails(); if (details != null) { builder.setDetails(details); } final Id contextId = task.getContextId(); if (contextId.isInitialised()) { builder.setContextId(contextId.getId()); } final Id projectId = task.getProjectId(); if (projectId.isInitialised()) { builder.setProjectId(projectId.getId()); } final String timezone = task.getTimezone(); if (timezone != null) { builder.setTimezone(timezone); } final Id calEventId = task.getCalendarEventId(); if (calEventId.isInitialised()) { builder.setCalEventId(calEventId.getId()); } final Id tracksId = task.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Task fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Task dto) { Task.Builder builder = Task.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setDescription(dto.getDescription()) .setDetails(dto.getDetails()) .setCreatedDate(ProtocolUtil.fromDate(dto.getCreated())) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setStartDate(ProtocolUtil.fromDate(dto.getStartDate())) .setDueDate(ProtocolUtil.fromDate(dto.getDueDate())) .setTimezone(dto.getTimezone()) .setAllDay(dto.getAllDay()) .setHasAlarm(false) .setOrder(dto.getOrder()) .setComplete(dto.getComplete()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasContextId()) { Id contextId = Id.create(dto.getContextId()); Context context = mContextDirectory.findById(contextId); builder.setContextId(context.getLocalId()); } if (dto.hasProjectId()) { Id projectId = Id.create(dto.getProjectId()); Project project = mProjectDirectory.findById(projectId); builder.setProjectId(project.getLocalId()); } if (dto.hasCalEventId()) { builder.setCalendarEventId(Id.create(dto.getCalEventId())); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/TaskProtocolTranslator.java
Java
asf20
4,337
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Id; /** * A lookup service for entities. Useful when matching up entities from different * sources that may have conflicting ids (e.g. backup or remote synching). */ public interface EntityDirectory<Entity> { public Entity findById(Id id); public Entity findByName(String name); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/protocol/EntityDirectory.java
Java
asf20
398
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.model.persistence; import java.util.Calendar; import java.util.TimeZone; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ResourcesProvider; import com.google.inject.Inject; import android.content.ContentResolver; import android.content.ContentUris; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.text.format.DateUtils; import android.util.Log; public class InitialDataGenerator { private static final String cTag = "InitialDataGenerator"; private static final int AT_HOME_INDEX = 0; private static final int AT_WORK_INDEX = 1; private static final int AT_COMPUTER_INDEX = 2; private static final int ERRANDS_INDEX = 3; private static final int COMMUNICATION_INDEX = 4; private static final int READ_INDEX = 5; private Context[] mPresetContexts = null; private EntityPersister<Context> mContextPersister; private EntityPersister<Project> mProjectPersister; private EntityPersister<Task> mTaskPersister; private ContentResolver mContentResolver; private Resources mResources; @Inject public InitialDataGenerator(EntityPersister<Context> contextPersister, EntityPersister<Project> projectPersister, EntityPersister<Task> taskPersister, ContentResolverProvider provider, ResourcesProvider resourcesProvider ) { mContentResolver = provider.get(); mResources = resourcesProvider.get(); mContextPersister = contextPersister; mProjectPersister = projectPersister; mTaskPersister = taskPersister; initPresetContexts(); } public Context getSampleContext() { return mPresetContexts[ERRANDS_INDEX]; } /** * Delete any existing projects, contexts and tasks and create the standard * contexts. * * @param handler the android message handler */ public void cleanSlate(Handler handler) { initPresetContexts(); int deletedRows = mContentResolver.delete( TaskProvider.Tasks.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " tasks."); deletedRows = mContentResolver.delete( ProjectProvider.Projects.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " projects."); deletedRows = mContentResolver.delete( ContextProvider.Contexts.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " contexts."); for (int i = 0; i < mPresetContexts.length; i++) { mPresetContexts[i] = insertContext(mPresetContexts[i]); } if (handler != null) handler.sendEmptyMessage(0); } /** * Clean out the current data and populate the database with a set of sample * data. * @param handler the message handler */ public void createSampleData(Handler handler) { cleanSlate(null); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long now = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, -1); long yesterday = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 3); long twoDays = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 5); long oneWeek = cal.getTimeInMillis(); cal.add(Calendar.WEEK_OF_YEAR, 1); long twoWeeks = cal.getTimeInMillis(); Project sellBike = createProject("Sell old Powerbook", Id.NONE); sellBike = insertProject(sellBike); insertTask( createTask("Backup data", null, AT_COMPUTER_INDEX, sellBike, now, now + DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Reformat HD", "Install Leopard and updates", AT_COMPUTER_INDEX, sellBike, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Determine good price", "Take a look on ebay for similar systems", AT_COMPUTER_INDEX, sellBike, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Put up ad", AT_COMPUTER_INDEX, sellBike, twoWeeks)); Project cleanGarage = createProject("Clean out garage", Id.NONE); cleanGarage = insertProject(cleanGarage); insertTask( createTask("Sort out contents", "Split into keepers and junk", AT_HOME_INDEX, cleanGarage, yesterday, yesterday)); insertTask( createTask("Advertise garage sale", "Local paper(s) and on craigslist", AT_COMPUTER_INDEX, cleanGarage, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Contact local charities", "See what they want or maybe just put in charity bins", COMMUNICATION_INDEX, cleanGarage, now, now)); insertTask( createTask("Take rest to tip", "Hire trailer?", ERRANDS_INDEX, cleanGarage, now, now)); Project skiTrip = createProject("Organise ski trip", Id.NONE); skiTrip = insertProject(skiTrip); insertTask( createTask("Send email to determine best week", null, COMMUNICATION_INDEX, skiTrip, now, now + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Look up package deals", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book chalet", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book flights", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book hire car", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Get board waxed", ERRANDS_INDEX, skiTrip, 0L)); Project discussI8n = createProject("Discuss internationalization", mPresetContexts[AT_WORK_INDEX].getLocalId()); discussI8n = insertProject(discussI8n); insertTask( createTask("Read up on options", null, AT_COMPUTER_INDEX, discussI8n, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Kickoff meeting", null, COMMUNICATION_INDEX, discussI8n, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Produce report", null, AT_WORK_INDEX, discussI8n, twoWeeks, twoWeeks + 2 * DateUtils.HOUR_IN_MILLIS)); // a few stand alone tasks insertTask( createTask("Organise music collection", AT_COMPUTER_INDEX, null, 0L)); insertTask( createTask("Make copy of door keys", ERRANDS_INDEX, null, yesterday)); insertTask( createTask("Read Falling Man", READ_INDEX, null, 0L)); insertTask( createTask("Buy Tufte books", ERRANDS_INDEX, null, oneWeek)); if (handler != null) handler.sendEmptyMessage(0); } private void initPresetContexts() { if (mPresetContexts == null) { mPresetContexts = new Context[] { createContext(mResources.getText(R.string.context_athome).toString(), 5, "go_home"), // 0 createContext(mResources.getText(R.string.context_atwork).toString(), 19, "system_file_manager"), // 1 createContext(mResources.getText(R.string.context_online).toString(), 1, "applications_internet"), // 2 createContext(mResources.getText(R.string.context_errands).toString(), 14, "applications_development"), // 3 createContext(mResources.getText(R.string.context_contact).toString(), 22, "system_users"), // 4 createContext(mResources.getText(R.string.context_read).toString(), 16, "format_justify_fill") // 5 }; } } private Context createContext(String name, int colourIndex, String iconName) { Context.Builder builder = Context.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setColourIndex(colourIndex) .setIconName(iconName); return builder.build(); } private Task createTask(String description, int contextIndex, Project project, long start) { return createTask(description, null, contextIndex, project, start); } private Task createTask(String description, String details, int contextIndex, Project project, long start) { return createTask(description, details, contextIndex, project, start, start); } private int ORDER = 1; private Task createTask(String description, String details, int contextIndex, Project project, long start, long due) { Id contextId = contextIndex > -1 ? mPresetContexts[contextIndex].getLocalId() : Id.NONE; long created = System.currentTimeMillis(); String timezone = TimeZone.getDefault().getID(); Task.Builder builder = Task.newBuilder(); builder .setDescription(description) .setDetails(details) .setContextId(contextId) .setProjectId(project == null ? Id.NONE : project.getLocalId()) .setCreatedDate(created) .setModifiedDate(created) .setStartDate(start) .setDueDate(due) .setTimezone(timezone) .setActive(true) .setDeleted(false) .setOrder(ORDER++); return builder.build(); } private Project createProject(String name, Id defaultContextId) { Project.Builder builder = Project.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setDefaultContextId(defaultContextId) .setModifiedDate(System.currentTimeMillis()); return builder.build(); } private Context insertContext( org.dodgybits.shuffle.android.core.model.Context context) { Uri uri = mContextPersister.insert(context); long id = ContentUris.parseId(uri); Log.d(cTag, "Created context id=" + id + " uri=" + uri); Context.Builder builder = Context.newBuilder(); builder.mergeFrom(context); builder.setLocalId(Id.create(id)); context = builder.build(); return context; } private Project insertProject( Project project) { Uri uri = mProjectPersister.insert(project); long id = ContentUris.parseId(uri); Log.d(cTag, "Created project id=" + id + " uri=" + uri); Project.Builder builder = Project.newBuilder(); builder.mergeFrom(project); builder.setLocalId(Id.create(id)); project = builder.build(); return project; } private Task insertTask( Task task) { Uri uri = mTaskPersister.insert(task); long id = ContentUris.parseId(uri); Log.d(cTag, "Created task id=" + id); Task.Builder builder = Task.newBuilder(); builder.mergeFrom(task); builder.setLocalId(Id.create(id)); task = builder.build(); return task; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/InitialDataGenerator.java
Java
asf20
11,653
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCountParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCreateEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryDeleteEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryEntityTypeParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryUpdateEntityEvent; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public abstract class AbstractEntityPersister<E extends Entity> implements EntityPersister<E> { protected Analytics mAnalytics; protected ContentResolver mResolver; protected Map<String, String> mFlurryParams; public AbstractEntityPersister(ContentResolver resolver, Analytics analytics) { mResolver = resolver; mAnalytics = analytics; Map<String, String> params = new HashMap<String,String>(); params.put(cFlurryEntityTypeParam, getEntityName()); mFlurryParams = Collections.unmodifiableMap(params); } @Override public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { Cursor cursor = mResolver.query( getContentUri(), getFullProjection(), BaseColumns._ID + " = ?", new String[] {localId.toString()}, null); if (cursor.moveToFirst()) { entity = read(cursor); } cursor.close(); } return entity; } @Override public Uri insert(E e) { validate(e); Uri uri = mResolver.insert(getContentUri(), null); update(uri, e); mAnalytics.onEvent(cFlurryCreateEntityEvent, mFlurryParams); return uri; } @Override public void bulkInsert(Collection<E> entities) { int numEntities = entities.size(); if (numEntities > 0) { ContentValues[] valuesArray = new ContentValues[numEntities]; int i = 0; for(E entity : entities) { validate(entity); ContentValues values = new ContentValues(); writeContentValues(values, entity); valuesArray[i++] = values; } int rowsCreated = mResolver.bulkInsert(getContentUri(), valuesArray); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsCreated)); mAnalytics.onEvent(cFlurryCreateEntityEvent, params); } } @Override public void update(E e) { validate(e); Uri uri = getUri(e); update(uri, e); mAnalytics.onEvent(cFlurryUpdateEntityEvent, mFlurryParams); } @Override public boolean updateDeletedFlag(Id id, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return (mResolver.update(getUri(id), values, null, null) == 1); } @Override public int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return mResolver.update(getContentUri(), values, selection, selectionArgs); } @Override public int emptyTrash() { int rowsDeleted = mResolver.delete(getContentUri(), "deleted = 1", null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return rowsDeleted; } @Override public boolean deletePermanently(Id id) { Uri uri = getUri(id); boolean success = (mResolver.delete(uri, null, null) == 1); if (success) { mAnalytics.onEvent(cFlurryDeleteEntityEvent, mFlurryParams); } return success; } abstract public Uri getContentUri(); abstract protected void writeContentValues(ContentValues values, E e); abstract protected String getEntityName(); private void validate(E e) { if (e == null || !e.isValid()) { throw new IllegalArgumentException("Cannot persist uninitialised entity " + e); } } protected Uri getUri(E e) { return getUri(e.getLocalId()); } protected Uri getUri(Id localId) { return ContentUris.appendId( getContentUri().buildUpon(), localId.getId()).build(); } private void update(Uri uri, E e) { ContentValues values = new ContentValues(); writeContentValues(values, e); mResolver.update(uri, values, null, null); } protected static Id readId(Cursor cursor, int index) { Id result = Id.NONE; if (!cursor.isNull(index)) { result = Id.create(cursor.getLong(index)); } return result; } protected static String readString(Cursor cursor, int index) { return (cursor.isNull(index) ? null : cursor.getString(index)); } protected static long readLong(Cursor cursor, int index) { return readLong(cursor, index, 0L); } protected static long readLong(Cursor cursor, int index, long defaultValue) { long result = defaultValue; if (!cursor.isNull(index)) { result = cursor.getLong(index); } return result; } protected static Boolean readBoolean(Cursor cursor, int index) { return (cursor.getInt(index) == 1); } protected static void writeId(ContentValues values, String key, Id id) { if (id.isInitialised()) { values.put(key, id.getId()); } else { values.putNull(key); } } protected static void writeBoolean(ContentValues values, String key, boolean value) { values.put(key, value ? 1 : 0); } protected static void writeString(ContentValues values, String key, String value) { if (value == null) { values.putNull(key); } else { values.put(key, value); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/AbstractEntityPersister.java
Java
asf20
7,181
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.*; @ContextScoped public class ProjectPersister extends AbstractEntityPersister<Project> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int DEFAULT_CONTEXT_INDEX = 2; private static final int TRACKS_ID_INDEX = 3; private static final int MODIFIED_INDEX = 4; private static final int PARALLEL_INDEX = 5; private static final int ARCHIVED_INDEX = 6; private static final int DELETED_INDEX = 7; private static final int ACTIVE_INDEX = 8; @Inject public ProjectPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Project read(Cursor cursor) { Builder builder = Project.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setDefaultContextId(readId(cursor, DEFAULT_CONTEXT_INDEX)) .setParallel(readBoolean(cursor, PARALLEL_INDEX)) .setArchived(readBoolean(cursor, ARCHIVED_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Project project) { // never write id since it's auto generated values.put(MODIFIED_DATE, project.getModifiedDate()); writeId(values, TRACKS_ID, project.getTracksId()); writeString(values, NAME, project.getName()); writeId(values, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); writeBoolean(values, PARALLEL, project.isParallel()); writeBoolean(values, ARCHIVED, project.isArchived()); writeBoolean(values, DELETED, project.isDeleted()); writeBoolean(values, ACTIVE, project.isActive()); } @Override protected String getEntityName() { return "project"; } @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override public String[] getFullProjection() { return ProjectProvider.Projects.FULL_PROJECTION; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/ProjectPersister.java
Java
asf20
3,104
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.Time; import android.util.Log; import android.util.SparseIntArray; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import roboguice.util.Ln; import java.util.*; import static org.dodgybits.shuffle.android.core.util.Constants.*; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.DELETED; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.*; @ContextScoped public class TaskPersister extends AbstractEntityPersister<Task> { private static final String cTag = "TaskPersister"; private static final int ID_INDEX = 0; private static final int DESCRIPTION_INDEX = ID_INDEX + 1; private static final int DETAILS_INDEX = DESCRIPTION_INDEX + 1; private static final int PROJECT_INDEX = DETAILS_INDEX + 1; private static final int CONTEXT_INDEX = PROJECT_INDEX + 1; private static final int CREATED_INDEX = CONTEXT_INDEX + 1; private static final int MODIFIED_INDEX = CREATED_INDEX + 1; private static final int START_INDEX = MODIFIED_INDEX + 1; private static final int DUE_INDEX = START_INDEX + 1; private static final int TIMEZONE_INDEX = DUE_INDEX + 1; private static final int CAL_EVENT_INDEX = TIMEZONE_INDEX + 1; private static final int DISPLAY_ORDER_INDEX = CAL_EVENT_INDEX + 1; private static final int COMPLETE_INDEX = DISPLAY_ORDER_INDEX + 1; private static final int ALL_DAY_INDEX = COMPLETE_INDEX + 1; private static final int HAS_ALARM_INDEX = ALL_DAY_INDEX + 1; private static final int TASK_TRACK_INDEX = HAS_ALARM_INDEX + 1; private static final int DELETED_INDEX = TASK_TRACK_INDEX +1; private static final int ACTIVE_INDEX = DELETED_INDEX +1; @Inject public TaskPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Task read(Cursor cursor) { Builder builder = Task.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setDescription(readString(cursor, DESCRIPTION_INDEX)) .setDetails(readString(cursor, DETAILS_INDEX)) .setProjectId(readId(cursor, PROJECT_INDEX)) .setContextId(readId(cursor, CONTEXT_INDEX)) .setCreatedDate(readLong(cursor, CREATED_INDEX)) .setModifiedDate(readLong(cursor, MODIFIED_INDEX)) .setStartDate(readLong(cursor, START_INDEX)) .setDueDate(readLong(cursor, DUE_INDEX)) .setTimezone(readString(cursor, TIMEZONE_INDEX)) .setCalendarEventId(readId(cursor, CAL_EVENT_INDEX)) .setOrder(cursor.getInt(DISPLAY_ORDER_INDEX)) .setComplete(readBoolean(cursor, COMPLETE_INDEX)) .setAllDay(readBoolean(cursor, ALL_DAY_INDEX)) .setHasAlarm(readBoolean(cursor, HAS_ALARM_INDEX)) .setTracksId(readId(cursor, TASK_TRACK_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Task task) { // never write id since it's auto generated writeString(values, DESCRIPTION, task.getDescription()); writeString(values, DETAILS, task.getDetails()); writeId(values, PROJECT_ID, task.getProjectId()); writeId(values, CONTEXT_ID, task.getContextId()); values.put(CREATED_DATE, task.getCreatedDate()); values.put(MODIFIED_DATE, task.getModifiedDate()); values.put(START_DATE, task.getStartDate()); values.put(DUE_DATE, task.getDueDate()); writeBoolean(values, DELETED, task.isDeleted()); writeBoolean(values, ACTIVE, task.isActive()); String timezone = task.getTimezone(); if (TextUtils.isEmpty(timezone)) { if (task.isAllDay()) { timezone = Time.TIMEZONE_UTC; } else { timezone = TimeZone.getDefault().getID(); } } values.put(TIMEZONE, timezone); writeId(values, CAL_EVENT_ID, task.getCalendarEventId()); values.put(DISPLAY_ORDER, task.getOrder()); writeBoolean(values, COMPLETE, task.isComplete()); writeBoolean(values, ALL_DAY, task.isAllDay()); writeBoolean(values, HAS_ALARM, task.hasAlarms()); writeId(values, TRACKS_ID, task.getTracksId()); } @Override protected String getEntityName() { return "task"; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } @Override public String[] getFullProjection() { return TaskProvider.Tasks.FULL_PROJECTION; } @Override public int emptyTrash() { // find tasks that are deleted or who's context or project is deleted TaskSelector selector = TaskSelector.newBuilder().setDeleted(Flag.yes).build(); Cursor cursor = mResolver.query(getContentUri(), new String[] {BaseColumns._ID}, selector.getSelection(null), selector.getSelectionArgs(), selector.getSortOrder()); List<String> ids = new ArrayList<String>(); while (cursor.moveToNext()) { ids.add(cursor.getString(ID_INDEX)); } cursor.close(); int rowsDeleted = 0; if (ids.size() > 0) { Ln.i("About to delete tasks %s", ids); String queryString = "_id IN (" + StringUtils.join(ids, ",") + ")"; rowsDeleted = mResolver.delete(getContentUri(), queryString, null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); } return rowsDeleted; } public int deleteCompletedTasks() { int deletedRows = updateDeletedFlag(TaskProvider.Tasks.COMPLETE + " = 1", null, true); Log.d(cTag, "Deleting " + deletedRows + " completed tasks."); Map<String, String> params = new HashMap<String,String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(deletedRows)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return deletedRows; } public void updateCompleteFlag(Id id, boolean isComplete) { ContentValues values = new ContentValues(); writeBoolean(values, COMPLETE, isComplete); values.put(MODIFIED_DATE, System.currentTimeMillis()); mResolver.update(getUri(id), values, null, null); if (isComplete) { mAnalytics.onEvent(cFlurryCompleteTaskEvent); } } /** * Calculate where this task should appear on the list for the given project. * If no project is defined, order is meaningless, so return -1. * * New tasks go on the end of the list if no due date is defined. * If due date is defined, add either to the start, or after the task * closest to the end of the list with an earlier due date. * * For existing tasks, check if the project changed, and if so * treat like a new task, otherwise leave the order as is. * * @param originalTask the task before any changes or null if this is a new task * @param newProjectId the project selected for this task * @param dueMillis due date of this task (or 0L if not defined) * @return 0-indexed order of task when displayed in the project view */ public int calculateTaskOrder(Task originalTask, Id newProjectId, long dueMillis) { if (!newProjectId.isInitialised()) return -1; int order; if (originalTask == null || !originalTask.getProjectId().equals(newProjectId)) { // get current highest order value Cursor cursor = mResolver.query( TaskProvider.Tasks.CONTENT_URI, new String[] {BaseColumns._ID, TaskProvider.Tasks.DISPLAY_ORDER, TaskProvider.Tasks.DUE_DATE}, TaskProvider.Tasks.PROJECT_ID + " = ?", new String[] {String.valueOf(newProjectId.getId())}, TaskProvider.Tasks.DISPLAY_ORDER + " desc"); if (cursor.moveToFirst()) { if (dueMillis > 0L) { Ln.d("Due date defined - finding best place to insert in project task list"); Map<Long,Integer> updateValues = new HashMap<Long,Integer>(); do { long previousId = cursor.getLong(0); int previousOrder = cursor.getInt(1); long previousDueDate = cursor.getLong(2); if (previousDueDate > 0L && previousDueDate < dueMillis) { order = previousOrder + 1; Ln.d("Placing after task %d with earlier due date", previousId); break; } updateValues.put(previousId, previousOrder + 1); order = previousOrder; } while (cursor.moveToNext()); moveFollowingTasks(updateValues); } else { // no due date so put at end of list int highestOrder = cursor.getInt(1); order = highestOrder + 1; } } else { // no tasks in the project yet. order = 0; } cursor.close(); } else { order = originalTask.getOrder(); } return order; } private void moveFollowingTasks(Map<Long,Integer> updateValues) { Set<Long> ids = updateValues.keySet(); ContentValues values = new ContentValues(); for (long id : ids) { values.clear(); values.put(DISPLAY_ORDER, updateValues.get(id)); Uri uri = ContentUris.withAppendedId(TaskProvider.Tasks.CONTENT_URI, id); mResolver.update(uri, values, null, null); } } /** * Swap the display order of two tasks at the given cursor positions. * The cursor is committed and re-queried after the update. */ public void swapTaskPositions(Cursor cursor, int pos1, int pos2) { cursor.moveToPosition(pos1); Id id1 = readId(cursor, ID_INDEX); int positionValue1 = cursor.getInt(DISPLAY_ORDER_INDEX); cursor.moveToPosition(pos2); Id id2 = readId(cursor, ID_INDEX); int positionValue2 = cursor.getInt(DISPLAY_ORDER_INDEX); Uri uri = ContentUris.withAppendedId(getContentUri(), id1.getId()); ContentValues values = new ContentValues(); values.put(DISPLAY_ORDER, positionValue2); mResolver.update(uri, values, null, null); uri = ContentUris.withAppendedId(getContentUri(), id2.getId()); values.clear(); values.put(DISPLAY_ORDER, positionValue1); mResolver.update(uri, values, null, null); mAnalytics.onEvent(cFlurryReorderTasksEvent); } private static final int TASK_COUNT_INDEX = 1; public SparseIntArray readCountArray(Cursor cursor) { SparseIntArray countMap = new SparseIntArray(); while (cursor.moveToNext()) { Integer id = cursor.getInt(ID_INDEX); Integer count = cursor.getInt(TASK_COUNT_INDEX); countMap.put(id, count); } return countMap; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/TaskPersister.java
Java
asf20
12,683
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.ItemCache; import org.dodgybits.shuffle.android.core.util.ItemCache.ValueBuilder; import roboguice.inject.ContextScoped; import android.util.Log; import com.google.inject.Inject; @ContextScoped public class DefaultEntityCache<E extends Entity> implements EntityCache<E> { private static final String cTag = "DefaultEntityCache"; private EntityPersister<E> mPersister; private Builder mBuilder; private ItemCache<Id, E> mCache; @Inject public DefaultEntityCache(EntityPersister<E> persister) { Log.d(cTag, "Created entity cache with " + persister); mPersister = persister; mBuilder = new Builder(); mCache = new ItemCache<Id, E>(mBuilder); } public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { entity = mCache.get(localId); } return entity; } private class Builder implements ValueBuilder<Id, E> { @Override public E build(Id key) { return mPersister.findById(key); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/DefaultEntityCache.java
Java
asf20
1,312
package org.dodgybits.shuffle.android.core.model.persistence; import java.util.Collection; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import android.database.Cursor; import android.net.Uri; public interface EntityPersister<E extends Entity> { Uri getContentUri(); String[] getFullProjection(); E findById(Id localId); E read(Cursor cursor); Uri insert(E e); void bulkInsert(Collection<E> entities); void update(E e); /** * Set deleted flag entity with the given id to isDeleted. * * @param id entity id * @param isDeleted flag to set deleted flag to * @return whether the operation succeeded */ boolean updateDeletedFlag(Id id, boolean isDeleted); /** * Set deleted flag for entities that match the criteria to isDeleted. * * @param selection where clause * @param selectionArgs parameter values from where clause * @param isDeleted flag to set deleted flag to * @return number of entities updates */ int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted); /** * Permanently delete all items that currently flagged as deleted. * * @return number of entities removed */ int emptyTrash(); /** * Permanently delete entity with the given id. * * @return whether the operation succeeded */ boolean deletePermanently(Id id); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/EntityPersister.java
Java
asf20
1,525
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; public interface EntityCache<E extends Entity> { E findById(Id localId); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/EntityCache.java
Java
asf20
249
package org.dodgybits.shuffle.android.core.model.persistence.selector; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.no; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.yes; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.net.Uri; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.text.format.DateUtils; import android.util.Log; public class TaskSelector extends AbstractEntitySelector { private static final String cTag = "TaskSelector"; private static final String[] cUndefinedArgs = new String[] {}; private PredefinedQuery mPredefined; private List<Id> mProjects; private List<Id> mContexts; private Flag mComplete = ignored; private Flag mPending = ignored; private String mSelection = null; private String[] mSelectionArgs = cUndefinedArgs; private TaskSelector() { } public final PredefinedQuery getPredefinedQuery() { return mPredefined; } public final List<Id> getProjects() { return mProjects; } public final List<Id> getContexts() { return mContexts; } public final Flag getComplete() { return mComplete; } public final Flag getPending() { return mPending; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } public final String getSelection(android.content.Context context) { if (mSelection == null) { List<String> expressions = getSelectionExpressions(context); mSelection = StringUtils.join(expressions, " AND "); Log.d(cTag, mSelection); } return mSelection; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); if (mPredefined != null) { expressions.add(predefinedSelection(context)); } addActiveExpression(expressions); addDeletedExpression(expressions); addPendingExpression(expressions); addListExpression(expressions, TaskProvider.Tasks.PROJECT_ID, mProjects); addListExpression(expressions, TaskProvider.Tasks.CONTEXT_ID, mContexts); addFlagExpression(expressions, TaskProvider.Tasks.COMPLETE, mComplete); return expressions; } private void addActiveExpression(List<String> expressions) { if (mActive == yes) { // A task is active if it is active and both project and context are active. String expression = "(task.active = 1 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.active = 1)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.active = 1)) " + ")"; expressions.add(expression); } else if (mActive == no) { // task is inactive if it is inactive or project in active or context is inactive String expression = "(task.active = 0 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.active = 0)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.active = 0)) " + ")"; expressions.add(expression); } } private void addDeletedExpression(List<String> expressions) { if (mDeleted == yes) { // task is deleted if it is deleted or project is deleted or context is deleted String expression = "(task.deleted = 1 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.deleted = 1)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.deleted = 1)) " + ")"; expressions.add(expression); } else if (mDeleted == no) { // task is not deleted if it is not deleted and project is not deleted and context is not deleted String expression = "(task.deleted = 0 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.deleted = 0)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.deleted = 0)) " + ")"; expressions.add(expression); } } private void addPendingExpression(List<String> expressions) { long now = System.currentTimeMillis(); if (mPending == yes) { String expression = "(start > " + now + ")"; expressions.add(expression); } else if (mPending == no) { String expression = "(start <= " + now + ")"; expressions.add(expression); } } private String predefinedSelection(android.content.Context context) { String result; long now = System.currentTimeMillis(); switch (mPredefined) { case nextTasks: result = "((complete = 0) AND " + " (start < " + now + ") AND " + " ((projectId is null) OR " + " (projectId IN (select p._id from project p where p.parallel = 1)) OR " + " (task._id = (select t2._id FROM task t2 WHERE " + " t2.projectId = task.projectId AND t2.complete = 0 AND " + " t2.deleted = 0 " + " ORDER BY displayOrder ASC limit 1))" + "))"; break; case inbox: long lastCleanMS = Preferences.getLastInboxClean(context); result = "((projectId is null AND contextId is null) OR (created > " + lastCleanMS + "))"; break; case tickler: // by default show all results (completely customizable) result = "(1 == 1)"; break; case dueToday: case dueNextWeek: case dueNextMonth: long startMS = 0L; long endOfToday = getEndDate(); long endOfTomorrow = endOfToday + DateUtils.DAY_IN_MILLIS; result = "(due > " + startMS + ")" + " AND ( (due < " + endOfToday + ") OR" + "( allDay = 1 AND due < " + endOfTomorrow + " ))"; break; default: throw new RuntimeException("Unknown predefined selection " + mPredefined); } return result; } private long getEndDate() { long endMS = 0L; Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); switch (mPredefined) { case dueToday: cal.add(Calendar.DAY_OF_YEAR, 1); endMS = cal.getTimeInMillis(); break; case dueNextWeek: cal.add(Calendar.DAY_OF_YEAR, 7); endMS = cal.getTimeInMillis(); break; case dueNextMonth: cal.add(Calendar.MONTH, 1); endMS = cal.getTimeInMillis(); break; } if (Log.isLoggable(cTag, Log.INFO)) { Log.i(cTag, "Due date ends " + endMS); } return endMS; } public final String[] getSelectionArgs() { if (mSelectionArgs == cUndefinedArgs) { List<String> args = new ArrayList<String>(); addIdListArgs(args, mProjects); addIdListArgs(args, mContexts); Log.d(cTag,args.toString()); mSelectionArgs = args.size() > 0 ? args.toArray(new String[0]): null; } return mSelectionArgs; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[TaskSelector predefined=%1$s projects=%2$s contexts='%3$s' " + "complete=%4$s sortOrder=%5$s active=%6$s deleted=%7$s pending=%8$s]", mPredefined, mProjects, mContexts, mComplete, mSortOrder, mActive, mDeleted, mPending); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<TaskSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new TaskSelector(); return builder; } public PredefinedQuery getPredefined() { return mResult.mPredefined; } public Builder setPredefined(PredefinedQuery value) { mResult.mPredefined = value; return this; } public List<Id> getProjects() { return mResult.mProjects; } public Builder setProjects(List<Id> value) { mResult.mProjects = value; return this; } public List<Id> getContexts() { return mResult.mContexts; } public Builder setContexts(List<Id> value) { mResult.mContexts = value; return this; } public Flag getComplete() { return mResult.mComplete; } public Builder setComplete(Flag value) { mResult.mComplete = value; return this; } public Flag getPending() { return mResult.mPending; } public Builder setPending(Flag value) { mResult.mPending = value; return this; } public Builder mergeFrom(TaskSelector query) { super.mergeFrom(query); setPredefined(query.mPredefined); setProjects(query.mProjects); setContexts(query.mContexts); setComplete(query.mComplete); setPending(query.mPending); return this; } public Builder applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { super.applyListPreferences(context, settings); setComplete(settings.getCompleted(context)); setPending(settings.getPending(context)); return this; } } public enum PredefinedQuery { nextTasks, dueToday, dueNextWeek, dueNextMonth, inbox, tickler } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/TaskSelector.java
Java
asf20
11,202
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.util.Log; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import java.util.ArrayList; import java.util.List; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; public abstract class AbstractEntitySelector implements EntitySelector { private static final String cTag = "AbstractEntitySelector"; protected Flag mActive = ignored; protected Flag mDeleted = ignored; protected String mSortOrder; @Override public Flag getActive() { return mActive; } @Override public Flag getDeleted() { return mDeleted; } @Override public final String getSortOrder() { return mSortOrder; } @Override public String getSelection(android.content.Context context) { List<String> expressions = getSelectionExpressions(context); String selection = StringUtils.join(expressions, " AND "); Log.d(cTag, selection); return selection; } protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = new ArrayList<String>(); return expressions; } protected void addFlagExpression(List<String> expressions, String field, Flag flag) { if (flag != Flag.ignored) { String expression = field + "=" + (flag == Flag.yes ? "1" : "0"); expressions.add(expression); } } protected void addListExpression(List<String> expressions, String field, List<Id> ids) { if (ids != null) { expressions.add(idListSelection(ids, field)); } } private String idListSelection(List<Id> ids, String idName) { StringBuilder result = new StringBuilder(); if (ids.size() > 0) { result.append(idName) .append(" in (") .append(StringUtils.repeat(ids.size(), "?", ",")) .append(')'); } else { result.append(idName) .append(" is null"); } return result.toString(); } protected void addIdListArgs(List<String> args, List<Id> ids) { if (ids != null && ids.size() > 0) { for(Id id : ids) { args.add(String.valueOf(id.getId())); } } } public abstract static class AbstractBuilder<E extends AbstractEntitySelector> implements EntitySelector.Builder<E> { protected E mResult; @Override public Flag getDeleted() { return mResult.getDeleted(); } @Override public Flag getActive() { return mResult.getActive(); } @Override public String getSortOrder() { return mResult.getSortOrder(); } @Override public AbstractBuilder<E> setSortOrder(String value) { mResult.mSortOrder = value; return this; } @Override public AbstractBuilder<E> setActive(Flag value) { mResult.mActive = value; return this; } @Override public AbstractBuilder<E> setDeleted(Flag value) { mResult.mDeleted = value; return this; } @Override public E build() { if (mResult == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } E returnMe = mResult; mResult = null; Log.d(cTag,returnMe.toString()); return returnMe; } @Override public AbstractBuilder<E> mergeFrom(E selector) { setActive(selector.mActive); setDeleted(selector.mDeleted); setSortOrder(selector.mSortOrder); return this; } @Override public AbstractBuilder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { setActive(settings.getActive(context)); setDeleted(settings.getDeleted(context)); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/AbstractEntitySelector.java
Java
asf20
4,440
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import java.util.List; public class ContextSelector extends AbstractEntitySelector { private static final String cTag = "ContextSelector"; private ContextSelector() { } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public final String toString() { return String.format( "[ContextSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ContextSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ContextSelector(); return builder; } public Builder mergeFrom(ContextSelector query) { super.mergeFrom(query); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/ContextSelector.java
Java
asf20
1,861
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import java.util.List; public class ProjectSelector extends AbstractEntitySelector { private static final String cTag = "ProjectSelector"; private ProjectSelector() { } @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[ProjectSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ProjectSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ProjectSelector(); return builder; } public Builder mergeFrom(ProjectSelector query) { super.mergeFrom(query); return this; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/ProjectSelector.java
Java
asf20
1,860
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.content.Context; import android.net.Uri; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; public interface EntitySelector<E extends EntitySelector> { Uri getContentUri(); Flag getActive(); Flag getDeleted(); String getSelection(Context context); String[] getSelectionArgs(); String getSortOrder(); Builder<E> builderFrom(); public interface Builder<E extends EntitySelector> { Flag getActive(); Builder<E> setActive(Flag value); Flag getDeleted(); Builder<E> setDeleted(Flag value); String getSortOrder(); Builder<E> setSortOrder(String value); E build(); Builder<E> mergeFrom(E selector); Builder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/EntitySelector.java
Java
asf20
960
package org.dodgybits.shuffle.android.core.model.persistence.selector; public enum Flag { yes, no, ignored }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/selector/Flag.java
Java
asf20
114
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.*; @ContextScoped public class ContextPersister extends AbstractEntityPersister<Context> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int COLOUR_INDEX = 2; private static final int ICON_INDEX = 3; private static final int TRACKS_ID_INDEX = 4; private static final int MODIFIED_INDEX = 5; private static final int DELETED_INDEX = 6; private static final int ACTIVE_INDEX = 7; @Inject public ContextPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Context read(Cursor cursor) { Builder builder = Context.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setColourIndex(cursor.getInt(COLOUR_INDEX)) .setIconName(readString(cursor, ICON_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Context context) { // never write id since it's auto generated values.put(MODIFIED_DATE, context.getModifiedDate()); writeId(values, TRACKS_ID, context.getTracksId()); writeString(values, NAME, context.getName()); values.put(COLOUR, context.getColourIndex()); writeString(values, ICON, context.getIconName()); writeBoolean(values, DELETED, context.isDeleted()); writeBoolean(values, ACTIVE, context.isActive()); } @Override protected String getEntityName() { return "context"; } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override public String[] getFullProjection() { return ContextProvider.Contexts.FULL_PROJECTION; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/persistence/ContextPersister.java
Java
asf20
2,757
package org.dodgybits.shuffle.android.core.model; public interface Entity { /** * @return primary key for entity in local sqlite DB. 0L indicates an unsaved entity. */ Id getLocalId(); /** * @return ms since epoch entity was last modified. */ long getModifiedDate(); boolean isActive(); boolean isDeleted(); boolean isValid(); String getLocalName(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/Entity.java
Java
asf20
433
package org.dodgybits.shuffle.android.core.model; public interface EntityBuilder<E> { EntityBuilder<E> mergeFrom(E e); EntityBuilder<E> setLocalId(Id id); EntityBuilder<E> setModifiedDate(long ms); EntityBuilder<E> setTracksId(Id id); EntityBuilder<E> setActive(boolean value); EntityBuilder<E> setDeleted(boolean value); E build(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/model/EntityBuilder.java
Java
asf20
370
package org.dodgybits.shuffle.android.core.view; import android.content.res.Resources; import android.text.TextUtils; public class ContextIcon { private static final String cPackage = "org.dodgybits.android.shuffle"; private static final String cType = "drawable"; public static final ContextIcon NONE = new ContextIcon(null, 0, 0); public final String iconName; public final int largeIconId; public final int smallIconId; private ContextIcon(String iconName, int largeIconId, int smallIconId) { this.iconName = iconName; this.largeIconId = largeIconId; this.smallIconId = smallIconId; } public static ContextIcon createIcon(String iconName, Resources res) { if (TextUtils.isEmpty(iconName)) return NONE; int largeId = res.getIdentifier(iconName, cType, cPackage); int smallId = res.getIdentifier(iconName + "_small", cType, cPackage); return new ContextIcon(iconName, largeId, smallId); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/view/ContextIcon.java
Java
asf20
1,012
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.util.Log; public class AlertUtils { private static final String cTag = "AlertUtils"; private AlertUtils() { //deny } public static void showDeleteGroupWarning(final Context context, final String groupName, final String childName, final int childCount, final OnClickListener buttonListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.delete_warning, groupName.toLowerCase(), childCount, childName.toLowerCase()); CharSequence deleteButtonText = context.getString(R.string.menu_delete); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); OnCancelListener cancelListener = new OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d(cTag, "Cancelled delete. Do nothing."); } }; Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(deleteButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } public static void showCleanUpInboxMessage(final Context context) { CharSequence title = context.getString(R.string.info_title); CharSequence message = context.getString(R.string.clean_inbox_message); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_information) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showWarning(final Context context, final String message) { CharSequence title = context.getString(R.string.warning_title); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showFileExistsWarning(final Context context, final String filename, final OnClickListener buttonListener, final OnCancelListener cancelListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.warning_filename_exists, filename); CharSequence replaceButtonText = context.getString(R.string.replace_button_title); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(replaceButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/view/AlertUtils.java
Java
asf20
3,820
package org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class IconArrayAdapter extends ArrayAdapter<CharSequence> { private Integer[] mIconIds; public IconArrayAdapter( Context context, int resource, int textViewResourceId, CharSequence[] objects, Integer[] iconIds) { super(context, resource, textViewResourceId, objects); mIconIds = iconIds; } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView nameView = (TextView) view.findViewById(R.id.name); // don't use toString in order to preserve colour change nameView.setText(getItem(position)); Integer iconId = null; if (position < mIconIds.length) { iconId = mIconIds[position]; if (iconId != null) { nameView.setCompoundDrawablesWithIntrinsicBounds( getContext().getResources().getDrawable(iconId), null, null, null); } } return view; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/view/IconArrayAdapter.java
Java
asf20
1,214
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.view; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; public class DrawableUtils { private DrawableUtils() { //deny } public static GradientDrawable createGradient(int colour, Orientation orientation) { return createGradient(colour, orientation, 1.1f, 0.9f); } public static GradientDrawable createGradient(int colour, Orientation orientation, float startOffset, float endOffset) { int[] colours = new int[2]; float[] hsv1 = new float[3]; float[] hsv2 = new float[3]; Color.colorToHSV(colour, hsv1); Color.colorToHSV(colour, hsv2); hsv1[2] *= startOffset; hsv2[2] *= endOffset; colours[0] = Color.HSVToColor(hsv1); colours[1] = Color.HSVToColor(hsv2); return new GradientDrawable(orientation, colours); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/view/DrawableUtils.java
Java
asf20
1,533
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.view; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.HelpActivity; import org.dodgybits.shuffle.android.list.activity.ContextsActivity; import org.dodgybits.shuffle.android.list.activity.ProjectsActivity; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableContextsActivity; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableProjectsActivity; import org.dodgybits.shuffle.android.list.activity.task.*; import org.dodgybits.shuffle.android.preference.activity.PreferencesActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity; public class MenuUtils { private static final String cTag = "MenuUtils"; private MenuUtils() { // deny } // Identifiers for our menu items. public static final int SAVE_ID = Menu.FIRST; public static final int SAVE_AND_ADD_ID = Menu.FIRST + 1; public static final int REVERT_ID = Menu.FIRST + 2; public static final int DISCARD_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int INSERT_ID = Menu.FIRST + 5; public static final int INSERT_CHILD_ID = Menu.FIRST + 6; public static final int INSERT_GROUP_ID = Menu.FIRST + 7; public static final int INBOX_ID = Menu.FIRST + 10; public static final int CALENDAR_ID = Menu.FIRST + 11; public static final int TOP_TASKS_ID = Menu.FIRST + 12; public static final int PROJECT_ID = Menu.FIRST + 13; public static final int CONTEXT_ID = Menu.FIRST + 14; public static final int TICKLER_ID = Menu.FIRST + 15; public static final int PREFERENCE_ID = Menu.FIRST + 20; public static final int HELP_ID = Menu.FIRST + 21; public static final int SYNC_ID = Menu.FIRST + 22; public static final int SEARCH_ID = Menu.FIRST + 23; public static final int CLEAN_INBOX_ID = Menu.FIRST + 50; public static final int PERMANENTLY_DELETE_ID = Menu.FIRST + 51; // Menu item for activity specific items public static final int PUT_BACK_ID = Menu.FIRST + 100; public static final int COMPLETE_ID = Menu.FIRST + 101; public static final int MOVE_UP_ID = Menu.FIRST + 102; public static final int MOVE_DOWN_ID = Menu.FIRST + 103; // Editor menus private static final int SAVE_ORDER = 1; private static final int SAVE_AND_ADD_ORDER = 2; private static final int REVERT_ORDER = 3; private static final int DISCARD_ORDER = 3; // Context menus private static final int EDIT_ORDER = 1; private static final int PUT_BACK_ORDER = 3; private static final int COMPLETE_ORDER = 4; private static final int MOVE_UP_ORDER = 5; private static final int MOVE_DOWN_ORDER = 6; private static final int DELETE_ORDER = 10; // List menus private static final int INSERT_ORDER = 1; private static final int INSERT_CHILD_ORDER = 1; private static final int INSERT_GROUP_ORDER = 2; private static final int CLEAN_INBOX_ORDER = 101; private static final int PERMANENTLY_DELETE_ORDER = 102; // General menus private static final int PERSPECTIVE_ORDER = 201; private static final int PREFERENCE_ORDER = 202; private static final int SYNCH_ORDER = 203; private static final int SEARCH_ORDER = 204; private static final int HELP_ORDER = 205; public static void addInsertMenuItems(Menu menu, String itemName, boolean isTaskList, Context context) { String menuName = context.getResources().getString(R.string.menu_insert, itemName); menu.add(Menu.NONE, INSERT_ID, INSERT_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add) .setAlphabeticShortcut(isTaskList ? 'c' : 'a'); } public static void addExpandableInsertMenuItems(Menu menu, String groupName, String childName, Context context) { String menuName; menuName = context.getResources().getString(R.string.menu_insert, childName); menu.add(Menu.NONE, INSERT_CHILD_ID, INSERT_CHILD_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('c'); menuName = context.getResources().getString(R.string.menu_insert, groupName); menu.add(Menu.NONE, INSERT_GROUP_ID, INSERT_GROUP_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a'); } public static void addViewMenuItems(Menu menu, int currentViewMenuId) { SubMenu viewMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, PERSPECTIVE_ORDER, R.string.menu_view) .setIcon(R.drawable.preferences_system_windows); viewMenu.add(Menu.NONE, INBOX_ID, 0, R.string.title_inbox) .setChecked(INBOX_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CALENDAR_ID, 1, R.string.title_due_tasks) .setChecked(CALENDAR_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TOP_TASKS_ID, 2, R.string.title_next_tasks) .setChecked(TOP_TASKS_ID == currentViewMenuId); viewMenu.add(Menu.NONE, PROJECT_ID, 3, R.string.title_project) .setChecked(PROJECT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CONTEXT_ID, 4, R.string.title_context) .setChecked(CONTEXT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TICKLER_ID, 5, R.string.title_tickler) .setChecked(TICKLER_ID == currentViewMenuId); } public static void addEditorMenuItems(Menu menu, int state) { menu.add(Menu.NONE, SAVE_ID, SAVE_ORDER, R.string.menu_save) .setIcon(android.R.drawable.ic_menu_save).setAlphabeticShortcut('s'); menu.add(Menu.NONE, SAVE_AND_ADD_ID, SAVE_AND_ADD_ORDER, R.string.menu_save_and_add) .setIcon(android.R.drawable.ic_menu_save); // Build the menus that are shown when editing. if (state == State.STATE_EDIT) { menu.add(Menu.NONE, REVERT_ID, REVERT_ORDER, R.string.menu_revert) .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r'); menu.add(Menu.NONE, DELETE_ID, DELETE_ORDER, R.string.menu_delete) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); // Build the menus that are shown when inserting. } else { menu.add(Menu.NONE, DISCARD_ID, DISCARD_ORDER, R.string.menu_discard) .setIcon(android.R.drawable.ic_menu_close_clear_cancel).setAlphabeticShortcut('d'); } } public static void addPrefsHelpMenuItems(Context context, Menu menu) { menu.add(Menu.NONE, PREFERENCE_ID, PREFERENCE_ORDER, R.string.menu_preferences) .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('p'); menu.add(Menu.NONE, HELP_ID, HELP_ORDER, R.string.menu_help) .setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('h'); } public static void addSyncMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SYNC_ID, SYNCH_ORDER, R.string.menu_sync) .setIcon(android.R.drawable.ic_menu_rotate).setVisible(Preferences.validateTracksSettings(context)); } public static void addSearchMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SEARCH_ID, SEARCH_ORDER, R.string.menu_search) .setIcon(android.R.drawable.ic_menu_search).setAlphabeticShortcut('s'); } public static void addSelectedAlternativeMenuItems(Menu menu, Uri uri, boolean includeView) { // Build menu... always starts with the EDIT action... int viewIndex = 0; int editIndex = (includeView ? 1 : 0); Intent[] specifics = new Intent[editIndex + 1]; MenuItem[] items = new MenuItem[editIndex + 1]; if (includeView) { specifics[viewIndex] = new Intent(Intent.ACTION_VIEW, uri); } specifics[editIndex] = new Intent(Intent.ACTION_EDIT, uri); // ... is followed by whatever other actions are available... Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, Menu.NONE, EDIT_ORDER, null, specifics, intent, 0, items); // Give a shortcut to the edit action. if (items[editIndex] != null) { items[editIndex].setAlphabeticShortcut('e'); items[editIndex].setIcon(android.R.drawable.ic_menu_edit); } if (includeView && items[viewIndex] != null) { items[viewIndex].setAlphabeticShortcut('v'); items[viewIndex].setIcon(android.R.drawable.ic_menu_view); } } public static void addPutBackMenuItem(Menu menu) { menu.add(Menu.CATEGORY_ALTERNATIVE, PUT_BACK_ID, PUT_BACK_ORDER, R.string.menu_put_back); } public static void addCompleteMenuItem(Menu menu, boolean isComplete) { int labelId = isComplete ? R.string.menu_incomplete : R.string.menu_complete; menu.add(Menu.CATEGORY_ALTERNATIVE, COMPLETE_ID, COMPLETE_ORDER, labelId) .setIcon(R.drawable.btn_check_on).setAlphabeticShortcut('x'); } public static void addDeleteMenuItem(Menu menu, boolean isDeleted) { int labelId = isDeleted ? R.string.menu_undelete : R.string.menu_delete; menu.add(Menu.CATEGORY_ALTERNATIVE, DELETE_ID, DELETE_ORDER, labelId) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); } public static void addCleanInboxMenuItem(Menu menu) { menu.add(Menu.NONE, CLEAN_INBOX_ID, CLEAN_INBOX_ORDER, R.string.clean_inbox_button_title) .setIcon(R.drawable.edit_clear).setAlphabeticShortcut('i'); } public static void addPermanentlyDeleteMenuItem(Menu menu) { menu.add(Menu.NONE, PERMANENTLY_DELETE_ID, PERMANENTLY_DELETE_ORDER, R.string.permanently_delete_button_title) .setIcon(R.drawable.icon_delete); } public static void addMoveMenuItems(Menu menu, boolean enableUp, boolean enableDown) { if (enableUp) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_UP_ID, MOVE_UP_ORDER, R.string.menu_move_up) .setIcon(R.drawable.go_up).setAlphabeticShortcut('k'); } if (enableDown) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_DOWN_ID, MOVE_DOWN_ORDER, R.string.menu_move_down) .setIcon(R.drawable.go_down).setAlphabeticShortcut('j'); } } public static boolean checkCommonItemsSelected(MenuItem item, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(item.getItemId(), activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(menuItemId, activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId, boolean finishCurrentActivity) { switch (menuItemId) { case MenuUtils.INBOX_ID: if (currentViewMenuId != INBOX_ID) { Log.d(cTag, "Switching to inbox"); activity.startActivity(new Intent(activity, InboxActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.CALENDAR_ID: if (currentViewMenuId != CALENDAR_ID) { Log.d(cTag, "Switching to calendar"); activity.startActivity(new Intent(activity, TabbedDueActionsActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.TOP_TASKS_ID: if (currentViewMenuId != TOP_TASKS_ID) { Log.d(cTag, "Switching to top tasks"); activity.startActivity(new Intent(activity, TopTasksActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.PROJECT_ID: if (currentViewMenuId != PROJECT_ID) { Log.d(cTag, "Switching to project list"); Class<? extends Activity> activityClass = null; if (Preferences.isProjectViewExpandable(activity)) { activityClass = ExpandableProjectsActivity.class; } else { activityClass = ProjectsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case CONTEXT_ID: if (currentViewMenuId != CONTEXT_ID) { Log.d(cTag, "Switching to context list"); Class<? extends Activity> activityClass = null; if (Preferences.isContextViewExpandable(activity)) { activityClass = ExpandableContextsActivity.class; } else { activityClass = ContextsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case TICKLER_ID: Log.d(cTag, "Switching to tickler list"); activity.startActivity(new Intent(activity, TicklerActivity.class)); return true; case PREFERENCE_ID: Log.d(cTag, "Bringing up preferences"); activity.startActivity(new Intent(activity, PreferencesActivity.class)); return true; case HELP_ID: Log.d(cTag, "Bringing up help"); Intent intent = new Intent(activity, HelpActivity.class); intent.putExtra(HelpActivity.cHelpPage, getHelpScreen(currentViewMenuId)); activity.startActivity(intent); return true; case SYNC_ID: Log.d(cTag, "starting sync"); activity.startActivity(new Intent(activity, SynchronizeActivity.class)); return true; case SEARCH_ID: Log.d(cTag, "starting search"); activity.onSearchRequested(); return true; } return false; } private static int getHelpScreen(int currentViewMenuId) { int result = 0; switch (currentViewMenuId) { case INBOX_ID: result = 1; break; case PROJECT_ID: result = 2; break; case CONTEXT_ID: result = 3; break; case TOP_TASKS_ID: result = 4; break; case CALENDAR_ID: result = 5; break; } return result; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/view/MenuUtils.java
Java
asf20
15,259
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.util; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.graphics.Color; import android.util.Log; public class TextColours { private static final String cTag = "TextColours"; private static TextColours instance = null; private int[] textColours; private int[] bgColours; public static TextColours getInstance(Context context) { if (instance == null) { instance = new TextColours(context); } return instance; } private TextColours(Context context) { Log.d(cTag, "Fetching colours"); String[] colourStrings = context.getResources().getStringArray(R.array.text_colours); Log.d(cTag, "Fetched colours"); textColours = parseColourString(colourStrings); colourStrings = context.getResources().getStringArray(R.array.background_colours); bgColours = parseColourString(colourStrings); } private int[] parseColourString(String[] colourStrings) { int[] colours = new int[colourStrings.length]; for (int i = 0; i < colourStrings.length; i++) { String colourString = '#' + colourStrings[i].substring(1); Log.d(cTag, "Parsing " + colourString); colours[i] = Color.parseColor(colourString); } return colours; } public int getNumColours() { return textColours.length; } public int getTextColour(int position) { return textColours[position]; } public int getBackgroundColour(int position) { return bgColours[position]; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/TextColours.java
Java
asf20
2,088
package org.dodgybits.shuffle.android.core.util; import java.util.List; public class StringUtils { public static String repeat(int count, String token) { return repeat(count, token, ""); } public static String repeat(int count, String token, String delim) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= count; i++) { builder.append(token); if (i < count) { builder.append(delim); } } return builder.toString(); } public static String join(List<String> items, String delim) { StringBuilder result = new StringBuilder(); final int len = items.size(); for(int i = 0; i < len; i++) { result.append(items.get(i)); if (i < len - 1) { result.append(delim); } } return result.toString(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/StringUtils.java
Java
asf20
839
package org.dodgybits.shuffle.android.core.util; import java.lang.ref.SoftReference; import java.util.HashMap; import android.util.Log; /** * Generic in-memory cache based on Romain Guy's suggestion. * See http://code.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html */ public class ItemCache<K,V> { private static final String cTag = "ItemCache"; private final HashMap<K, SoftReference<V>> mCache; private final ValueBuilder<K,V> mBuilder; public ItemCache(ValueBuilder<K,V> builder) { mCache = new HashMap<K, SoftReference<V>>(); mBuilder = builder; } public void put(K key, V value) { mCache.put(key, new SoftReference<V>(value)); } public V get(K key) { V value = null; SoftReference<V> reference = mCache.get(key); if (reference != null) { value = reference.get(); } // not in cache or gc'd if (value == null) { Log.d(cTag, "Cache miss for " + key); value = mBuilder.build(key); put(key, value); } return value; } public void remove(K key) { mCache.remove(key); } public void clear() { mCache.clear(); } public interface ValueBuilder<K,V> { V build(K key); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/ItemCache.java
Java
asf20
1,382
package org.dodgybits.shuffle.android.core.util; public final class Constants { private Constants() { //deny } public static final String cPackage = "org.dodgybits.android.shuffle"; public static final int cVersion = 29; public static final String cFlurryApiKey = "T7KF1PCGVU6V2FS8LILF"; public static final String cFlurryCreateEntityEvent = "createEntity"; public static final String cFlurryUpdateEntityEvent = "updateEntity"; public static final String cFlurryDeleteEntityEvent = "deleteEntity"; public static final String cFlurryReorderTasksEvent = "reorderTasks"; public static final String cFlurryCompleteTaskEvent = "completeTask"; public static final String cFlurryTracksSyncStartedEvent = "tracsSyncStarted"; public static final String cFlurryTracksSyncCompletedEvent = "tracsSyncCompleted"; public static final String cFlurryTracksSyncError = "tracksSyncError"; public static final String cFlurryCountParam = "count"; public static final String cFlurryEntityTypeParam = "entityType"; public static final String cFlurryCalendarUpdateError = "calendarUpdateError"; public static final String cIdType = "id"; public static final String cStringType = "string"; }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/Constants.java
Java
asf20
1,292
package org.dodgybits.shuffle.android.core.util; import java.lang.reflect.Field; import android.os.Build; public class OSUtils { public static boolean osAtLeastFroyo() { boolean isFroyoOrAbove = false; try { Field field = Build.VERSION.class.getDeclaredField("SDK_INT"); int version = field.getInt(null); isFroyoOrAbove = version >= Build.VERSION_CODES.FROYO; } catch (Exception e) { // ignore exception - field not available } return isFroyoOrAbove; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/OSUtils.java
Java
asf20
565
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.core.util; import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH; import static android.text.format.DateUtils.FORMAT_ABBREV_TIME; import static android.text.format.DateUtils.FORMAT_SHOW_DATE; import static android.text.format.DateUtils.FORMAT_SHOW_TIME; import java.lang.ref.SoftReference; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.text.format.Time; public class DateUtils { /** * Lazily create date format objects, one per thread. Use soft references so format * may be collected when low on memory. */ private static final ThreadLocal<SoftReference<DateFormat>> cDateFormat = new ThreadLocal<SoftReference<DateFormat>>() { private SoftReference<DateFormat> createValue() { return new SoftReference<DateFormat>(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); } @Override public SoftReference<DateFormat> get() { SoftReference<DateFormat> value = super.get(); if (value == null || value.get() == null) { value = createValue(); set(value); } return value; } }; /** * Accepts strings in ISO 8601 format. This includes the following cases: * <ul> * <li>2009-08-15T12:50:03+01:00</li> * <li>2009-08-15T12:50:03+0200</li> * <li>2010-04-07T04:00:00Z</li> * </ul> */ public static long parseIso8601Date(String dateStr) throws ParseException { // normalize timezone first String timezone = dateStr.substring(19); timezone = timezone.replaceAll(":", ""); if ("Z".equals(timezone)) { // Z indicates UTC, so convert to standard representation timezone = "+0000"; } String cleanedDateStr = dateStr.substring(0, 19) + timezone; DateFormat f = cDateFormat.get().get(); Date d = f.parse(cleanedDateStr); return d.getTime(); } public static String formatIso8601Date(long ms) { DateFormat f = cDateFormat.get().get(); String dateStr = f.format(new Date(ms)); if (dateStr.length() == 24) { dateStr = dateStr.substring(0, 22) + ":" + dateStr.substring(22); } return dateStr; } public static boolean isSameDay(long millisX, long millisY) { return Time.getJulianDay(millisX, 0) == Time.getJulianDay(millisY, 0); } public static CharSequence displayDateRange(Context context, long startMs, long endMs, boolean includeTime) { CharSequence result = ""; final boolean includeStart = startMs > 0L; final boolean includeEnd = endMs > 0L; if (includeStart) { if (includeEnd) { int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; if (includeTime) { flags |= FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME; } result = android.text.format.DateUtils.formatDateRange( context, startMs, endMs, flags); } else { result = displayShortDateTime(context, startMs); } } else if (includeEnd) { result = displayShortDateTime(context, endMs); } return result; } /** * Display date time in short format using the user's date format settings * as a guideline. * * For epoch, display nothing. * For today, only show the time. * Otherwise, only show the day and month. * * @param context * @param timeInMs datetime to display * @return locale specific representation */ public static CharSequence displayShortDateTime(Context context, long timeInMs) { long now = System.currentTimeMillis(); CharSequence result; if (timeInMs == 0L) { result = ""; } else { int flags; if (isSameDay(timeInMs, now)) { flags = FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME; } else { flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; } result = android.text.format.DateUtils.formatDateRange( context, timeInMs, timeInMs, flags); } return result; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/DateUtils.java
Java
asf20
5,036
package org.dodgybits.shuffle.android.core.util; import android.net.Uri; public class CalendarUtils { // We can't use the constants from the provider since it's not a public portion of the SDK. private static final Uri CALENDAR_CONTENT_URI = Uri.parse("content://calendar/calendars"); // Calendars.CONTENT_URI private static final Uri CALENDAR_CONTENT_URI_FROYO_PLUS = Uri.parse("content://com.android.calendar/calendars"); // Calendars.CONTENT_URI private static final Uri EVENT_CONTENT_URI = Uri.parse("content://calendar/events"); // Calendars.CONTENT_URI private static final Uri EVENT_CONTENT_URI_FROYO_PLUS = Uri.parse("content://com.android.calendar/events"); // Calendars.CONTENT_URI public static final String EVENT_BEGIN_TIME = "beginTime"; // android.provider.Calendar.EVENT_BEGIN_TIME public static final String EVENT_END_TIME = "endTime"; // android.provider.Calendar.EVENT_END_TIME public static Uri getCalendarContentUri() { Uri uri; if(OSUtils.osAtLeastFroyo()) { uri = CALENDAR_CONTENT_URI_FROYO_PLUS; } else { uri = CALENDAR_CONTENT_URI; } return uri; } public static Uri getEventContentUri() { Uri uri; if(OSUtils.osAtLeastFroyo()) { uri = EVENT_CONTENT_URI_FROYO_PLUS; } else { uri = EVENT_CONTENT_URI; } return uri; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/core/util/CalendarUtils.java
Java
asf20
1,459
/* * Copyright (C) 2009 Android Shuffle 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 org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.util.TextColours; import org.dodgybits.shuffle.android.list.view.LabelView; import roboguice.inject.InjectView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; public class ColourPickerActivity extends FlurryEnabledActivity implements OnItemClickListener { public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.colours"; @InjectView(R.id.colourGrid) GridView mGrid; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.colour_picker); mGrid.setAdapter(new IconAdapter(this)); mGrid.setOnItemClickListener(this); } @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("colour", String.valueOf(position)); Intent mIntent = new Intent(); mIntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish(); } public class IconAdapter extends BaseAdapter { private TextColours textColours; public IconAdapter(Context context) { textColours = TextColours.getInstance(context); } public View getView(int position, View convertView, ViewGroup parent) { LabelView view; if (convertView instanceof LabelView) { view = (LabelView)convertView; } else { view = new LabelView(ColourPickerActivity.this); view.setText("Abc"); view.setGravity(Gravity.CENTER); } view.setColourIndex(position); view.setIcon(null); return view; } public final int getCount() { return textColours.getNumColours(); } public final Object getItem(int position) { return textColours.getTextColour(position); } public final long getItemId(int position) { return position; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/ColourPickerActivity.java
Java
asf20
2,863